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

标签 swift swift4

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

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

我遇到的问题是 compactMap 在这里不起作用。 nil 值仍在生成的数组 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 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().

关于swift - 在类扩展中包装泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54261341/

相关文章:

android - 在 iOS 和 Android 上唯一标识 Beacon

swift - 在 swift 中使用内部结构时引用包含类的属性

ios - swift 4 : How can I make the keyboard always appear and never disappear?

ios - 将数据从 Collectionview 传递到 UIcollectionResuableview

swift - 一键式 SCNAction?

json - 将 JSON 转换为属性选项数组

ios - swift 4 访问库中的 C 结构值

ios - 切换标签时向 Controller 发送数据

Swift 包管理器找不到模块

ios - 如何在单击按钮时向页面 View Controller 添加详细 View