Swift: 扩展数组,_ 类型的值没有成员 _
Swift: Extending Array, Value of type _ has no member _
我正在尝试将 Array 扩展为 return 一个子数组。
let 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
}
}
只需以这种方式在扩展声明下方使用该扩展:
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)
你的结果将是:
定义 extension
后,您应该调用您的方法。检查这个 Extension reference
也.append
不return任何值,所以不分配它
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)
我正在尝试将 Array 扩展为 return 一个子数组。
let 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
}
}
只需以这种方式在扩展声明下方使用该扩展:
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)
你的结果将是:
定义 extension
后,您应该调用您的方法。检查这个 Extension reference
也.append
不return任何值,所以不分配它
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)