Stats

Contributors: 3 Thursday, July 21, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

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