ios swift中字典键的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26386093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array from dictionary keys in swift
提问by Kyle Goslan
Trying to fill an array with strings from the keys in a dictionary in swift.
试图用 swift 字典中键的字符串填充数组。
var componentArray: [String]
let dict = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Components", ofType: "plist")!)
componentArray = dict.allKeys
This returns an error of: 'AnyObject' not identical to string
这将返回错误:“AnyObject”与字符串不同
Also tried
也试过
componentArray = dict.allKeys as String
but get: 'String' is not convertible to [String]
但得到:'String' 不能转换为 [String]
回答by Andrius Steponavi?ius
Swift 3 & Swift 4
斯威夫特 3 和斯威夫特 4
componentArray = Array(dict.keys) // for Dictionary
componentArray = dict.allKeys // for NSDictionary
回答by Imanou Petit
With Swift 3, Dictionaryhas a keysproperty. keyshas the following declaration:
有了Swift 3,Dictionary就有了keys属性。keys有以下声明:
var keys: LazyMapCollection<Dictionary<Key, Value>, Key> { get }
A collection containing just the keys of the dictionary.
仅包含字典键的集合。
Note that LazyMapCollectionthat can easily be mapped to an Arraywith Array's init(_:)initializer.
请注意,LazyMapCollection这可以很容易地映射到ArraywithArray的init(_:)初始化程序。
From NSDictionaryto [String]
从NSDictionary到[String]
The following iOS AppDelegateclass snippet shows how to get an array of strings ([String]) using keysproperty from a NSDictionary:
以下 iOSAppDelegate类片段展示了如何[String]使用keysa 中的属性获取字符串数组 ( ) 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
}
From [String: Int]to [String]
从[String: Int]到[String]
In a more general way, the following Playground code shows how to get an array of strings ([String]) using keysproperty from a dictionary with string keys and integer values ([String: Int]):
以更一般的方式,以下 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"]
From [Int: String]to [String]
从[Int: String]到[String]
The following Playground code shows how to get an array of strings ([String]) using keysproperty from a dictionary with integer keys and string values ([Int: 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(componentArray = [String] (dict.keys)
) })
// let stringArray = Array(lazyMapCollection).map { String(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
}
}
) } // also works
print(stringArray)
// prints: ["32", "12", "7", "49"]
回答by Santo
Array from dictionary keys in Swift
Swift 中字典键的数组
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)
回答by matt
dict.allKeysis not a String. It is a [String], exactly as the error message tells you (assuming, of course, that the keys areall strings; this is exactly what you are asserting when you say that).
dict.allKeys不是字符串。它是一个[String],正如错误消息告诉您的那样(当然,假设所有键都是字符串;这正是您所说的断言)。
So, either start by typing componentArrayas [AnyObject], because that is how it is typed in the Cocoa API, or else, if you cast dict.allKeys, cast it to [String], because that is how you have typed componentArray.
因此,要么从输入componentArrayas开始[AnyObject],因为这是在 Cocoa API 中输入的方式,或者,如果您强制转换dict.allKeys,则将其强制转换为[String],因为这就是您输入的方式componentArray。
回答by Jitesh Desai
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)
回答by Darshan Panchal
NSDictionaryis Class(pass by reference)
Dictionaryis Structure(pass by value)
====== Array from NSDictionary ======
NSDictionary是类(按引用传递)字典是结构(按值传递)
====== NSDictionary 中的数组 ======

NSDictionary has allKeysand allValuesget properties with
type [Any].![NSDictionary has get [Any] properties for allkeys and allvalues](/static/img/viewimg.png)
NSDictionary 具有allKeys和allValues获取类型为[Any] 的属性。![NSDictionary has get [Any] properties for allkeys and allvalues](/static/img/viewimg.png)
dict.keys.sorted()
====== Array From Dictionary ======
====== 字典中的数组 ======
Apple reference for Dictionary'skeysand valuesproperties.

Array.init<S>(_ s: S) where Element == S.Element, S : Sequence
回答by Jlam
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"]"
that gives [String] https://developer.apple.com/documentation/swift/array/2945003-sorted
给出 [String] https://developer.apple.com/documentation/swift/array/2945003-sorted
回答by Chris Graf
From the official Array Apple documentation:
来自官方Array Apple 文档:
init(_:)- Creates an array containing the elements of a sequence.
init(_:)- 创建一个包含序列元素的数组。
Declaration
宣言
var dict = ["key1":"Value1", "key2":"Value2"]
let k = dict.keys
var a: [String]()
a.append(contentsOf: k)
Parameters
参数
s- The sequence of elements to turn into an array.
s- 要变成数组的元素序列。
Discussion
讨论
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].
您可以使用此初始化程序从符合 Sequence 协议的任何其他类型创建数组……您还可以使用此初始化程序将复杂序列或集合类型转换回数组。例如,字典的 keys 属性不是一个拥有自己存储空间的数组,它是一个仅在访问时才从字典中映射元素的集合,从而节省了分配数组所需的时间和空间。但是,如果您需要将这些键传递给采用数组的方法,请使用此初始化程序将该列表从其类型转换为
LazyMapCollection<Dictionary<String, Int>, Int> to a simple [String].
let dict: [String: Int] = ["hey": 1, "yo": 2, "sup": 3, "hello": 4, "whassup": 5]
回答by Siddharth Kavthekar
Swift 5
斯威夫特 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 }
}
}
This works for me.
这对我有用。
回答by jnblanchard
This answer will be for swift dictionary w/ String keys. Like this one below.
此答案适用于带有字符串键的 swift 字典。像下面这个。
let componentsArray = dict.allKeys()
Here's the extension I'll use.
这是我将使用的扩展名。
##代码##And I'll get all the keys later using this.
稍后我将使用它获取所有密钥。
##代码##
