Konwertowanie ciągu znaków na Int za pomocą Swift


352

Aplikacja zasadniczo oblicza przyspieszenie, wprowadzając początkową i końcową prędkość i czas, a następnie używa wzoru do obliczenia przyspieszenia. Ponieważ jednak wartości w polach tekstowych są ciągami, nie jestem w stanie przekonwertować ich na liczby całkowite.

@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

7
Nie próbowałem, ale może możesz rzucić takie wartości jakvar answer1 = Int(txtBox1.text)
Daniel

Jeśli ciąg ma oznaczać „23,0”, to jeśli rzucisz go na Int („23.0”), zwróci zero, w tym przypadku najpierw musisz rzucić na Double / Float, a następnie ponownie rzucić na Int.
Ariven Nadar

Odpowiedzi:


326

Podstawowa idea, zauważ, że działa to tylko w Swift 1.x (sprawdź odpowiedź ParaSary, aby zobaczyć, jak to działa w Swift 2.x):

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

Aktualizacja dla Swift 4

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

Dzięki, to działa. Mam jednak problem, ponieważ chcę, aby liczby zawierały również liczby zmiennoprzecinkowe. Dzięki jeszcze raz.
Marwan Qasem

4
Jeśli potrzebujesz liczb zmiennoprzecinkowych (a naprawdę naprawdę chcesz Double, a nie zmiennoprzecinkowych), toInt () tego nie zrobi. Czy możesz użyć swojej wyobraźni i dostępnej dokumentacji, aby znaleźć odpowiednią funkcję?
gnasher729

4
I dostać 'NSString' does not have a member named 'toInt'. Jakieś pomysły?
Matej

1
NSStringi Stringsą dwoma różnymi obiektami i mają różne metody. NSStringma metodę o nazwie.intValue
Byron Coetsee

7
To rozwiązanie było odpowiednie tylko dla Swift, a nie dla Swift2. Teraz powinieneś użyć: Int (firstText.text)
gurehbgui

337

Zaktualizuj odpowiedź dla swift 2.0 :

toInt()metoda otrzymuje błąd. Ponieważ w Swift 2.x .toInt()funkcja została usunięta z String. W zamian Int ma teraz inicjalizator, który akceptuje ciąg znaków:

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

Czy mogę zapytać, dlaczego pojawia się błąd, gdy pomijam „?” zwęglać? Dlaczego muszę podać „a” jako opcjonalne?
Manos Serifios

1
@ManosSerifios ta dyskusja może być pomocna: stackoverflow.com/questions/32621022/...
Paraneetharan Saravanaperumal

nie jest tak naprawdę powiązane, ale podejście konstruktorskie jest zawsze preferowane i bardziej czytelne dla Int do Strings. "\(someInt)"nie jest dobre String(someInt)jest o wiele łatwiejsze do odczytania
Honey

Drukuję, Int(firstText.text)!a następnie nadal widzę opcjonalne. Dlaczego? Czy go nie rozpakowałem?
Honey

Spowoduje to awarię, gdy ciąg jest nil . Może się tak nie zdarzyć, gdy ciąg znaków pochodzi z elementu interfejsu użytkownika, jak w tym przypadku. Ale jeden sposób, aby zapobiec awarii jest dodanie wartości domyślnej do napisu: let a:Int? = Int(firstText.text ?? "").
Jens

85

myString.toInt() - przekonwertuj wartość ciągu na int.

Swift 3.x

Jeśli masz liczbę całkowitą ukrytą w ciągu, możesz przekonwertować za pomocą konstruktora liczb całkowitych, tak jak to:

let myInt = Int(textField.text)

Podobnie jak w przypadku innych typów danych (Float i Double), możesz także konwertować za pomocą NSString:

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

1
to faktycznie odpowiada na pytanie, wszyscy inni mówią OP, jak
wybierać

1
Przykład dla Swift 3?
Peter Kreinz

proszę o wyjaśnienie „najnowszych wersji szybkich” dla nadziei potomności na zamieszanie :)
Alex Hall

