尝试用swift字典中的键字符串填充数组。

var componentArray: [String]

let dict = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Components", ofType: "plist")!)
componentArray = dict.allKeys

这将返回一个错误:'AnyObject'与string不相同

也试过

componentArray = dict.allKeys as String 

but get: 'String'不能转换为[String]


当前回答

这个答案将用于swift字典w/ String键。就像下面这个。

let dict: [String: Int] = ["hey": 1, "yo": 2, "sup": 3, "hello": 4, "whassup": 5]

这是我将使用的扩展。

extension Dictionary {
  func allKeys() -> [String] {
    guard self.keys.first is String else {
      debugPrint("This function will not return other hashable types. (Only strings)")
      return []
    }
    return self.flatMap { (anEntry) -> String? in
                          guard let temp = anEntry.key as? String else { return nil }
                          return temp }
  }
}

我稍后会用这个得到所有的键。

let componentsArray = dict.allKeys()

其他回答

NSDictionary是类(通过引用传递) 字典是结构(按值传递) ======数组从NSDictionary ======

NSDictionary有allKeys和allValues获取属性 类型(任何)。

  let objesctNSDictionary = 
    NSDictionary.init(dictionary: ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"])
            let objectArrayOfAllKeys:Array = objesctNSDictionary.allKeys
            let objectArrayOfAllValues:Array = objesctNSDictionary.allValues
            print(objectArrayOfAllKeys)
            print(objectArrayOfAllValues)

======数组从字典======

字典的键和值属性的Apple引用。

let objectDictionary:Dictionary = 
            ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
    let objectArrayOfAllKeys:Array = Array(objectDictionary.keys)          
    let objectArrayOfAllValues:Array = Array(objectDictionary.values)
    print(objectArrayOfAllKeys)
    print(objectArrayOfAllValues)

来自Array Apple官方文档:

init(_:) -创建一个包含序列元素的数组。

宣言

Array.init<S>(_ s: S) where Element == S.Element, S : Sequence

参数

s -要转换为数组的元素序列。

讨论

You can use this initializer to create an array from any other type that conforms to the Sequence protocol...You can also use this initializer to convert a complex sequence or collection type back to an array. For example, the keys property of a dictionary isn’t an array with its own storage, it’s a collection that maps its elements from the dictionary only when they’re accessed, saving the time and space needed to allocate an array. If you need to pass those keys to a method that takes an array, however, use this initializer to convert that list from its type of LazyMapCollection<Dictionary<String, Int>, Int> to a simple [String].

func cacheImagesWithNames(names: [String]) {
    // custom image loading and caching
 }

let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,
        "Gold": 50, "Cerise": 320]
let colorNames = Array(namedHues.keys)
cacheImagesWithNames(colorNames)

print(colorNames)
// Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"

字典allKeys不是一个字符串。它是一个[String],就像错误消息告诉你的那样(当然,假设键都是字符串;这正是你所说的)。

所以,要么首先将componentArray键入为[AnyObject],因为这是它在Cocoa API中键入的方式,要么,如果你强制转换dict。allKeys,将它转换为[String],因为这是你键入componentArray的方式。

你可以用字典。这样的地图:

let myKeys: [String] = myDictionary.map{String($0.key) }

解释: Map遍历myDictionary并接受每个键和值对为$0。从这里你可以得到0美元。Key或$0.value。在后面的闭包{}中,可以转换每个元素并返回该元素。因为你想要$0,你想要它作为一个字符串,然后你转换使用string ($0.key)。将转换后的元素收集到字符串数组中。

extension Array {
    public func toDictionary<Key: Hashable>(with selectKey: (Element) -> Key) -> [Key:Element] {
        var dict = [Key:Element]()
        for element in self {
            dict[selectKey(element)] = element
        }
        return dict
    }
}