AFAIK, Swift class
can be assigned by literal value by conform to ExpressibleBy*Literal
.
For example, class A can be assigned by Int
like this, which is similar to implicit construction in C++
class A : ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
required init(integerLiteral value: A.IntegerLiteralType) {
}
}
var a: A = 1
Now, can I extended ExpressibleBy*
protocol to any my custom type ?
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'
B()
is not a literal but a value constructed at runtime; Swift doesn't support custom conversions like C++ does — it uses explicit initializers instead. – BetseybetsyExpressibleBy*Literal
protocols. – Asyut