Initialisation with `=` from another type

In Swift the SIMD types can be initialised like this:

let x: simd_float2 = [1,2]

i.e. by passing an array after the = operator.

I wonder how it is made.

E.g. I have this struct (for the reasons I explained elsewhere on this forum):

struct simd_packed_float3{
    var x: Float
    var y: Float
    var z: Float
    
    init(_ xyz: [Float]){
        self.x = xyz[0]
        self.y = xyz[1]
        self.z = xyz[2]
    }
    
    init(_ xyz: simd_float3){
        self.x = xyz[0]
        self.y = xyz[1]
        self.z = xyz[2]
    }
}

Neither of the initialisers of the fake simd struct will work like those of the native types:

let x: simd_packed_float3 = [1,2,3] // Cannot convert value of type '[Int]' to specified type 'simd_packed_float3'
let y: simd_packed_float3 = simd_float3 // Cannot convert value of type 'simd_float3' (aka 'SIMD3<Float>') to specified type 'simd_packed_float3'

Is it possible to make an initialiser accept a value passed with the = operator like it's done with SIMD types?

I think it uses ExpressibleByArrayLiteral

2 Likes

Indeed. Jeremy answered this on StackOverflow initialization - Initialisation in Swift with `=` operator - Stack Overflow

1 Like