2017-09-13 90 views
-3

我有,通過使用文本框引入了新的數的函數:如何在Swift 3中將字符串從TextField轉換爲Int?

//First node 
var root = TreeNode(7) 
@IBAction func introducirNumero(_ sender: Any) { 
    var d = Int(entrada1.text!) 
    print(d) 
    var call = TreeNode(d!) 
    root = TreeNode(d!) 

    //let numero: Int? = (Int(entrada1.text!)!) 
} 

這個功能應該投的類型和發送詮釋這一類:

class TreeNode { 
    var value : Int 
    var left : TreeNode? = nil 
    var right : TreeNode? = nil 

    //incia como val 
    init(_ rootValue:Int) 
    { value = rootValue } 

    @discardableResult // if we don't use the method so that it can send a warning 
    func addValue(_ newValue:Int) -> TreeNode 
    { 
     if newValue == value // exclude duplicate entries 
     { return self } 
     else if newValue < value 
     { 
      if let newNode = left?.addValue(newValue) 
      { return newNode } 
      left = TreeNode(newValue) 
      return left! 
     } 
     else 
     { 
      if let newNode = right?.addValue(newValue) 
      { return newNode } 
      right = TreeNode(newValue) 
      return right! 
     } 
    } 

} 

的問題是,它似乎沒有投射,因爲我收到此線錯誤:

var d = Int(entrada1.text!) 

而我的應用程序崩潰。

+2

我可能是錯的,但我不認爲錯誤與鑄造! – Siyavash

+2

你的代碼在哪裏處理文本字段?你的代碼試圖將'String'轉換爲'Int'的位置?與您的代碼相關的崩潰細節在哪裏? – rmaddy

+1

選擇權是有原因的。如果返回一個可選項,它可以返回零,你應該適當地處理它。不要只是強行打包所有東西。 – Palle

回答

0

你可以做INT(「你的號碼」),我相信它會改變它爲int

+1

發佈此問題的答案是沒有意義的。這個問題沒有關於這個問題的有用細節,並且有無數的例子顯示了這個答案中發佈的信息。在發佈實際解決問題的答案之前,請等到問題更新並提供有用的信息。 – rmaddy

+0

我做了,但我不工作。 – Mari