为了更熟悉 Swift,我将一个类的开头放在一起,该类旨在表示人类游戏角色的需求。现在它跟踪水和食物变量。这些变量由接受 NSStrings(或 Strings,我都尝试过)并通过 switch 语句运行该参数的函数更改。
import Foundation
class human {
var food:Int = 0
var water:Int = 0
func setFood(str:NSString) {
var generic:String = "The \(str) filled your Food Hole with "
switch str {
case "chicken":
food += 10
println(generic + "10 points.")
case "bread":
food += 5
println(generic + "5 points")
case "beans":
food += 10
println(generic + "10 points")
default:
if food < 30 {
food += 2
println("That wasn't really food...Here's two pity points")
} else {
println("Stop eating garbage")
}
}
}
func setWater(str:NSString) {
var generic:String = "The \(str) filled your Water Hole with "
switch str {
case "water":
water += 30
println(generic + "30 points.")
case "mud water":
water += 10
println(generic + "10 points. And you're gross.")
case "radioactive coolant":
water += 5
println("Okay so that technically worked but wasn't a good idea")
default:
println("Don't put that in your mouth")
}
}
}
以下是从控制台获取输入的代码:
var hu = human()
hu.setFood("bread")
println(hu.food) //this works fine
let keyboard = NSFileHandle.fileHandleWithStandardInput()
while (keyboard) {
println("What do you eat or drink?")
var input = NSString(data: keyboard.availableData, encoding: NSUTF8StringEncoding)
hu.setFood(input)
println(input) //check input to confirm it even holds a string
}
setFood
带有硬编码字符串的第一个函数可以正常工作。匹配正确的大小写,正确更新变量,打印文本等。我println
在最后有一个语句,以便我可以看到input
变量实际包含的内容,并且它似乎包含某种字符串。
具体问题是 switch 语句在匹配来自控制台的输入时总是选择默认情况。在控制台中输入一个像这样的有效字符串chicken
将与 switch 语句的小鸡大小写不匹配。
这是编码问题吗?我尝试过 NSString、String,我尝试过强制转换input
为 String,使用一种lowercase
方法来查看是否“清理”了一些东西。我查看了 Xcode 中的库参考,寻找任何可能给我想要的东西但没有任何运气的东西。我显然是 Swift 的初学者,而且我从未编写过任何 Objective-C。我希望我没有遗漏一些明显的东西。谢谢。