Ilja Kosynkin Ilja Kosynkin - 1 month ago 15
Swift Question

Swift: create object from primitive value

I'm not entirely sure that what I want to do is possible to implement currently, however I hope that it is.

Basically, I would like to have some mechanism for a bit shorter object creation for primitive. Let me explain. Consider we have some kind of wrapper around Int:

class Wrapper {
var value: Int = 0

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


And then instead of creating object with init, i.e:

let wrapper = Wrapper(value: -1)


I would like to do something like this:

let wrapper: Wrapper = -1


Or:

var array = [Wrapper]()
array.append(-1)


It would short declarations quite heavily, especially in case with arrays.

Interesting note: I've tested code above with CGFloat i.e:

let val: CGFloat = 0.0
var array = [CGFloat]()
array.append(0.0)


and all seems to be working fine. However I'm not entirely sure that there is way in language that allow to create such behaviour for custom object and it's why I'm asking about it basically. I've reviewed sources of CGFloat, but didn't saw anything that seems to be related to functionality that i want to achieve (beside NativeType alias may be, but I didn't understand how it would work).

Answer

Like this:

class Wrapper : ExpressibleByIntegerLiteral {
    var value: Int = 0

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

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

And now you can say:

let w : Wrapper = 1