简体   繁体   中英

How to convert a String to an Int in Swift?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM