【问题标题】:Swift force cast Bool to Int error when creating key/value pairs in dictionary在字典中创建键/值对时,Swift 强制将 Bool 强制转换为 Int 错误
【发布时间】:2017-09-25 13:25:02
【问题描述】:

TLDR:尝试创建类型为 [String]/[Any] 的字典,其键包含混合数据类型的数组。然后尝试循环并仅使用键和布尔值创建一个新的字典会导致强制转换错误。

提前感谢您的帮助!

长版:

我需要将 4 个数组(2 个字符串、1 个布尔值、1 个整数)转换为字典。我用字符串类型的键和任何类型的值创建了一个字典,因为我需要一个字符串数组作为键,其余的作为值包含在数组中。像这样:

var dict1: [String: [Any]] = [:]

然后我遍历前面提到的数组并创建键/值对:

编辑:i = 0

//i-1 to match iteration with array position
while i < dict1.count {
    i += 1
    dict1[stringArray1[i-1]] = [intArray[i-1], boolArray[i-1], stringArray2[i-1]]
}

当我打印字典时,它包含正确的键/值对。

现在我需要创建一个字典,其中仅包含 dict1 中的键和键中的 Bool 数组值。所以我设置了一个这样的空数组:

var dict2: [String: [Bool]] = [:]

并尝试像这样创建 KeyValue 对:

for (string, bool) in dict1 {
dict2[string] = bool
}

我收到一条错误消息,提示我需要强制强制转换为 Bool 类型。强制转换为 Bool 类型会产生错误,提示 swift 无法将 Int 转换为 Bool。我尝试将 dict2 中的 Key 的类型更改为 Int 类型,但出现错误说要预测为 Int 类型。这样做说明 Swift 不能强制 Bool 为 Int。

【问题讨论】:

    标签: arrays swift xcode dictionary


    【解决方案1】:

    编辑: 这将帮助您进行投射

    var dict2: [String: [Bool]] = [:]
    var dict1: [String: [Any]] = ["a" : [1], "b" : [true], "c": [false], "d" : ["e"]]
    for (string, bool) in dict1 {
    
        dict2[string] = bool.flatMap({$0 as? Bool})
    }
    

    这是一个示例,如何过滤 [string:any] 字典并将其转换为 [string:bool]

    let dict: [String : Any] = ["a" : 1, "b" : true, "c": false]
    
    let casted = dict.filter{$0.value is Bool}.reduce([String: Bool]()) { (dictionary, nextValue) -> [String: Bool] in
        var mutableDictionary = dictionary
        mutableDictionary[nextValue.key] = nextValue.value as? Bool
        return mutableDictionary
    }
    

    我认为你遵循这个并将 [String:[Any]] 转换为 [String:[Bool]] 不会有问题

    【讨论】:

    • 非常感谢,我认为我遇到的问题是值是数组的位置。我的字典设置为 Key: [int, bool, string]。在您的示例中,我无法弄清楚如何访问值数组中的 bool 值。我可以用 dict2[1] 正常访问它
    • 我的意思是 for 循环中的 bool[1]
    • 好吧,我阅读了一些过滤器,发现我不需要访问数组的特定元素。现在错误是error: cannot subscript a value of type '[String : [Bool]]' with an index of type '(String).Type' (aka 'String.Type')
    • 非常感谢...我的逻辑中有一些错误导致了这些错误。它现在正在工作:)
    猜你喜欢
    • 2015-12-19
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    相关资源
    最近更新 更多