数组从字典键在swift

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

218448 次浏览

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

因此,要么从将componentArray输入为[AnyObject]开始,因为这是在Cocoa API中键入它的方式,要么,如果您转换了dict.allKeys,则将其转换为[String],因为这是您键入componentArray的方式。

数组从字典键在Swift

componentArray = [String] (dict.keys)

Swift 3 &斯威夫特4

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


componentArray = dict.allKeys // for NSDictionary

在Swift 3中,Dictionary有一个keys属性。keys有以下声明:

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

仅包含字典键的集合。

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


NSDictionary[String]

下面的iOS AppDelegate类片段展示了如何使用keys属性从NSDictionary中获取字符串数组([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代码以更通用的方式展示了如何使用keys属性从包含字符串键和整数值的字典([String: Int])中获取字符串数组([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代码展示了如何使用keys属性从包含整型键和字符串值的字典([Int: String])中获取字符串数组([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"]
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
}
}

这个答案将用于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 is class type 字典结构(通过值传递) Dictionary is structure of key and value ======数组从NSDictionary ======

NSDictionary有allKeysallValues get属性with 类型(任何).NSDictionary has get [Any] properties for allkeys and allvalues . NSDictionary has get [Any] properties for allkeys and allvalues . < / p >
  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)

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

苹果引用字典的 属性。 enter image description here < / p >

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

来自官方Array Apple文档:

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

宣言

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

参数

<年代trong>年代 -要转换为数组的元素序列。

讨论

您可以使用此初始化式从符合Sequence协议的任何其他类型创建一个数组…还可以使用此初始化式将复杂序列或集合类型转换回数组。例如,字典的keys属性不是一个有自己存储空间的数组,它是一个集合,只有当它们被访问时才从字典中映射它们的元素,从而节省了分配数组所需的时间和空间。但是,如果需要将这些键传递给接受数组的方法,则使用此初始化式将该列表从其类型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"]"

斯威夫特5

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


let k = dict.keys


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

这对我很有用。

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

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