【问题标题】:Swift Console input not case sensitiveSwift 控制台输入不区分大小写
【发布时间】:2017-03-28 20:36:50
【问题描述】:

我刚开始学习 Swift3。一开始,我编写了一个用于转换单位的控制台程序。我有一个控制台输入流

let typ = readLine()

当然我得到了完全相同的字符串,但我在 if 语句中使用了它。现在我的问题我不想检查它是否区分大小写我只想要纯字符串。 这是我使用的 if 构造:

if typ == unitA {
    print("foo")
    //Some Code
}else if typ == unitB{
    print("super foo")
    //Some Code
}else{
    print("Invalid input :/")
}

谢谢你:D

【问题讨论】:

    标签: swift macos if-statement case-sensitive


    【解决方案1】:

    在比较之前只需将输入小写即可。此外,switch 语句可以极大地清理if/if else/else 阶梯。

    guard let input = readLine() else {
        fatalError("No input recieved")
    }
    
    switch input.lowercased() {
        case unitA: print("foo")
        case unitB: print("super foo")
        default: print("Invalid input :/")
    }
    

    【讨论】:

    【解决方案2】:

    如果您想比较不区分大小写的字符串,您可以使用caseInsensitiveCompare 参见answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      相关资源
      最近更新 更多