首页 文章

swift中字典键的数组

提问于
浏览
198

尝试使用swift中字典中的键填充数组 .

var componentArray: [String]

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

这将返回以下错误:'AnyObject'与string不同

也试过了

componentArray = dict.allKeys as String

但得到:'String'不能转换为[String]

8 回答

  • 2
    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
        }
    }
    
  • 0

    dict.allKeys 不是字符串 . 它是一个 [String] ,正如错误消息告诉你的那样(当然,假设键都是字符串;这正是你在说的时断言) .

    所以,要么首先输入 componentArray 作为 [AnyObject] ,因为这是在Cocoa API中输入的方式,否则,如果你强制转换 dict.allKeys ,则将其强制转换为 [String] ,因为这就是你输入 componentArray 的方式 .

  • 436

    Swift 3和Swift 4

    componentArray = Array(dict.keys) // for Dictionary
    
    componentArray = dict.allKeys // for NSDictionary
    
  • 36

    使用Swift 3, Dictionary 具有keys属性 . keys 有以下声明:

    var keys: LazyMapCollection<Dictionary<Key, Value>, Key> { get }
    

    仅包含字典键的集合 .

    注意LazyMapCollection可以很容易地映射到带有 Arrayinit(_:)初始化程序的 Array .


    从NSDictionary到[String]

    以下iOS AppDelegate 类代码段显示如何使用 NSDictionary 中的 keys 属性获取字符串数组( [String] ):

    enter image description here

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let string = Bundle.main.path(forResource: "Components", ofType: "plist")!
        if let dict = NSDictionary(contentsOfFile: string) as? [String : Int] {
            let lazyMapCollection = dict.keys
    
            let componentArray = Array(lazyMapCollection)
            print(componentArray)
            // prints: ["Car", "Boat"]
        }
    
        return true
    }
    

    从[String:Int]到[String]

    以更一般的方式,以下Playground代码显示如何使用字符串键和整数值( [String: Int] )的字典中的 keys 属性获取字符串数组( [String] ):

    let dictionary = ["Gabrielle": 49, "Bree": 32, "Susan": 12, "Lynette": 7]
    let lazyMapCollection = dictionary.keys
    
    let stringArray = Array(lazyMapCollection)
    print(stringArray)
    // prints: ["Bree", "Susan", "Lynette", "Gabrielle"]
    

    从[Int:String]到[String]

    以下Playground代码显示如何使用带有整数键和字符串值( [Int: String] )的字典中的 keys 属性获取字符串数组( [String] ):

    let dictionary = [49: "Gabrielle", 32: "Bree", 12: "Susan", 7: "Lynette"]
    let lazyMapCollection = dictionary.keys
    
    let stringArray = Array(lazyMapCollection.map { String($0) })
    // let stringArray = Array(lazyMapCollection).map { String($0) } // also works
    print(stringArray)
    // prints: ["32", "12", "7", "49"]
    
  • 47

    Swift中字典键中的数组

    componentArray = [String] (dict.keys)
    
  • 8

    NSDictionaryClass(pass by reference)
    NSDictionary is class type
    DictionaryStructure(pass by value
    Dictionary is structure of key and value
    ======来自NSDictionary的数组======

    NSDictionary的 allKeysallValues 获取类型为 [Any] 的属性 .
    NSDictionary has get Any properties for allkeys and 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参考 Dictionary's keysvalues 属性 .
    enter image description here

    enter image description here

    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)
    
  • 0

    这个答案将用于swift字典w / String键 . Like this one below .

    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()
    
  • 2

相关问题