如何在 Swift 中扩展类型化数组? [英] How can I extend typed Arrays in Swift?

查看:40
本文介绍了如何在 Swift 中扩展类型化数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用自定义功能实用程序扩展 Swift 的 ArrayT[] 类型?

How can I extend Swift's Array<T> or T[] type with custom functional utils?

浏览 Swift 的 API 文档表明 Array 方法是 T[] 的扩展,例如:

Browsing around Swift's API docs shows that Array methods are an extension of the T[], e.g:

extension T[] : ArrayType {
    //...
    init()

    var count: Int { get }

    var capacity: Int { get }

    var isEmpty: Bool { get }

    func copy() -> T[]
}

复制和粘贴相同的源并尝试任何变体时:

When copying and pasting the same source and trying any variations like:

extension T[] : ArrayType {
    func foo(){}
}

extension T[] {
    func foo(){}
}

它无法构建并出现错误:

It fails to build with the error:

标称类型T[]不能扩展

使用完整类型定义失败,Use of undefined type 'T',即:

Using the full type definition fails with Use of undefined type 'T', i.e:

extension Array<T> {
    func foo(){}
}

而且它也因 ArrayArray 而失败.

And it also fails with Array<T : Any> and Array<String>.

奇怪的是 Swift 允许我扩展一个无类型数组:

Curiously Swift lets me extend an untyped array with:

extension Array {
    func each(fn: (Any) -> ()) {
        for i in self {
            fn(i)
        }
    }
}

它让我打电话:

[1,2,3].each(println)

但我无法创建适当的泛型类型扩展,因为类型在流经方法时似乎丢失了,例如尝试 替换Swift的内置过滤器:

But I can't create a proper generic type extension as the type seems to be lost when it flows through the method, e.g trying to replace Swift's built-in filter with:

extension Array {
    func find<T>(fn: (T) -> Bool) -> T[] {
        var to = T[]()
        for x in self {
            let t = x as T
            if fn(t) {
                to += t
            }
        }
        return to
    }
}

但是编译器将其视为无类型的,它仍然允许使用以下命令调用扩展:

But the compiler treats it as untyped where it still allows calling the extension with:

["A","B","C"].find { $0 > "A" }

当使用调试器单步执行时指示类型为 Swift.String 但尝试像 String 一样访问它而不先将其转换为 String 是构建错误,即:

And when stepped-thru with a debugger indicates the type is Swift.String but it's a build error to try access it like a String without casting it to String first, i.e:

["A","B","C"].find { ($0 as String).compare("A") > 0 }

有谁知道创建类似于内置扩展的类型化扩展方法的正确方法是什么?

Does anyone know what's the proper way to create a typed extension method that acts like the built-in extensions?

推荐答案

对于使用扩展类型化数组,以下对我有用(Swift 2.2).例如,对类型化数组进行排序:

For extending typed arrays with classes, the below works for me (Swift 2.2). For example, sorting a typed array:

class HighScoreEntry {
    let score:Int
}

extension Array where Element == HighScoreEntry {
    func sort() -> [HighScoreEntry] {
      return sort { $0.score < $1.score }
    }
}

尝试使用 structtypealias 执行此操作会产生错误:

Trying to do this with a struct or typealias will give an error:

Type 'Element' constrained to a non-protocol type 'HighScoreEntry'

更新:

要使用非类扩展类型化数组,请使用以下方法:

To extend typed arrays with non-classes use the following approach:

typealias HighScoreEntry = (Int)

extension SequenceType where Generator.Element == HighScoreEntry {
    func sort() -> [HighScoreEntry] {
      return sort { $0 < $1 }
    }
}

Swift 3 中,某些类型已重命名:

In Swift 3 some types have been renamed:

extension Sequence where Iterator.Element == HighScoreEntry 
{
    // ...
}

这篇关于如何在 Swift 中扩展类型化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