【问题标题】:swift 1.2 if loop to switch statementswift 1.2 if 循环切换语句
【发布时间】:2015-10-19 07:45:04
【问题描述】:

我有以下 If-Statment,我想知道如何使用 switch 语句来实现?

我试图将数组中的整数值表示为字符串(例如 1 == "Jan")

func assigningMonthName([Data]) {
    for i in dataset.arrayOfDataStructures {
        if (i.month) == 1 {
            println("Jan")
        }
        else if (i.month) == 2 {
            print("Feb")
        }
        else if (i.month) == 3 {
            print("March")
        }
        else if (i.month) == 4 {
            print("April")
        }
        else if (i.month) == 5 {
            print("May")
        }
        else if (i.month) == 6 {
            print("June")
        }
        else if (i.month) == 7 {
            print("July")
        }
        else if (i.month) == 8 {
            print("August")
        }
        else if (i.month) == 9 {
            print("September")
        }
        else if (i.month) == 10 {
            print("October")
        }
        else if (i.month) == 11 {
            print("November")
        }
        else if (i.month) == 12 {
            print("December")
        }
        else {
            println("Error assigning month name")
        }
    }

}

任何答案将不胜感激:)

【问题讨论】:

  • 只是一个建议,使用NSDate 找到从 Int 获取月份的方法。它会让您的生活比使用if elseswitch case 更轻松

标签: swift if-statement switch-statement


【解决方案1】:

虽然您可以使用 switch,但这本质上只是编写 if-else 的另一种方式,因此您的代码没有大的改进:

switch i.month {
    case 1:
        print("Jan")
    case 2:
        print("Feb")
    ...
}

使用数组怎么样?

let monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "Sept", "October", "November", "December"]
print(monthNames[i.month - 1])

系统实际上已经包含月份名称,它们甚至是本地化的:

let monthNames = NSDateFormatter().monthSymbols;
print(monthNames[i.month - 1])

【讨论】:

  • 谢谢!这很有意义。如果我想插入书面月份,我在名为“monthValue”的数据结构数组中创建了一个空字符串。我尝试了“i.monthName.insert(monthNames[i.month - 1])”但是我得到了错误“字符串类型的不可变值只有名为插入的变异成员”
  • @JessMurray 这是一个有点不同的问题。可能您想创建一个新字符串(例如,使用String(format: ...) 并分配它而不是修改一个已经存在的字符串。
【解决方案2】:

试试这个:

switch i.month {
    case 1:
        print("Jan")
    case 2:
        print("Feb")
    ...
    default:
        print("default value")
}

【讨论】:

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