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
Declaring an array in Swift is quite easy, and it then allows all the elements and values to get accessed and manipulated easily. There are two ways to declare an array which are as follows: One way is to initialize the variable with an empty array. Another way is to use the automatic type inference.
In order to check if an object is of given type in Swift, you can use the type check operator is. Given an example class Item , you can check if the object is of its type like that: Same applies to built-in data types in Swift. For example, if you’d like to check if given object is a String or Int:
1.4 Wrong Usage Of Swift Array. Use an empty array variable without specify array data type. // declare an empty array but do not specify the array element data type. Below is the correct usage. Use an array variable which is not initialized.
For example: You can create an empty array by specifying the Element type of your array in the declaration. For example: If you need an array that is preinitialized with a fixed number of default values, use the Array (repeating:count:) initializer.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With