swift - 铸型及检验查询

标签 swift types casting

我目前正在研究 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/

相关文章:

arrays - swift 字典 : Get values as array

swift - 找不到 Find : Elements matching predicate '""IN identifiers' from input 的匹配项

c# - ASP.net c# 将 int 解析为日期时间

python - Pandas 将 NULL 读取为 NaN float 而不是 str

python - 如何隐式确定 python 中的数据框列类型? (隐式转换)

java - 能够将 ArrayList<Set<String>> 转换为 ArrayList<String> String 而不会出现类转换异常

java - 为什么在采用 int 参数的 BufferedOutputStream write 方法中将 int 转换为 byte?

ios - 如何快速将本地视频转换为base64?

arrays - Matlab 向量查找的 Swift 版本?

Oracle %TYPE : when one var, 两个表,如何定义?