无法在Swift中使用AnyObject

时间:2014-07-21 10:06:12

标签: ios objective-c swift

我不明白Swift中的AnyObject类型应该如何工作。我正在我的Swift代码中将Plist文件加载到NSDictionary实例中(此处未显示)。后来我尝试在UIPickerView中使用Plist文件中的一些值:

// Trying to extract the first fruit
let fruitKeys = fruits.allKeys
let fruitKey = fruitKeys[0]

// This is another NSDictionary
let fruit = fruits.objectForKey(fruitKey)

// Getting a property of a fruit                
let nutritions = fruit.objectForKey("nutritions") 
let nutritionKeys = nutritions.allKeys

但是,我无法通过拨打nutritions.allKeys获取水果的钥匙。我得到Could not find member allKeys。但是,我误解了文档的哪一部分?我读到你可以在AnyObject的实例上调用任何目标c方法。为什么我需要施放或其他魔法呢?

我应该把所有东西都投入真实的类型吗?或者我应该使用AnyObject ??

1 个答案:

答案 0 :(得分:1)

简而言之,是的,您通常希望转换为您定义的类型,这是我将如何编写它:

let fruitKeys = fruits.allKeys as [String]
let fruitKey = fruitKeys[0]

let fruit = fruits[fruitKey] as NSDictionary

let nutritions = fruit["nutritions"] as NSDictionary
let nutritionKeys = nutritions.allKeys

正如我在评论中已经提到的,对代码的可能更改将是:

let fruitKeys = fruits.allKeys
let fruitKey = fruitKeys[0]

let fruit = fruits.objectForKey(fruitKey)

let nutritions = fruit.objectForKey("nutritions")
let nutritionKeys : AnyObject? = nutritions.allKeys

我省略了每个值的向下转换因为我认为它没有意义,所以你可能会遇到一些警告,但它会起作用。