[ios] Swift를 사용하여 문자열을 Int로 변환

이 응용 프로그램은 기본적으로 초기 및 최종 속도와 시간을 입력하여 가속을 계산 한 다음 공식을 사용하여 가속을 계산합니다. 그러나 텍스트 상자의 값은 문자열이므로 정수로 변환 할 수 없습니다.

@IBOutlet var txtBox1 : UITextField
@IBOutlet var txtBox2 : UITextField
@IBOutlet var txtBox3 : UITextField
@IBOutlet var lblAnswer : UILabel


@IBAction func btn1(sender : AnyObject) {

    let answer1 = "The acceleration is"
    var answer2 = txtBox1
    var answer3 = txtBox2
    var answer4 = txtBox3



답변

기본 아이디어, 이것은 Swift 1.x에서만 작동한다는 점에 유의하십시오 ( Swift 2.x에서 어떻게 작동하는지 보려면 ParaSara의 답변 을 확인하십시오).

    // toInt returns optional that's why we used a:Int?
    let a:Int? = firstText.text.toInt() // firstText is UITextField
    let b:Int? = secondText.text.toInt() // secondText is UITextField

    // check a and b before unwrapping using !
    if a && b {
        var ans = a! + b!
        answerLabel.text = "Answer is \(ans)" // answerLabel ie UILabel
    } else {
        answerLabel.text = "Input values are not numeric"
    }

스위프트 4 업데이트

...
let a:Int? = Int(firstText.text) // firstText is UITextField
let b:Int? = Int(secondText.text) // secondText is UITextField
...


답변

swift 2.0 업데이트 답변 :

toInt()방법에 오류가 발생했습니다. Swift 2.x에서는 .toInt()함수가 문자열에서 제거 되었기 때문 입니다. 대신, Int는 이제 String을 허용하는 이니셜 라이저를 갖습니다.

let a:Int? = Int(firstText.text)     // firstText is UITextField
let b:Int? = Int(secondText.text)   // secondText is UITextField


답변

myString.toInt() -문자열 값을 int로 변환합니다.

스위프트 3.x

문자열 안에 정수가 숨겨져 있으면 다음과 같이 정수의 생성자를 사용하여 변환 할 수 있습니다.

let myInt = Int(textField.text)

다른 데이터 유형 (Float 및 Double)과 마찬가지로 NSString을 사용하여 변환 할 수도 있습니다.

let myString = "556"
let myInt = (myString as NSString).integerValue


답변

편집 / 업데이트 : Xcode 11.4 • Swift 5.2

코드를 통해 주석을 확인하십시오


IntegerField.swift 파일 내용 :

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
    }
}

프로젝트에 이러한 확장을 추가해야합니다.


확장자 UITextField.swift 파일 내용 :

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

확장명 Formatter.swift 파일 내용 :

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

확장자 NumberFormatter.swift 파일 내용 :

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

확장명 StringProtocol.swift 파일 내용 :

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

샘플 프로젝트


답변

사용할 수 있습니다 NSNumberFormatter().numberFromString(yourNumberString). if let전환이 성공했는지 테스트 하기 위해 테스트 할 수있는 선택 사항을 반환하기 때문에 좋습니다 . 예.

var myString = "\(10)"
if let myNumber = NSNumberFormatter().numberFromString(myString) {
    var myInt = myNumber.integerValue
    // do what you need to do with myInt
} else {
    // what ever error code you need to write
}

스위프트 5

var myString = "\(10)"
if let myNumber = NumberFormatter().number(from: myString) {
    var myInt = myNumber.intValue
    // do what you need to do with myInt
  } else {
    // what ever error code you need to write
  }


답변

스위프트 4.0

let stringNumber = "123"
let number = Int(stringNumber) //here number is of type "Int?"


//using Forced Unwrapping

if number != nil {
 //string is converted to Int
}

강제 바인딩 이외의 선택적 바인딩을 사용할 수도 있습니다.

예 :

  if let number = Int(stringNumber) {
   // number is of type Int
  }


답변

// Xcode 8.1 및 swift 3.0

옵션 바인딩으로 간단히 처리 할 수도 있습니다.

let occur = "10"

if let occ = Int(occur) {
        print("By optional binding :", occ*2) // 20

    }