来自swift中字典键的数组

Kyl*_*lan 235 arrays xcode dictionary ios swift

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

var componentArray: [String]

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

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

也试过了

componentArray = dict.allKeys as String 
Run Code Online (Sandbox Code Playgroud)

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

And*_*ius 504

Swift 3和Swift 4

componentArray = Array(dict.keys) // for Dictionary

componentArray = dict.allKeys // for NSDictionary
Run Code Online (Sandbox Code Playgroud)

  • 自Xcode 7.0 beta 6以来的数组(dict.keys) (7认同)
  • dict.map { $0.key } (6认同)

Ima*_*tit 51

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

var keys: LazyMapCollection<Dictionary<Key, Value>, Key> { get }
Run Code Online (Sandbox Code Playgroud)

仅包含字典键的集合.

请注意,LazyMapCollection这可以很容易地映射到Arraywith Arrayinit(_:)初始化程序.


NSDictionary[String]

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

在此输入图像描述

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
}
Run Code Online (Sandbox Code Playgroud)

[String: Int][String]

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

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"]
Run Code Online (Sandbox Code Playgroud)

[Int: String][String]

以下Playground代码显示如何[String]使用keys带有整数键和字符串值([Int: 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"]
Run Code Online (Sandbox Code Playgroud)


San*_*nto 39

Swift中字典键的数组

componentArray = [String] (dict.keys)
Run Code Online (Sandbox Code Playgroud)


mat*_*att 8

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

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


Sid*_*kar 6

雨燕5

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

let k = dict.keys

var a: [String]()
a.append(contentsOf: k)
Run Code Online (Sandbox Code Playgroud)

这对我有用。


Meo*_*ute 6

您可以像这样使用 dictionary.map:

let myKeys: [String] = myDictionary.map{String($0.key) }
Run Code Online (Sandbox Code Playgroud)

解释:Map 遍历 myDictionary 并接受每个键值对为 $0。从这里您可以获得 $0.key 或 $0.value。在尾随闭包 {} 内,您可以转换每个元素并返回该元素。既然你想要 $0 并且你想要它作为一个字符串,那么你可以使用 String($0.key) 进行转换。您将转换后的元素收集到一个字符串数组中。


小智 5

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
    }
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*raf 5

来自Apple Array官方文档:

\n\n

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

\n\n

宣言

\n\n
Array.init<S>(_ s: S) where Element == S.Element, S : Sequence\n
Run Code Online (Sandbox Code Playgroud)\n\n

参数

\n\n

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

\n\n

讨论

\n\n
\n

您可以使用此初始值设定项从符合序列协议的任何其他类型创建数组...您还可以使用此初始值设定项将复杂序列或集合类型转换回数组。例如,字典的keys属性是一个有自己存储的数组,它是一个集合,仅当访问字典时才映射其元素,节省分配数组所需的时间和空间。但是,如果您需要将这些键传递给采用数组的方法,请使用此初始值设定项将该列表从其类型转换为LazyMapCollection<Dictionary<String, Int>, Int> to a simple [String].

\n
\n\n
func cacheImagesWithNames(names: [String]) {\n    // custom image loading and caching\n }\n\nlet namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,\n        "Gold": 50, "Cerise": 320]\nlet colorNames = Array(namedHues.keys)\ncacheImagesWithNames(colorNames)\n\nprint(colorNames)\n// Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"\n
Run Code Online (Sandbox Code Playgroud)\n