@aremvee masz na myśli „obsadzić” liczbę całkowitą jako ciąg? A co to dokładnie robi, że odpowiada na pytanie, którego nie udzielają inne odpowiedzi?
Alex Hall

31

edycja / aktualizacja: Xcode 11.4 • Swift 5.2

Sprawdź komentarze za pomocą kodu


Zawartość pliku 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
    }
}

Musisz także dodać te rozszerzenia do swojego projektu:


Rozszerzenia Zawartość pliku UITextField.swift :

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

Rozszerzenia Formatter.swift zawartość pliku:

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

Rozszerzenia Zawartość pliku NumberFormatter.swift :

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

Rozszerzenia Zawartość pliku StringProtocol.swift :

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

Przykładowy projekt


27

Możesz użyć NSNumberFormatter().numberFromString(yourNumberString). Jest świetny, ponieważ zwraca opcję opcjonalną, z którą można następnie przetestować, if letaby ustalić, czy konwersja się powiodła. na przykład.

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
}

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

1
Właśnie zmieniłem go na „myNumber.integerValue”, ponieważ Xcode 7 nie buduje się z „intValue”. Ta ostatnia ma wartość Int32
brainray

21

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

możesz także użyć Opcjonalnego wiązania innego niż wiązanie wymuszone.

na przykład:

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

14

// Xcode 8.1 i szybki 3.0

Możemy sobie z tym poradzić również poprzez opcjonalne wiązanie

let occur = "10"

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

    }

11

W Swift 4.2 i 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)

7

Szybki 3

Najprostszym i bezpieczniejszym sposobem jest:

@IBOutlet var textFieldA  : UITextField
@IBOutlet var textFieldB  : UITextField
@IBOutlet var answerLabel : UILabel

@IBAction func calculate(sender : AnyObject) {

      if let intValueA = Int(textFieldA),
            let intValueB = Int(textFieldB) {
            let result = intValueA + intValueB
            answerLabel.text = "The acceleration is \(result)"
      }
      else {
             answerLabel.text = "The value \(intValueA) and/or \(intValueB) are not a valid integer value"
      }        
}

Unikaj nieprawidłowych wartości ustawiających typ klawiatury na klawiaturę numeryczną:

 textFieldA.keyboardType = .numberPad
 textFieldB.keyboardType = .numberPad

7

W Swift 4:

extension String {            
    var numberValue:NSNumber? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter.number(from: self)
    }
}
let someFloat = "12".numberValue

4

Zrobiłem prosty program, w którym masz 2 pola tekstowe, które pobierasz od użytkownika i dodajesz, aby ułatwić zrozumienie, znajdź poniższy kod.

@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)"
}

mam nadzieję że to pomoże.


4

Swift 3.0

Spróbuj tego, nie musisz sprawdzać żadnego warunku Zrobiłem wszystko, po prostu użyj tej funkcji. Wyślij dowolny ciąg, liczbę, liczbę zmiennoprzecinkową, podwójną itp. otrzymasz liczbę jako wartość lub 0, jeśli nie będzie w stanie przekonwertować twojej wartości

Funkcjonować:

func getNumber(number: Any?) -> NSNumber {
    guard let statusNumber:NSNumber = number as? NSNumber else
    {
        guard let statString:String = number as? String else
        {
            return 0
        }
        if let myInteger = Int(statString)
        {
            return NSNumber(value:myInteger)
        }
        else{
            return 0
        }
    }
    return statusNumber
}

Użycie: Dodaj powyższą funkcję do kodu i przekonwertuj użycie, let myNumber = getNumber(number: myString) jeśli myStringma liczbę lub ciąg znaków, zwraca liczbę, którą zwraca0

Przykład 1:

let number:String = "9834"
print("printing number \(getNumber(number: number))")

Wynik: printing number 9834

Przykład 2:

let number:Double = 9834
print("printing number \(getNumber(number: number))")

