John Doodle John Doodle -4 years ago 97
Swift Question

Seperate a string into an array - Swift

I am new to swift and I would like to separate a string into an array. In my case the string is "20170227" and I would like to have it in an array like [2017,02,27]. I have tried doing this, but the code was way too long and I think by far to complicated for what it is.

var date = "20170227"
var Space: Character = " "
let indexMain = date.index(date.startIndex, offsetBy: 4)
date.insert(Space, at: indexMain)

which eventually only returns 2017 0227, so I'm lost... Thanks in advance!

Answer Source

If you're just interested in the substrings this will do:

let s = "20170227"

let year = s[s.startIndex..<s.index(s.startIndex, offsetBy: 4)] // "2017"
let month = s[s.index(s.startIndex, offsetBy: 4)..<s.index(s.startIndex, offsetBy: 6)] // "02"
let date = s[s.index(s.startIndex, offsetBy: 6)..<s.endIndex] // "27"

let date = [year, month, date] // ["2017", "02", "27"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download