'Initialising a class from a number Swift
A range of basic classes in the foundation framework can be made by simply assigning a basic number to the value where the desired type is known take for example CGFloat:
let a: CGFloat = 42
instead of having to simply use an init like so:
let a = CGFloat(42)
My question is what is this called when a struct or a class implements this behaviour and how can it be implemented for your own classes.
I don't believe this is matter of CGFloat being a type alias and I cannot seem to find a suitable answer for this.
Solution 1:[1]
Your type would need to implement the IntegerLiteralConvertible protocol.
That protocol requires you to implement a constructor of the form:
init(integerLiteral value: Self.IntegerLiteralType) {}
Example:
struct MyCoolStruct {
let value: Int
}
extension MyCoolStruct : IntegerLiteralConvertible {
init(integerLiteral value: Int) {
self.value = value
}
}
let instance: MyCoolStruct = 3
instance.value
Solution 2:[2]
Swift 4/5:
IntegerLiteralConvertible has been renamed in ExpressibleByIntegerLiteral:
extension MyStruct: ExpressibleByIntegerLiteral {
init(integerLiteral value: IntegerLiteralType) {
self.value = value
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Martin Ullrich |
| Solution 2 | Lucio Botteri |
