Stats

Contributors: 3
2016-07-21
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

Initializers in Extensions

Download swift eBook

Example

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