我怎样才能在斯威夫特扩展类型数组? [英] How can I extend typed Arrays in Swift?

查看:116
本文介绍了我怎样才能在斯威夫特扩展类型数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何延长斯威夫特的阵列< T> T [] 自定义功能utils的类型?

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

各地斯威夫特的API文档浏览显示,阵列方法是为扩展名的 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 [] 不能延长

使用完整的类型定义失败,使用未定义类型'T'的,即:

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

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

和它也失败,阵列&LT; T:。任何&GT; 阵列&LT;弦乐&GT;

奇怪的是斯威夫特让我带扩展非类型化的数组:

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)

但作为类型似乎是失去了当它流经的方法,如争取的更换斯威夫特的内建有过滤器:

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 但它是一个生成错误尝试像一个字符串访问它,没有它转换为字符串第一,即:

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?

推荐答案

一个尝试不同的事情解决后似乎删除&LT;从喜欢签名; T&GT

After a while trying different things the solution seems to remove the <T> from the signature like:

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

现在按预期工作不生成错误:

Which now works as intended without build errors:

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

这篇关于我怎样才能在斯威夫特扩展类型数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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