Wynik: printing number 9834

Przykład 3:

let number = 9834
print("printing number \(getNumber(number: number))")

Wynik: printing number 9834


4

Przydatne dla String na Int i innego typu

extension String {
        //Converts String to Int
        public func toInt() -> Int? {
            if let num = NumberFormatter().number(from: self) {
                return num.intValue
            } else {
                return nil
            }
        }

        //Converts String to Double
        public func toDouble() -> Double? {
            if let num = NumberFormatter().number(from: self) {
                return num.doubleValue
            } else {
                return nil
            }
        }

        /// EZSE: Converts String to Float
        public func toFloat() -> Float? {
            if let num = NumberFormatter().number(from: self) {
                return num.floatValue
            } else {
                return nil
            }
        }

        //Converts String to Bool
        public func toBool() -> Bool? {
            return (self as NSString).boolValue
        }
    }

Użyj tego jak:

"123".toInt() // 123

3

Informacje o int () i Swift 2.x: jeśli po konwersji uzyskasz zero, sprawdź, czy próbujesz przekonwertować ciąg z dużą liczbą (na przykład: 1073741824), w tym przypadku spróbuj:

let bytesInternet : Int64 = Int64(bytesInternetString)!

1
Dziękuję, że zadziałało w mojej sprawie. Int () pracował dla mnie z 16 cyframi, ale ostatnio zaczął się nie udać.
Ryan Boyd

3

Najnowsze swift3 ten kod jest po prostu przekonwertować ciąg na int

let myString = "556"
let myInt = Int(myString)

2

Ponieważ ciąg znaków może zawierać znaki nienumeryczne, należy użyć znaku a w guardcelu ochrony operacji. Przykład:

guard let labelInt:Int = Int(labelString) else {
    return
}

useLabelInt()

2

Niedawno dostałem ten sam problem. Poniższe rozwiązanie jest dla mnie pracą:

        let strValue = "123"
        let result = (strValue as NSString).integerValue

1

Użyj tego:

// get the values from text boxes
    let a:Double = firstText.text.bridgeToObjectiveC().doubleValue
    let b:Double = secondText.text.bridgeToObjectiveC().doubleValue

//  we checking against 0.0, because above function return 0.0 if it gets failed to convert
    if (a != 0.0) && (b != 0.0) {
        var ans = a + b
        answerLabel.text = "Answer is \(ans)"
    } else {
        answerLabel.text = "Input values are not numberic"
    }

LUB

Ustaw UITextField KeyboardType jako DecimalTab z XIB lub storyboardu i usuń wszelkie warunki do wykonywania jakichkolwiek obliczeń, tj.

var ans = a + b
answerLabel.text = "Answer is \(ans)"

Ponieważ typ klawiatury to DecimalPad, nie ma szans na wprowadzenie innych cyfr 0-9 lub.

Mam nadzieję, że to pomoże !!


1
//  To convert user input (i.e string) to int for calculation.I did this , and it works.


    let num:Int? = Int(firstTextField.text!);

    let sum:Int = num!-2

    print(sum);

1

To działa dla mnie

var a:Int? = Int(userInput.text!)

Czym różni się to od rozwiązania podanego w komentarzu?
Prune

2
W rozwiązaniu podanym w komentarzu brakuje „!” na końcu, czego można się spodziewać w Swift 2 i później
Naishta,

1

dla Swift3.x

extension String {
    func toInt(defaultValue: Int) -> Int {
        if let n = Int(self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) {
            return n
        } else {
            return defaultValue
        }
    }
}

0

dla alternatywnego rozwiązania. Możesz użyć rozszerzenia typu natywnego. Możesz przetestować na placu zabaw.

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

„2” .add (1)


0

Moim rozwiązaniem jest ogólne rozszerzenie konwersji łańcucha na int.

extension String {

 // default: it is a number suitable for your project if the string is not an integer

    func toInt(default: Int) -> Int {
        if let result = Int(self) {
            return result
        }
        else {
            return default  
        }
    }

}

