如何改进这个Swift readLine代码?

时间:2016-07-04 14:09:56

标签: swift input console-application

它有效,但我认为不够好。是否可以在if-let构造之外使用readLine()???我发现范围非常有限,并且不相信我可以使用此方法从命令行使用此参数传递参数。任何人都可以建议更好地解决这个问题吗?

    import Foundation

    print("\nTemperature Conversion\n")
    print("What is your current Temperature Unit?\n ")
    print("Valid options are f or F for Fahrenheit, c or C for Celsius: \n")

    if var  temp = readLine() {
        switch temp{
        case "c","C":
            print("And the temperature: ")
            if var  degrees = readLine() {
                var fahr = (5 * Float(degrees)! * 1.8 + 32)
                print("\(degrees) Degrees is equal to \(fahr) degrees Fahrenheit. \n")
            } else {
                print("You entered an invalid temperature")
            }
        case "f","F":
            print("Fahrenheit")
            if var degrees = readLine() {
                var celsius = (5 * Float(degrees)! - 32) / 9;
                print("\(degrees) Degrees is equal to \(celsius) degrees Fahrenheit. \n")
            } else {
                print("You entered an invalid temperature")
            }
        default:
            print("Not a valid Temperature unit")
        }
    }

1 个答案:

答案 0 :(得分:0)

readLine()会返回String?,如果没有更多输入(EOF是Xcode中的CTRL-D),则为nil。你需要以某种方式展开它,if let声明是完美的。

参数与标准输入(readLine())无关,你可以得到这样的参数:

Process.arguments // type [String]