17

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

2
  • I don't think you can do it. Obviously if the array contains any elements you can pass the array or an element and we can learn its dynamic type. But if you pass the empty array to a function, that function cannot learn what type of thing array would be an array of if it had any elements. Commented Feb 21, 2015 at 16:26
  • I guess I would ask you to think about why you believe you need this degree of introspection. What are you really trying to do? Commented Feb 21, 2015 at 16:26

3 Answers 3

20

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

Something like this?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.