Blake Lockley
Blake Lockley

Reputation: 2961

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.

Upvotes: 2

Views: 47

Answers (2)

Lucio Botteri
Lucio Botteri

Reputation: 140

Swift 4/5:

IntegerLiteralConvertible has been renamed in ExpressibleByIntegerLiteral:

extension MyStruct: ExpressibleByIntegerLiteral {
    init(integerLiteral value: IntegerLiteralType) {
        self.value = value
    }
}

Upvotes: 0

Martin Ullrich
Martin Ullrich

Reputation: 100741

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

Upvotes: 1

Related Questions