Extensions can contain convenience initializers. For example, a failable initializer for Int
that accepts a NSString
:
extension Int {
init?(_ string: NSString) {
self.init(string as String) // delegate to the existing Int.init(String) initializer
}
}
let str1: NSString = "42"
Int(str1) // 42
let str2: NSString = "abc"
Int(str2) // nil