Swift - 字面量
2022-04-25 本文已影响0人
aven_kang

字面量协议

字面量协议的应用
extension Int : ExpressibleByBooleanLiteral,ExpressibleByStringLiteral {
public init(booleanLiteral value: BooleanLiteralType) {
self = value ? 1 : 0
}
public init(stringLiteral value: StringLiteralType) {
if Int(value) == nil {
self = 1000
}else {
self = Int(stringLiteral: value)
}
}
}
var num:Int = true
var num2:Int = "asdfdf"
print(num2) // 1000
可以将一个bool值赋值给Int类型,因为我们给Int这个字面量协议扩展了bool字面量的方法,所以可以这么玩
上面的方法中,把asdfdf赋值给num2这个Int变量,按照正常来讲,是赋值不成功的,但是现在打印返回1000,这个字面可以更改的还有很多,同志们自行探索了

