Swift之Optional

2017-03-27  本文已影响0人  张义飞

可选类型

var i: Int = 3
var age: Int?
var age: Optional<Int>
public enum Optional<Wrapped> : ExpressibleByNilLiteral
{
    case none
    case some(Wrapped)
    public init(_ some: Wrapped)
}
let number: Int? = Optional.some(10)
let noNumber: Int? = Optional.none

print(noNumber == nil)
//打印结果 true
func callPhone(phone: String?) {
    if let phoneString = phone { 
        print(phoneString)
    } else {
        print("电话号码为空")
    }
}
func callPhone(phone: String?) {
    if phone != nil {
        print(phone!) //这里要强制解包,强制解包一定要确定该值不为nil,不然会造成程序的crash
    } else {
        print("电话号码为空")
    }
}
func callPhone(phone: String?) {
    guard let phoneString = phone else { //这里相当于一个门卫,当phone为空时,就不要往下执行了。
        return
    }
    print(phoneString)
}
func callPhone(phone: String?) {
    let phoneString = phone ?? "15737937865"
    print(phoneString)
}
extension String {
   static func MM<T>(_ optional: T?, detaultValue: T) -> T {
        switch optional {
        case .some(let value):
            return value
        case .none:
            return detaultValue
        }
    }
}
func callPhone(phone: String?) {
    let phoneString = String.MM(phone, detaultValue: "15737937865")
    print(phoneString)
}
callPhone(phone: nil)
//打印结果 15737937865
上一篇下一篇

猜你喜欢

热点阅读