在我的课程中,我有以下方法,该方法返回其中所有属性的名称数组:
func getListOfProperties() -> Array<Any>
{
var count : UInt32 = 0
let classToInspect = NSURL.self
let properties : UnsafePointer <objc_property_t> = class_copyPropertyList(classToInspect, &count)
var propertyNames : Array<String> = []
let intCount = Int(count)
for var i = 0; i < intCount; i++ {
let property : objc_property_t = properties[i]
let properyName = NSString(UTF8String: property_getName(property))
propertyNames += properyName
}
free(properties)
return propertyNames
}
我还有一个方法,我试图在for循环中使用valueForKey来操作这些属性:
func doSomethingWithPropertyName()
{
var someProperty = self.valueForKey("someProperty") // this is fine for compiler :-)
var properties = self.getListOfProperties()
for (index, propertyName) in enumerate(properties)
{
var currentProperty = self.valueForKey(propertyName) // compiler complains : 'protocol <>' is not convertible to 'String':-(
}
}
问题是 -
如果我尝试在for循环中使用valueForKey访问属性, 编译器抱怨 - 协议&lt;&gt;&#39;不能转换为&#39; String&#39;
注意:如果我尝试在for循环之外做同样的事情,它可以正常工作。
任何线索?
答案 0 :(得分:1)
问题是propertyName被定义为Any
。 Swift中没有隐式转换。
您必须将propertyName强制转换为String:
for (index, propertyName) in enumerate(properties) {
if let stringPropertyName = propertyName as? String {
var currentProperty = self.valueForKey(stringPropertyName)
}
}
或者您可以让getListOfProperties
方法返回一个字符串数组:
func getListOfProperties() -> Array<String>