Said Sikira
Said Sikira

Reputation: 4543

Get object type from empty Swift Array

Is there a way to get instance of Array element from the empty array? (I need dynamic properties because I use some KVC methods on NSObject)

import Foundation

class BaseClass: NSObject {
    func myFunction() {
        doWork()
    }
}

class Car: BaseClass {
    dynamic var id: Int = 0
}

class Bus: BaseClass {
    dynamic var seats: Int = 0
}

var cars = Array<Car>()

What I need is a vay to get instance of empty Car object from this empty array, for example like this:

var carFromArray = cars.instanceObject() // will return empty Car object

I know that I can use:

var object = Array<Car>.Element()

but this doesn't work for me since I get array from function parameter and I don't know it's element class.

I have tried to write my own type that will do this, and it works, but then I cannot mark it as dynamic since it cannot be represented in Objective C. I tried to write extension of Array

extension Array {
    func instanceObject<T: BaseClass>() -> T? {
        return T()
    }
}

but when I use it, it sometimes throws error fatal error: NSArray element failed to match the Swift Array Element type

Upvotes: 17

Views: 8927

Answers (3)

ma11hew28
ma11hew28

Reputation: 126507

Swift 3: Get an empty array's element type:

let cars = [Car]()                    // []
let arrayType = type(of: cars)        // Array<Car>.Type
let carType = arrayType.Element.self  // Car.Type
String(describing: carType)           // "Car"

Upvotes: 19

lehn0058
lehn0058

Reputation: 20257

This seems to work as of Swift 2.0:

let nsobjectype = cars.dynamicType.Element()
let newCar = nsobjectype.dynamicType.init()

Not sure if it will work in earlier versions.

Upvotes: 1

rintaro
rintaro

Reputation: 51911

Something like this?

let cars = Array<Car>()
let car = cars.dynamicType.Element()

Upvotes: 0

Related Questions