2014-10-23 可失败的构造器
定义(使用?或!):
extension Int {
init?(fromString: String) {
if let i = fromString.toInt() {
// Initialize
self = i
} else {
// return nil, discarding self is implied
return nil
}
}
}
使用(成功返回对象,不成功返回nil):
if let image = NSImage(contentsOfFile: "swift.png") {
// loaded the image successfully
} else {
// could not load the image
}