Swift:扩展数组,类型_的值没有成员_

时间:2015-09-29 05:11:42

标签: arrays swift extend

我正在尝试扩展Array以返回子数组。 该行让b = arr.objectsAtIndexes([1,3,5])产生错误“类型'[Int]'的值没有成员'objectsAtIndexes'playground screenshot

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
    }
}

2 个答案:

答案 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)

你的结果将是:

enter image description here

答案 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)