在类扩展中包装泛型方法 [英] Wrapping a generic method in a class extension

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

问题描述

我正在尝试将通用 Array 方法 compactMap 包装在 Array 扩展中,以使该方法的目的更具意义/可读性.我只是想获取一个 Optionals 数组并从中删除所有 nil 值.

I'm trying to wrap the generic Array method compactMap inside an Array extension to give the purpose of the method more meaning/readability. I'm simply trying to take an Array of Optionals and remove any and all nil values from it.

extension Array {
    public func removeNilElements() -> [Element] {
        let noNils = self.compactMap { $0 }
        return noNils // nil values still exist
    }
}

我遇到的问题是 compactMap 在这里不起作用.nil 值仍然在结果数组 noNils 中.当我直接使用 compactMap 方法而不使用这个包装器时,我得到了一个没有 nil 值的数组的期望结果.

The problem I am having is that compactMap here is not working. nil values are still in the resulting Array noNils. When I use the compactMap method directly without using this wrapper, I get the desired result of an Array with no nil values.

let buttons = [actionMenuButton, createButton]   // [UIBarButtonItem?]
let nonNilButtons = buttons.compactMap { $0 }    // works correctly
let nonNilButtons2 = buttons.removeNilElements() // not working

我是否没有正确设计我的扩展方法?

Am I not designing my extension method correctly?

推荐答案

你必须为一个可选元素的数组定义方法,并且返回类型为对应的非可选数组.这可以通过通用函数来完成:

You have to define the method for an array of optional elements, and the return type as the corresponding array of non-optionals. This can be done with a generic function:

extension Array {
    public func removingNilElements<T>() -> [T] where Element == T?    {
        let noNils = self.compactMap { $0 }
        return noNils
    }
}

示例:

let a = [1, 2, nil, 3, nil, 4]   // The type of a is [Int?]
let b = a.removingNilElements()  // The type of b is [Int]
print(b) // [1, 2, 3, 4]

在您的代码中,$0 具有(非可选)类型 Element,它只是被编译器包装成一个可选的,以匹配compactMap().

In your code, $0 has the (non-optional) type Element, and it just wrapped by the compiler into an optional in order to match the argument type of compactMap().

这篇关于在类扩展中包装泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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