xcode 从空的 Swift 数组中获取对象类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28647858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get object type from empty Swift Array
提问by Said Sikira
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
)
有没有办法从空数组中获取数组元素的实例?(我需要dynamic
属性,因为我在 上使用了一些 KVC 方法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:
我需要的是从这个空数组中获取空 Car 对象实例的方法,例如:
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
我曾尝试编写自己的类型来执行此操作,并且它可以工作,但是我无法将其标记为dynamic
因为它无法在 Objective C 中表示。我尝试编写 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
但是当我使用它时,它有时会引发错误 fatal error: NSArray element failed to match the Swift Array Element type
回答by ma11hew28
Swift 3: Get an empty array's element type:
Swift 3:获取空数组的元素类型:
let cars = [Car]() // []
let arrayType = type(of: cars) // Array<Car>.Type
let carType = arrayType.Element.self // Car.Type
String(describing: carType) // "Car"
回答by lehn0058
This seems to work as of Swift 2.0:
这似乎适用于 Swift 2.0:
let nsobjectype = cars.dynamicType.Element()
let newCar = nsobjectype.dynamicType.init()
Not sure if it will work in earlier versions.
不确定它是否适用于早期版本。
回答by rintaro
Something like this?
像这样的东西?
let cars = Array<Car>()
let car = cars.dynamicType.Element()