deanWombourne
deanWombourne

Reputation: 38475

implicit cast to primitive in swift

If I have a struct, I can implement ExpressibleByIntegerLiteral to implicitly create an instance of it from an integer literal.

struct MyStruct: ExpressibleByIntegerLiteral {
    let value: Int

    init(integerLiteral value: Int) {
        self.value = value
    }
}


let a: MyStruct = 1

Nice.

Is there a way to do the opposite i.e. implicitly convert from a MyStruct to an Int?

I know that I can implement an init method in an extension on Int to get explicit casting to work, like this:

extension Int {
    init(_ myStruct: MyStruct) {
        self = myStruct.value
    }
}


let b = Int(a)

But is there anything I can do to get this line to compile:

let c: Int = a

Upvotes: 2

Views: 368

Answers (1)

Federico Malagoni
Federico Malagoni

Reputation: 792

The best way to do that in one line is to choose the value property:

let c: Int = a.value

Because you cannot overload the "=" you could check out that:

struct MyStruct: ExpressibleByIntegerLiteral {
    let value: Int

    init(integerLiteral value: Int) {
        self.value = value
    }
}


func += (inout left: Int, right: MyStruct) {
    left = right.value
}


let a: MyStruct = 1;
var c:Int = 0;
c += a

Otherwise you have to create your custom ExpressibleByStructLiteral

Upvotes: 1

Related Questions