【问题标题】:Cannot assign value of type '[String]' to type 'String?' error Swift无法将类型“[String]”的值分配给类型“String?”错误斯威夫特
【发布时间】:2020-05-13 17:12:55
【问题描述】:

所以我知道很多人之前都问过类似的问题,但是在遵循这些解决方案后我仍然无法解决这个问题。我正在尝试从两个数组中生成一个随机颜色的汽车并将其存储在字典中。我的代码如下:

var colorTypeDictionary = [String:String]()
var colorArray = ["Red", "Black", "Silver", "Yellow", "Orange", "Blue", "Purple", "Pink", "White", "Gray", "Green"]
var carTypeArray = ["Ferarri", "Lamborghini", "Porsche", "Aston Martin", "Maserati"]
colorTypeDictionary[colorArray.randomElement()!] = [carTypeArray.randomElement()!]
print(colorTypeDictionary)

我不断收到错误消息 [carTypeArray.randomElement()!]。它说:无法将类型“[String]”的值分配给类型“String?”。

我尝试将该行转换为字符串,但无法正常工作。有谁知道为什么会这样?

谢谢!

【问题讨论】:

    标签: arrays swift dictionary


    【解决方案1】:

    你只需要去掉方括号:

    colorTypeDictionary[colorArray.randomElement()!] = carTypeArray.randomElement()!
    

    【讨论】:

      【解决方案2】:

      [carTypeArray.randomElement()!] 属于 [String] 类型,您无法将其分配给类型为 String 的字典值,因此请替换

      colorTypeDictionary[colorArray.randomElement()!] = [carTypeArray.randomElement()!]
      

      colorTypeDictionary[colorArray.randomElement()!] = carTypeArray.randomElement()!
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多