除了循环和追加之外,是否有更快/更简洁的方法从阵列中获取多个索引?也许是以下的单线功能变体? let names: [String] = ["John", "Mary", "Hugo", "Bill", "Andrea"]let indexesToGet = [0, 1, 3]var result: [
let names: [String] = ["John", "Mary", "Hugo", "Bill", "Andrea"] let indexesToGet = [0, 1, 3] var result: [String] = [] for i in 0..<indexesToGet.count { result.append(names[indexesToGet[i]]) } return result //returns ["John", "Mary", "Bill"]你可以这样试试.
let result = indexesToGet.map { names[$0] }
要防止indexOutOfBounds崩溃,您可以使用flatMap.
let result = indexesToGet.flatMap { (names.count > $0) ? names[$0] : nil}