尝试用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

componentArray = [String] (dict.keys)

其他回答

斯威夫特5

var dict = ["key1":"Value1", "key2":"Value2"]

let k = dict.keys

var a: [String]()
a.append(contentsOf: k)

这对我很有用。

数组从字典键在Swift

componentArray = [String] (dict.keys)
// Old version (for history)
let keys = dictionary.keys.map { $0 }
let keys = dictionary?.keys.map { $0 } ?? [T]()

// New more explained version for our ducks
extension Dictionary {

    var allKeys: [Dictionary.Key] {
        return self.keys.map { $0 }
    }
}
dict.keys.sorted() 

给出[String] https://developer.apple.com/documentation/swift/array/2945003-sorted

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
    }
}