问题
I'm trying to assign a value to a let in Swift 1.2 and its causing a compile error. On Apple's blog it says that this is now allowed
The new rule is that a let constant must be initialized before use (like a var), and that it may only be initialized, not reassigned or mutated after initialization.
So in my code i made a let a property in my class
class SampleClass: NSObject {
let idOfSomething:String
public func createSomething(idString:String)-> Void {
self.idOfSomething = idString
}
}
After I get this far the compiler complains that I cannot assign to self
here is a snapshot of the error, anyone understand what i'm doing wrong?
回答1:
The statement you're referring to is valid for local and global variables, not for properties, for which the old rule applies: they must all be initialized either inline or in an initializer (unless it's a mutable optional property, which is automatically initialized to nil).
回答2:
What you're doing was never legal, and it still isn't. This is a let property. You cannot assign to it; it is a constant, meaning that its value can never change.
The only way you can give it its initial value (the only value it will ever have) is as its default or during initialization, i.e. in an initializer — and public func createSomething is not an initializer.
来源:https://stackoverflow.com/questions/29564272/swift-1-2-assigning-let-after-initialization