stringswiftintegercharacter

Swift How to get integer from string and convert it into integer


I need to extract numbers from string and put them into a new array in Swift.

var str = "I have to buy 3 apples, 7 bananas, 10eggs"

I tried to loop each characters and I have no idea to compare between Characters and Int.


Solution

  • First, we split the string so we can process the single items. Then we use NSCharacterSet to select the numbers only.

    import Foundation
    
    let str = "I have to buy 3 apples, 7 bananas, 10eggs"
    let strArr = str.split(separator: " ")
    
    for item in strArr {
        let part = item.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
    
        if let intVal = Int(part) {
            print("this is a number -> \(intVal)")
        }
    }
    

    Swift 4:

    let string = "I have to buy 3 apples, 7 bananas, 10eggs"
    let stringArray = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
    for item in stringArray {
        if let number = Int(item) {
            print("number: \(number)")
        }
    }