Swift 3 : How can I get the Array from the String

503 views Asked by At

Actually I got the address field string from the api like "District-1 1656-Union-Street Eureka 707-445-6600", so I need to convert into Array.

Expected Result :

["District-1", "1656-Union-Street", "Eureka", "707-445-6600"]

As I can get the Array from the components method using space as a separator.

//Code
var getAddress = addInfo.components(separatedBy: " ")

//Result
["District-1", "", "", "1656-Union-Street", "", "", "Eureka", "", "707-445-6600"]

But the problem is that it will return the empty object also.

1

There are 1 answers

0
Ramkrishna Sharma On BEST ANSWER

You can apply the split method for accomplished the task.

For i.e.

var addInfo = "District-1   1656-Union-Street   Eureka  707-445-6600"
var getAddress = addInfo.characters.split(separator: " ", omittingEmptySubsequences: true).map(String.init)

//Result
["District-1", "1656-Union-Street", "Eureka", "707-445-6600"]

omittingEmptySubsequences : If false, an empty subsequence is returned in the result for each consecutive pair of separator elements in the collection and for each instance of separator at the start or end of the collection. If true, only nonempty subsequences are returned. The default value is true.

For more information please review the link