Converting String to Int with Swift

前端 未结 30 1273
小鲜肉
小鲜肉 2020-11-22 06:59

The application basically calculates acceleration by inputting Initial and final velocity and time and then use a formula to calculate acceleration. However, since the value

相关标签:
30条回答
  • 2020-11-22 07:09

    This works for me

    var a:Int? = Int(userInput.text!)
    
    0 讨论(0)
  • 2020-11-22 07:10

    //Xcode 8.1 and swift 3.0

    We can also handle it by Optional Binding, Simply

    let occur = "10"
    
    if let occ = Int(occur) {
            print("By optional binding :", occ*2) // 20
    
        }
    
    0 讨论(0)
  • 2020-11-22 07:11

    In Swift 4.2 and Xcode 10.1

    let string:String = "789"
    let intValue:Int = Int(string)!
    print(intValue)
    
    let integerValue:Int = 789
    let stringValue:String = String(integerValue)
        //OR
    //let stringValue:String = "\(integerValue)"
    print(stringValue)
    
    0 讨论(0)
  • 2020-11-22 07:11

    i have made a simple program, where you have 2 txt field you take input form the user and add them to make it simpler to understand please find the code below.

    @IBOutlet weak var result: UILabel!
    @IBOutlet weak var one: UITextField!
    @IBOutlet weak var two: UITextField!
    
    @IBAction func add(sender: AnyObject) {        
        let count = Int(one.text!)
        let cal = Int(two.text!)
        let sum = count! + cal!
        result.text = "Sum is \(sum)"
    }
    

    hope this helps.

    0 讨论(0)
  • 2020-11-22 07:13

    Latest swift3 this code is simply to convert string to int

    let myString = "556"
    let myInt = Int(myString)
    
    0 讨论(0)
  • 2020-11-22 07:13
    @IBAction func calculateAclr(_ sender: Any) {
        if let addition = addition(arrayString: [txtBox1.text, txtBox2.text, txtBox3.text]) {
          print("Answer = \(addition)")
          lblAnswer.text = "\(addition)"
        }
    }
    
    func addition(arrayString: [Any?]) -> Int? {
    
        var answer:Int?
        for arrayElement in arrayString {
            if let stringValue = arrayElement, let intValue = Int(stringValue)  {
                answer = (answer ?? 0) + intValue
            }
        }
    
        return answer
    }
    
    0 讨论(0)
提交回复
热议问题