我目前正在研究 swift 4 中类型转换和检查的基础知识。我在 Apple Developer 书中找到了一个示例,我需要一些帮助。
他们有一个练习来创建一个 Any 类型的字典,然后解开循环遍历字典的值。给定的解决方案显示了 for 循环,其中值在括号中并且每个值都被展开。有人可以解释显示的解决方案吗?还有另一种(简单的)方法来解决这个问题吗?书中没有足够的信息。
let anythingAndEverything: [String: Any] = ["FirstBool": true,
"FalseBool": false, "Unknown": "90", "AnInteger": 12, "ADouble": 1.1]
print(anythingAndEverything)
var total: Double = 0
for (_, value) in anythingAndEverything {
if let value = value as? Bool {
if value {
total += 2
} else {
total -= 3
}
} else if let value = value as? Double {
total += value
} else if let value = value as? Int {
total += Double(value)
} else if let value = value as? String {
total += 1
}
}
print(total)
非常感谢您的提前帮助:-)
最佳答案
Dictionary
符合Collection
,后者符合Sequence
。这意味着可以使用 for...in 循环遍历字典。
在Dictionary
的定义中,有这样一行:
public typealias Element = (key: Key, value: Value)
这意味着“在称为字典的集合中,它包含(key: Key, value: Value)
类型的元素”。这意味着您将获得 (key: Key, value: Value)
作为 in
之前的变量类型:
for element in someDictionary {
// element is of type (key: Key, value: Value)
}
因为 element
是一个元组,我们实际上可以通过这样做来打开元组:
for (key, value) in someDictionary {}
在您的特定情况下,我们不需要 key
位,所以我们写 _
来表示“丢弃它”:
for (_, value) in someDictionary {}
解决这个问题的另一种方法是使用reduce
。不过,我不会说这一定更简单:
total = anythingAndEverything.reduce(0.0) { (x, y) -> Double in
if let value = y.value as? Bool {
if value {
return x + 2
} else {
return x - 3
}
} else if let value = y.value as? Double {
return x + value
} else if let value = y.value as? Int {
return x + Double(value)
} else if let value = y.value as? String {
return x + 1
} else {
return x
}
}
关于swift - 铸型及检验查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47301726/