Swift 3:如何从字符串中获取数组

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

实际上我是从api中得到地址字段字符串,如"District-1 1656-Union-Street Eureka 707-445-6600",所以我需要转换成数组。

预期结果:

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

因为我可以使用 space 作为分隔符从 components 方法获取数组。

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

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

但问题是它也会 return 空对象。

您可以应用split方法来完成任务。

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.

有关详细信息,请查看 link