How to convert a String to an Int in Swift?

Dimoreno

I'm trying to get the substring of the var num, but I need that substring be an Int How can I do that?

This is my code

func sbs_inicio(num: String, index: Int) -> Int{
    let dato: Int = num.index(num.startIndex, offsetBy: index)
    return dato
}

var num = "20932121133222"
var value = sbs_inicio(num: num, index: 2)
print(value) //value should be 20
Scriptable

Use the prefix function on the characters array

let startString = "20932121133222"
let prefix = String(startString.characters.prefix(2))
let num = Int(prefix)

Prefix allows you to get the first n elements from the start of an array, so you get these, convert them back to a String and then convert the resulting String to an Int

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related