2016-07-04 52 views
-1

它有效,但我认为不够好。是否有可能在if-let构造之外使用readLine()?我只是发现范围非常有限,不相信我可以使用此方法从命令行使用此方法传递参数。任何人都可以提出更好的方法解决这个问题?我该如何改进这个Swift 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") 
     } 
    } 

回答

0

readLine()返回String?,这是nil如果没有更多的输入(EOF这是在Xcode CTRL-d)。您需要以某种方式解开它,并且if let声明对此非常合适。

参数无关使用标准输入(readLine()),你可以得到的参数是这样,而不是:

Process.arguments // type [String]