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'