Leo*_*bus 7

Xcode 8.3.1•Swift 3.1

您可以使用componentsSeparatedByString方法将字符串转换为数组,并使用flatMap将其转换为Int:

let str = "1,2,3,4,5"
let arr = str.components(separatedBy: ",").flatMap{Int($0)}

print(arr)  // "[1, 2, 3, 4, 5]\n"
Run Code Online (Sandbox Code Playgroud)

如果你的字符串包含空格,你可以在转换为Int之前使用stringByTrimmingCharactersInSet修剪它:

let str = "1, 2, 3, 4, 5 "
let numbers = str.components(separatedBy: ",")
    .flatMap{ Int($0.trimmingCharacters(in: .whitespaces)) }

print(numbers)  // "[1, 2, 3, 4, 5]\n"
Run Code Online (Sandbox Code Playgroud)