Reputation: 227
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
Upvotes: 1
Views: 6708
Reputation: 19758
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
Upvotes: 5