如何使用自定义功能工具扩展Swift Array<T>或T[]类型?
浏览Swift的API文档显示,Array方法是其扩展T[],例如:
extension T[] : ArrayType {
//...
init()
var count: Int { get }
var capacity: Int { get }
var isEmpty: Bool { get }
func copy() -> T[]
}
Run Code Online (Sandbox Code Playgroud)
复制和粘贴相同的源并尝试任何变化时,例如:
extension T[] : ArrayType {
func foo(){}
}
extension T[] {
func foo(){}
}
Run Code Online (Sandbox Code Playgroud)
它无法构建错误:
标称类型
T[]不能扩展
使用完整类型定义失败Use of undefined type 'T',即:
extension Array<T> {
func foo(){}
}
Run Code Online (Sandbox Code Playgroud)
而且它也失败,Array<T : Any>和Array<String>.
好奇Swift让我扩展一个无类型数组:
extension Array …Run Code Online (Sandbox Code Playgroud) 我想扩展Array类,以便它可以知道它是否已经排序(升序).我想添加一个名为的计算属性isSorted.如何声明Array的元素可以比较?
我目前在Playground中的实现
extension Array {
var isSorted: Bool {
for i in 1..self.count {
if self[i-1] > self[i] { return false }
}
return true
}
}
// The way I want to get the computed property
[1, 1, 2, 3, 4, 5, 6, 7, 8].isSorted //= true
[2, 1, 3, 8, 5, 6, 7, 4, 8].isSorted //= false
Run Code Online (Sandbox Code Playgroud)
错误 Could not find an overload for '>' that accepts the supplied arguments
当然,我仍然有一个错误,因为Swift不知道如何比较元素.如何在Swift中实现此扩展?或者我在这里做错了什么?