class ViewController: UIViewController {
@IBOutlet weak var inputField: UITextField!
@IBOutlet weak var output: UITextView!
var guesses : UInt = 0
var number : UInt32 = 0
var gameOver = false
let MAX_GUESSES : UInt = 8
@IBAction func guess(sender: UIButton) {
var possibleGuess : Int? = inputField.text.toInt()
if let guess = possibleGuess {
// possibleGuess exists!
} else {
consoleOut("Please input a valid number!\n")
clearInput()
}
if UInt32(guess) > Int(number) {
consoleOut("\(guess): You guessed too high!\n")
++guesses
} else if UInt32(guess) < number {
consoleOut("\(guess): You guessed too low!\n")
++guesses
} else {
consoleOut("\n\(guess): You win!\n")
consoleOut("Go again? (Y)")
guesses = 0
gameOver = true
}
clearInput()
if (guesses == MAX_GUESSES) {
consoleOut("\nYou lose :(\n")
consoleOut("Go again? (Y)")
guesses = 0
gameOver = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
number = generateNewNumber()
consoleOut("Gondolkodom egy számot...\n")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func consoleOut(text : String) {
output.text = output.text + text
}
func generateNewNumber () -> UInt32 {
return arc4random_uniform(100)
}
func clearInput() {
inputField.text = ""
}
}这是我使用的代码,我在if UInt32(guess) > Int(number) {上得到了错误消息。我真的挺不过去的。
(swift)错误:无法调用“具有类型的参数列表”(UInt32,@lvalue UInt32)‘’
发布于 2014-10-09 05:33:33
*这并不完全是您的问题,但它可能会向您展示一种绕过它的方法:) *
这肯定是一个Swift的错误,就像许多其他的ObjectiveC一样。我在试图将一个arc4random()数字(这是一个UInt32类型)和一个UInt32()抛出的字符串进行比较时遇到了同样的问题,我得到了同样的错误,这在我的例子中更令人愤慨,因为这两个数字是相同的类型。这使我认为铸造不能产生预期的结果。
我认为在创建一个辅助UIint32变量并将其赋值为UInt32(theString)时,butSwift不允许在定义变量时将字符串转换为UInt32,因此我必须创建一个辅助变量以转换为Int,然后将Int转换为UInt32,以便能够比较这两个数字:
var theString = "5"
var randomNumber = arc4random() % 10
var UInt32Number = UInt32(theString)
// => ERROR: "Cannot invoke 'init' with an argument of type '@lvalue String!'
// (this is where I realized the comparison line could be suffering from the same problem)
if randomNumber == UInt32(theString) { ... }
// No error here 'cos Swift is supposed to have casted theString into a UInt32
// ...but surprisingly it prompts an ERROR saying it can't compare a UInt32 with a UInt32 (WTF!)
// And here's where I go crazy, because watch what happens in the next lines:
var intValue = theString.toInt()
var UInt32Value = UInt32(intValue!)
if randomNumber == UInt32Value { ... } // => NOW IT WORKS!!结论: Swift并不是在比较中做出转换类型,即使它是应该的。有时,它似乎是搞砸*。使用具有集合类型的辅助变量可以解决这个问题。
https://stackoverflow.com/questions/25898004
复制相似问题