ios - 如何在集合类型约束中制作泛型?

标签 ios swift generics option-type

我一直在尝试从字符串数组中提取非零值。如下图。但是,我的学长希望它也能够从其他类型中提取非 nil 值

我读到,泛型 可以帮助我处理不同的类型。我怎样才能使用泛型,以便我也可以使用以下类似扩展来处理其他类型?

getNonNil 必须返回提取的特定类型的非 nil 值(即 如果数组是 [String?],它必须返回 [String],如果 [Int? ])

因为我还要做进一步的计算。

我试过的如下:

import Foundation
// Extended the collection-type so that collectiontype is constrained to having element with optional strings
extension CollectionType where Self.Generator.Element == Optional<String>{
    func getNonNil() -> [String] {
        // filter out all nil elements and forcefully unwrap them using map
        return self.filter({$0 != nil}).map({$0!})
    }
}

// Usage
let x: [String?] = ["Er", "Err", nil, "errr"]

x.getNonNil().forEach { (str) in
    print(str)
}

最佳答案

对于 getNonNil 你可以简单地使用

x.flatMap { $0 }
// returns ["Er", "Err", "errr"] which is [String]

对于最初的问题,通常您可以为 Optional 类型引入一个协议(protocol)(例如通过 muukii/OptionalProtocol 包):

protocol OptionalProtocol {
    associatedtype Wrapped
    var value: Wrapped? { get }
}

extension Optional: OptionalProtocol {
    public var value: Wrapped? { return self }
}

extension CollectionType where Self.Generator.Element: OptionalProtocol {
    func getNonNil() -> [Self.Generator.Element.Wrapped] {
        ...
    }
}

关于ios - 如何在集合类型约束中制作泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38434125/

相关文章:

ios - 在导航栏中快速添加图像

ios - 如何更新CNContact?获取 CNErrorDomain 代码=2

java - 为什么这段带有泛型的java代码不能编译

generics - Dart,不能调用Generic的方法

ios - Google Analytics 3.03 iOS SDK 中的应用程序速度

IOS开发(Swift) : If value exists, 取当前数组索引的值

ios - 解码错误 : The data couldn't be read. Alamofire

java - 如何获取类型为 T 的字段的类?

iphone - 从 UITableview 向上滚动时的操作

ios - 部分改变UIView的背景颜色