2

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
deanWombourne
  • 38,189
  • 13
  • 98
  • 110

1 Answers1

1

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

Federico Malagoni
  • 722
  • 1
  • 7
  • 21