1

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
Dimoreno
  • 227
  • 3
  • 15
  • 2
    Possible duplicate of [Swift - Converting String to Int](https://stackoverflow.com/questions/24115141/swift-converting-string-to-int) – Scriptable Nov 10 '17 at 15:42
  • 1
    Your question isn't clear. You have a string. You have an index. What part of the string do you want from that index? Do you want the string from its start to that index? Do you want the string from the index to the end? Do you want just the one digit at that index? – rmaddy Nov 10 '17 at 15:42
  • Update your question to show the desired output from the code you posted. – rmaddy Nov 10 '17 at 15:43
  • I have edited my question – Dimoreno Nov 10 '17 at 15:45
  • 1
    Where do you extract a substring in your code? Why so complicated? What about `Int(num.prefix(2))` ? – Martin R Nov 10 '17 at 15:49

1 Answers1

5

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

Scriptable
  • 19,402
  • 5
  • 56
  • 72