Converting String to Int with Swift

前端 未结 30 1236
小鲜肉
小鲜肉 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:20

    for Alternative solution. You can use extension a native type. You can test with playground.

    extension String {
        func add(a: Int) -> Int? {
            if let b = Int(self) {
                return b + a
            }
            else {
                return nil
            }
        }     
    }
    

    "2".add(1)

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

    About int() and Swift 2.x: if you get a nil value after conversion check if you try to convert a string with a big number (for example: 1073741824), in this case try:

    let bytesInternet : Int64 = Int64(bytesInternetString)!
    
    0 讨论(0)
  • 2020-11-22 07:23

    for Swift3.x

    extension String {
        func toInt(defaultValue: Int) -> Int {
            if let n = Int(self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) {
                return n
            } else {
                return defaultValue
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 07:24

    edit/update: Xcode 11.4 • Swift 5.2

    Please check the comments through the code


    IntegerField.swift file contents:

    import UIKit
    
    class IntegerField: UITextField {
    
        // returns the textfield contents, removes non digit characters and converts the result to an integer value
        var value: Int { string.digits.integer ?? 0 }
    
        var maxValue: Int = 999_999_999
        private var lastValue: Int = 0
    
        override func willMove(toSuperview newSuperview: UIView?) {
            // adds a target to the textfield to monitor when the text changes
            addTarget(self, action: #selector(editingChanged), for: .editingChanged)
            // sets the keyboard type to digits only
            keyboardType = .numberPad
            // set the text alignment to right
            textAlignment = .right
            // sends an editingChanged action to force the textfield to be updated
            sendActions(for: .editingChanged)
        }
        // deletes the last digit of the text field
        override func deleteBackward() {
            // note that the field text property default value is an empty string so force unwrap its value is safe
            // note also that collection remove at requires a non empty collection which is true as well in this case so no need to check if the collection is not empty.
            text!.remove(at: text!.index(before: text!.endIndex))
            // sends an editingChanged action to force the textfield to be updated
            sendActions(for: .editingChanged)
        }
        @objc func editingChanged() {
            guard value <= maxValue else {
                text = Formatter.decimal.string(for: lastValue)
                return
            }
            // This will format the textfield respecting the user device locale and settings
            text = Formatter.decimal.string(for: value)
            print("Value:", value)
            lastValue = value
        }
    }
    

    You would need to add those extensions to your project as well:


    Extensions UITextField.swift file contents:

    import UIKit
    extension UITextField {
        var string: String { text ?? "" }
    }
    

    Extensions Formatter.swift file contents:

    import Foundation
    extension Formatter {
        static let decimal = NumberFormatter(numberStyle: .decimal)
    }
    

    Extensions NumberFormatter.swift file contents:

    import Foundation
    extension NumberFormatter {
        convenience init(numberStyle: Style) {
            self.init()
            self.numberStyle = numberStyle
        }
    }
    

    Extensions StringProtocol.swift file contents:

    extension StringProtocol where Self: RangeReplaceableCollection {
        var digits: Self { filter(\.isWholeNumber) }
        var integer: Int? { Int(self) }
    }
    

    Sample project

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

    Updated answer for Swift 2.0+:

    toInt() method gives an error, as it was removed from String in Swift 2.x. Instead, the Int type now has an initializer that accepts a String:

    let a: Int? = Int(firstTextField.text)
    let b: Int? = Int(secondTextField.text)
    
    0 讨论(0)
  • 2020-11-22 07:27

    Because a string might contain non-numerical characters you should use a guard to protect the operation. Example:

    guard let labelInt:Int = Int(labelString) else {
        return
    }
    
    useLabelInt()
    
    0 讨论(0)
提交回复
热议问题