Yusha Yusha - 7 months ago 21
Swift Question

How to parse certain data into an array in Swift?

I'm reading a .txt file in iOS/Swift. I get all my information from the text file. The problem is I only want to get the usernames and store them in an array. Right now I think it's storing all my data from .txt file in a string. How can I parse this correctly so I have only the usernames in an array?

Here is my code right now

if let filepath = NSBundle.mainBundle().pathForResource("myfile", ofType: "txt") {
do {
let contents = try NSString(contentsOfFile: filepath, usedEncoding: nil) as String
print(contents)
} catch {
// contents could not be loaded
}
} else {
print("UNABLE TO FIND TEXT FILE");
}


My text File Format:

User FirstName LastName

asf john smith

adfkh carrie underwood

Answer

Here is a solution using high order functions. Hopefully this works for you.

let text = "tj thomas jeffereson \nbf benjamin franklin\ngw george washington"


let usernames = text.characters
    .split { $0 == "\n" }
    .map { String($0) }
    .map { String($0.characters.split(" ")[0]) }

print(usernames)

output:

["tj", "bf", "gw"]

Loop through result:

for user in usernames {
   print(user)
}