在 Swift 中创建一个扩展以从数组中过滤 nils [英] Creating an extension to filter nils from an Array in Swift

查看:19
本文介绍了在 Swift 中创建一个扩展以从数组中过滤 nils的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 Array 编写一个扩展,它允许将可选 T 的数组转换为非可选 T 的数组.

I'm trying to write an extension to Array which will allow an array of optional T's to be transformed into an array of non-optional T's.

例如这可以写成这样的自由函数:

e.g. this could be written as a free function like this:

func removeAllNils(array: [T?]) -> [T] {
    return array
        .filter({ $0 != nil })   // remove nils, still a [T?]
        .map({ $0! })            // convert each element from a T? to a T
}

但是,我无法让它作为扩展工作.我试图告诉编译器该扩展仅适用于可选值的数组.这是我目前所拥有的:

But, I can't get this to work as an extension. I'm trying to tell the compiler that the extension only applies to Arrays of optional values. This is what I have so far:

extension Array {
    func filterNils<U, T: Optional<U>>() -> [U] {
        return filter({ $0 != nil }).map({ $0! })
    }
}

(它不会编译!)

推荐答案

不能限制为泛型结构或类定义的类型 - 数组旨在用于任何类型,因此您无法添加有效的方法对于类型的子集.类型约束只能在声明泛型类型时指定

It's not possible to restrict the type defined for a generic struct or class - the array is designed to work with any type, so you cannot add a method that works for a subset of types. Type constraints can only be specified when declaring the generic type

实现您需要的唯一方法是创建全局函数或静态方法 - 在后一种情况下:

The only way to achieve what you need is by creating either a global function or a static method - in the latter case:

extension Array {
    static func filterNils(_ array: [Element?]) -> [Element] {
        return array.filter { $0 != nil }.map { $0! }
    }
}

var array:[Int?] = [1, nil, 2, 3, nil]

Array.filterNils(array)

或者简单地使用 compactMap(以前是 flatMap),它可以用来删除所有的 nil 值:

Or simply use compactMap (previously flatMap), which can be used to remove all nil values:

[1, 2, nil, 4].compactMap { $0 } // Returns [1, 2, 4]

这篇关于在 Swift 中创建一个扩展以从数组中过滤 nils的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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