【问题标题】:How to iterate through a dictionary that has multiple values per key in Swift如何遍历 Swift 中每个键具有多个值的字典
【发布时间】:2020-12-27 04:20:57
【问题描述】:

我使用此代码的目标是遍历一个字典,其中键是特定的大学,而这些键的值是大学颜色。当用户通过在文本字段中键入他们的大学来选择他们的大学时,背景会更改为他们的大学颜色。当我只使用一种颜色迭代字典时工作完美,但现在我已经引入了第二种颜色,我的代码不断出现错误“For-in 循环需要'[UIColor]'符合'Sequence'”,这是我的代码。我会很感激任何帮助

对于我的字典,我使用 Color Literal 轻松选择颜色:

var collegeDict = ["UCLA": [#colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1), #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)], "Stanford": [#colorLiteral(red: 0.3098039329, green: 0.01568627544, blue: 0.1294117719, alpha: 1), #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)]]

这是出现错误的迭代器:

    @IBAction func Button1Pressed(_ sender: Any) {
        for (key, colors) in collegeDict {
            for (primaryColor, secondaryColor) in colors {
            if collegeName == textField1.text {
                self.View1.backgroundColor = primaryColor
                self.Button1.backgroundColor = primaryColor

【问题讨论】:

    标签: swift loops dictionary for-in-loop


    【解决方案1】:

    for (primaryColor, secondaryColor) in colors 实际上是(index, element) 语法,但是你必须添加.enumerated()

    for (primaryColor, secondaryColor) in colors.enumerated()
    

    尽管如此,即使使用enumerated(),语法也毫无意义。

    等等,这确实(某种)有意义

    @IBAction func Button1Pressed(_ sender: Any) {
        for (_, colors) in collegeDict {
            for (index, color) in colors.enumerated() {
            if collegeName == textField1.text {
                switch index {
                    case 0: self.View1.backgroundColor = color
                    case 1: self.Button1.backgroundColor = = color
                    default: break
                }
                
    

    这是严肃的解决方案:

    colors是一个数组,可以通过索引订阅获取第一个和第二个元素

     @IBAction func Button1Pressed(_ sender: Any) {
        for (_, colors) in collegeDict {
            if collegeName == textField1.text {
                self.View1.backgroundColor = colors[0]
                self.Button1.backgroundColor = colors[1]
    

    其实与循环无关的比较if collegeName == textField1.text {也是没有意义的。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多