Convenience initializer on NSString in swift -
when try create convenience initializer on nsstring in swift fails
error: cannot assign value: 'self' immutable self = "(number)"
extension nsstring { public init(for number: int) { self = "\(number)" } }
while similar extension on string works
extension string { public init(for number: int) { self = "\(number)" } }
nsstring
class (a reference type) , string
struct (a value type), , these have different rules initialization.
value types (struct
, enum
) not support inheritance , have simpler initialization rules. in particular, can initialize value assigning self
:
extension string { public init(for number: int) { self = "\(number)" } }
class initialization two-phase process in order prevent property values being accessed before initialized. must follow rules, , 1 of them convenience initializer must delegate initializer of same type (and designated initializer):
extension nsstring { public convenience init(for number: int) { self.init(string: "\(number)") } }
contrary objective-c, swift not (yet?) support "factory initialization", can create , return instance of class or subclass, instead of initiliazing self
.
for details, see initialization in "the swift programming language" reference.
Comments
Post a Comment