AFAIK,Swift
class
可以通过符合 ExpressibleBy*Literal
来按字面值赋值。
例如A类可以这样通过
Int
来赋值,类似于C++
中的隐式构造
class A : ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
required init(integerLiteral value: A.IntegerLiteralType) {
}
}
var a: A = 1
现在,我可以将
ExpressibleBy*
协议扩展到任何我的自定义类型吗?
protocol ExpressibleByMyTypeLiteral {
associatedtype MyType
init(literal value: Self.MyType)
}
class B {
}
class A : ExpressibleByIntegerLiteral, ExpressibleByMyTypeLiteral {
//ExpressibleByIntegerLiteral
typealias IntegerLiteralType = Int
required init(integerLiteral value: A.IntegerLiteralType) {
}
//ExpressibleByMyTypeLiteral
typealias MyType = B
required init(literal value: A.MyType) {
}
}
var a: A = 1
var aMyType: A = B() //Compiler Error: Cannot convert value of 'B' to specified type 'A'
使用自定义运算符:
postfix operator |
postfix func |(context: Foo) -> Bar {
Bar(context)
}
let foo = Foo()
let aMyType: Bar = foo|
//Even with generics
postfix func |<C, T>(context: C) -> T
查看示例此处
/// Obtain
///
/// let object: T = context|
///
postfix func |<C, T: Obtain>(context: C) -> T {
Wand.attach(to: context).obtain()
}