加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 在类扩展中包装泛型方法

发布时间:2020-12-14 04:36:27 所属栏目:百科 来源:网络整理
导读:我正在尝试将通用Array方法compactMap包装在Array扩展中,以使该方法的目的更具意义/可读性.我只是试图获取一个Option of Optionals并从中删除任何和所有的nil值. extension Array { public func removeNilElements() - [Element] { let noNils = self.compac
我正在尝试将通用Array方法compactMap包装在Array扩展中,以使该方法的目的更具意义/可读性.我只是试图获取一个Option of Optionals并从中删除任何和所有的nil值.

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

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

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

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

解决方法

您必须为可选元素数组定义方法,并将返回类型定义为非选项的相应数组.这可以使用通用函数完成:

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

例:

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

在你的代码中,$0有(非可选)类型的元素,它只是由编译器包装成一个可选项,以匹配compactMap()的参数类型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读