我正在尝试扩展Array以返回子数组。 该行让b = arr.objectsAtIndexes([1,3,5])产生错误“类型'[Int]'的值没有成员'objectsAtIndexes'
import Foundation
var arr = [Int](6..<19)
let b = arr.objectsAtIndexes([1,3,5])
b = b.append(1)
extension Array {
func objectsAtIndexes(indexes: [Int]) -> [Element] {
var returnArray = [Element]()
for i in indexes {
returnArray.append(self[i])
}
return returnArray
}
}
答案 0 :(得分:0)
只需在扩展声明下方使用该扩展程序:
import Foundation
extension Array {
func objectsAtIndexes(indexes: [Int]) -> [Element] {
var returnArray = [Element]()
for i in indexes {
returnArray.append(self[i])
}
return returnArray
}
}
var arr = [Int](6..<19)
var b = arr.objectsAtIndexes([1,3,5])
b = b.append(1)
并替换此行:
b = b.append(1)
这一行:
b.append(1)
你的结果将是:
答案 1 :(得分:0)
定义extension
后,您应该调用您的方法。请检查此Extension reference
.append
也不会返回任何值,所以不要指定它
extension Array {
func objectsAtIndexes(indexes: [Int]) -> [Element] {
var returnArray = [Element]()
for i in indexes {
returnArray.append(self[i])
}
return returnArray
}
}
var arr = [Int](6..<19)
var b = arr.objectsAtIndexes([1,3,5])
// Do not assign to b
b.append(1)