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

时间:2022-01-22 17:06:39

I'm trying to extend Array to return a sub array. the line let b = arr.objectsAtIndexes([1,3,5]) produces the error "Value of type '[Int]' has no member 'objectsAtIndexes' Swift:扩展数组,类型_的值没有成员_

我正在尝试扩展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
    }
}

2 个解决方案

#1


0  

Just use that extension below the extension declaration this way:

只需在扩展声明下方使用该扩展名:

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)

And replace this line:

并替换此行:

b = b.append(1)

With this line:

有了这条线:

b.append(1)

And your result will be:

你的结果将是:

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

#2


0  

After defining the extension, you should call your method. Check this Extension reference

定义扩展后,您应该调用您的方法。检查此扩展参考

also .append don't return any value, so don't assign it

也.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)

#1


0  

Just use that extension below the extension declaration this way:

只需在扩展声明下方使用该扩展名:

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)

And replace this line:

并替换此行:

b = b.append(1)

With this line:

有了这条线:

b.append(1)

And your result will be:

你的结果将是:

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

#2


0  

After defining the extension, you should call your method. Check this Extension reference

定义扩展后,您应该调用您的方法。检查此扩展参考

also .append don't return any value, so don't assign it

也.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)