Dav*_*son 13 arrays dictionary ios swift
我有2个数组:
var identic = [String]()
var linef = [String]()
Run Code Online (Sandbox Code Playgroud)
我已经附上了数据.现在出于可用性目的,我的目标是将它们全部组合成具有以下结构的字典
FullStack = ["identic 1st value":"linef first value", "identic 2nd value":"linef 2nd value"]
Run Code Online (Sandbox Code Playgroud)
我一直在网上浏览,无法找到一个可行的解决方案.
任何想法都非常感谢.
谢谢!
Mat*_*ues 30
从Xcode 9.0开始,您可以简单地执行以下操作:
var identic = [String]()
var linef = [String]()
// Add data...
let fullStack = Dictionary(uniqueKeysWithValues: zip(identic, linef))
Run Code Online (Sandbox Code Playgroud)
如果您的密钥不能保证是唯一的,请改用:
let fullStack =
Dictionary(zip(identic, linef), uniquingKeysWith: { (first, _) in first })
Run Code Online (Sandbox Code Playgroud)
要么
let fullStack =
Dictionary(zip(identic, linef), uniquingKeysWith: { (_, last) in last })
Run Code Online (Sandbox Code Playgroud)
文档:
https://developer.apple.com/documentation/swift/dictionary/2894798-init
https://developer.apple.com/documentation/swift/dictionary/2892961-init
Vat*_*not 29
这听起来像是一份工作enumerated()!
var arrayOne: [String] = []
var arrayTwo: [String] = []
var dictionary: [String: String] = [:]
for (index, element) in arrayOne.enumerated() {
dictionary[element] = arrayTwo[index]
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您想要专业方法,请使用扩展名:
extension Dictionary {
public init(keys: [Key], values: [Value]) {
precondition(keys.count == values.count)
self.init()
for (index, key) in keys.enumerate() {
self[key] = values[index]
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑: enumerate() → enumerated()(Swift 3→Swift 4)
Abi*_*ern 20
一种稍微不同的方法,它不需要数组具有相同的长度,因为该zip函数将安全地处理它.
extension Dictionary {
init(keys: [Key], values: [Value]) {
self.init()
for (key, value) in zip(keys, values) {
self[key] = value
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想更安全并确保每次都选择较小的数组(如果第二个数组小于第一个数组,那么您不会崩溃),那么执行以下操作:
var identic = ["A", "B", "C", "D"]
var linef = ["1", "2", "3"]
var Fullstack = [String: String]()
for i in 0..<min(linef.count, identic.count) {
Fullstack[identic[i]] = linef[i]
}
print(Fullstack) // "[A: 1, B: 2, C: 3]"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9780 次 |
| 最近记录: |