2014-09-19 76 views
2

編輯: 好的。我只是將我的代碼更改爲:var randomX = Int(arc4random()%6)希望我可以在發佈之前考慮它:|'UInt32'不可轉換爲'MirrorDisposition'

我拿了接受了這個話題的答案作爲參考:Swift convert UInt to Int


我一直試圖做一個簡單的ios與SWIFT應用猜測。我正在生成一個隨機數字,並從用戶那裏獲得另一個數字並比較兩者。但我堅持了這個錯誤:'UInt32' is not convertible to 'MirrorDisposition'同時比較兩個整數(其中一人從字符串轉換爲整數的toInt()方法)

下面你可以看到我的UI,我的代碼,二計算器話題,我讀以及在閱讀這些主題後我如何更改我的代碼。

UI:(我不能調整圖像大小) enter image description here

我的代碼:

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet var myImageView: UIImageView! 
    @IBOutlet var inputField: UITextField! 
    @IBAction func clickedGuessButtonAction(sender: AnyObject) { 
     println("Guess button clicked") 
     var randomX = arc4random()%6 
     println("randomX = \(randomX)") 
     var guess = inputField.text.toInt() 

     if((inputField.text) != nil){ 
      if(guess == randomX){ 
       println("correct") 
       var image = UIImage(named: "images/tick.png"); 
       myImageView.image=image; 
       self.view.addSubview(myImageView); // what is this? 
       inputField.resignFirstResponder();// hides keyboard 

      } 
      else 
      { 
       println("wrong") 
       var image = UIImage(named: "images/cross.png") 
       myImageView.image=image; 
       self.view.addSubview(myImageView); 
       inputField.resignFirstResponder();//hides keyboard 
      } 
     } 
     else{ 
      println("invalid input. requires integer only") 
      inputField.resignFirstResponder();// hides keyboard 
     } 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 

我發現計算器這些主題:

float is not convertible to 'MirrorDisposition' Swift What is mirrordisposition?

iOS Swift Error: 'T' is not convertible to 'MirrorDisposition'

首先一個特別有一個擴展的答案終於暗示if intValue == Int(floatValue)

比我改變var guess = inputField.text.toInt()

var guess = Int(inputField.text);

但是這一次我得到這樣的錯誤消息:Cannot invoke 'init' with an argument of type '@lvalue String!'

這一次,我搜索了這個錯誤信息,但找不到任何有用的信息。比較兩個整數應該不是那麼難。我肯定錯過了一些容易的事情。有任何想法嗎?

+0

確定。我只是將我的代碼更改爲:** var randomX = Int(arc4random()%6)** 希望我可以在發佈之前想想它:| – 2014-09-19 12:53:14

+0

[Swift convert UInt to Int]可能重複(http://stackoverflow.com/questions/24144557/swift-convert-uint-to-int) – mattt 2014-11-20 06:42:16

回答

3

嘗試改變:

var randomX = arc4random()%6 

var randomX = Int(arc4random()%6) 
+0

嗨,感謝您的回覆,但我已經在頂部說明了答案我的問題和在它的結尾(作爲評論) – 2014-10-03 06:46:55

+0

我已經使用這種方法來解決我自己的問題,它不再工作。 – 2014-11-06 08:24:29

0

這應該這樣做

let sizeX = UInt32(6) 
let randomX = CGFloat(arc4random_uniform(sizeX)) 
相關問題