Home > Net >  Initialisation in Swift with `=` operator
Initialisation in Swift with `=` operator

Time:11-05

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?

CodePudding user response:

You can initialise from arrays by conforming your type to ExpressibleByArrayLiteral. You need to supply a type that is the type of elements in your array and an initialiser. However, the type can usually be inferred by the compiler from the initialiser, so, in practice, you just need the initialiser

extension simd_packed_float3: ExpressibleByArrayLiteral
{
   init(arrayLiteral: Float...)
   {
       self.init(arrayLiteral)
   }  
}

let x: simd_packed_float3 = [1,2,3]

Should do the trick.

This will obviously only work with the the array literal initialisation, not the simd_float3 version because the syntax requires compiler support. But to initialise from a simd_float3 you can use the following:

let y = simd_packed_float3(simd_float3)

because of your existing initialiser from a simd_float3

  • Related