0
@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

Pytanie: ciągu „4.0000” nie można przekonwertować na liczbę całkowitą za pomocą Int („4.000”)?

Odpowiedź: Ciąg kontrolny Int () jest liczbą całkowitą, czy nie, jeśli tak, to daje liczbę całkowitą, a w przeciwnym razie zero. ale Float lub Double mogą konwertować dowolny ciąg liczbowy na odpowiedni Float lub Double bez podania wartości zero. Przykład, jeśli masz ciąg liczb całkowitych „45”, ale użycie zmiennoprzecinkowe („45”) daje wartość zmiennoprzecinkową 45,0 lub użycie podwójnego („4567”) daje 45,0.

Rozwiązanie: NSString (ciąg: „45.000”). IntegerValue lub Int (Float („45.000”)!)! aby uzyskać poprawny wynik.


0

Int w Swift zawiera inicjator, który akceptuje ciąg znaków. Zwraca opcjonalny Int? ponieważ konwersja może się nie powieść, jeśli ciąg nie zawiera liczby.

Za pomocą instrukcji if let możesz sprawdzić, czy konwersja się powiodła.

Twój kod stanie się mniej więcej taki:

@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

    if let intAnswer = Int(txtBox1.text) {
      // Correctly converted
    }
}

0

Swift 5.0 i wyżej

Pracujący

W przypadku dzielenia Stringtworzy dwa, substringsa nie dwa Strings. Będzie to poniżej metody sprawdzania Anyi przekształcić go t0 NSNumberjej łatwo przekonwertować NSNumberdo Int, Floatjakie kiedykolwiek dane wpisz czego potrzebujesz.

Aktualny kod

//Convert Any To Number Object Removing Optional Key Word.
public func getNumber(number: Any) -> NSNumber{
 guard let statusNumber:NSNumber = number as? NSNumber  else {
    guard let statString:String = number as? String else {
        guard let statSubStr : Substring = number as? Substring else {
            return 0
        }
        if let myInteger = Int(statSubStr) {
            return NSNumber(value:myInteger)
        }
        else{
            return 0
        }
    }

    if let myInteger = Int(statString) {
        return NSNumber(value:myInteger)
    }
    else if let myFloat = Float(statString) {
        return NSNumber(value:myFloat)
    }else {
        return 0
    }
}
return statusNumber }

Stosowanie

if let hourVal = getNumber(number: hourStr) as? Int {

}

Przekazywanie Stringdo sprawdzenia i konwersji naDouble

Double(getNumber(number:  dict["OUT"] ?? 0)

0

Swift5 float lub int string na int:

extension String {
    func convertStringToInt() -> Int {
        return Int(Double(self) ?? 0.0)
    }
}

let doubleStr = "4.2"
// print 4
print(doubleStr.convertStringToInt())

let intStr = "4"
// print 4
print(intStr.convertStringToInt())

-1

Począwszy od szybkiego 3 , muszę wymusić #% @! string i int z „!” inaczej to po prostu nie działa.

Na przykład:

let prefs = UserDefaults.standard
var counter: String!
counter = prefs.string(forKey:"counter")
print("counter: \(counter!)")


var counterInt = Int(counter!)
counterInt = counterInt! + 1
print("counterInt: \(counterInt!)")

OUTPUT:
counter: 1
counterInt: 2

Nie możesz po prostu zrobić var counterInt = counter.map { Int($0) }? Gdzie countermoże byćString?
Martin

@Martin - Nie? czyni ją opcjonalną, a zatem dodaje słowo „opcjonalne” do ciągu licznika.
Sam B,

IMHO, nie powinieneś zmuszać do rozpakowywania opcji. Wolę używać guardi if letoświadczenia
Martin

-1

Konwertuj wartość ciągu na liczbę całkowitą w Swift 4

let strValue:String = "100"
let intValue = strValue as! Int
var intValueFromString:Int = strValue as! Int
or
var intValueFromString = Int(strValue)!
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.