如何返回字符数组的子集?

时间:2016-04-30 15:31:37

标签: arrays swift

我正在尝试动态切割一个字母数组,但我似乎无法将结果重新转换回[String]

let letters:String = "abcdefghijklmnopqrstuvwxyz"
let lettersarray = Array(letters.characters)

var targetNum = 14 // Show just the first 14 characters

var resultsArray = [String]()

let resultsSlice = lettersarray.dropLast(lettersarray.count - targetNum) // Returns an Array Slice instead of an Array

let newresultsArray = Array(resultsSlice) // Returns Array<_element> instead of [String]

如何返回[String]即[“a”,“b”,“c”......例如]

3 个答案:

答案 0 :(得分:3)

您需要将Character数组映射回String

let resultsArray = lettersarray.dropLast(lettersarray.count - targetNum).map{String($0)}

或者(Leo Dabus的学分)

let letters = "abcdefghijklmnopqrstuvwxyz"
let targetNum = 14
let resultsArray = letters.characters.prefix(targetNum).map{String($0)}

答案 1 :(得分:2)

这里不需要数组。很难理解您尝试做什么,但如果您只想要字符串的前14个字符,请使用prefix方法:

    let s = String("abcdefghijklmno".characters.prefix(14))

答案 2 :(得分:0)

假设您正在获得String并且想要一个字符数组,这是一个来自String的字符切片,您可以使用Swift的半开放范围运算符here

let letters:String = "abcdefghijklmnopqrstuvwxyz"
let lettersArray = Array(letters.characters)
let targetNum = 2
let resultsArray = lettersArray[0..<targetNum]

这将为您提供ArraySlice<Character>。如果你想要Array<Character>,你可以这样做:

let resultsArray:Array<Character> = Array(lettersArray[0..<targetNum]) // ["a","b"]