如何使集合类型约束中的泛型? [英] How to make generics in collection type constraint?

查看:120
本文介绍了如何使集合类型约束中的泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图从字符串数组中提取非零值。如下所示。但是,我的资深人士希望它能够从其他类型中提取非零值 我读过泛型可以帮助我处理不同的类型。我怎样才能使用泛型,以便我可以像使用扩展一样使用其他类型?

getNonNil 必须返回特定类型的提取的非零值(即 if array is [ String?]它必须返回[String],如果[Int?] 返回[Int])

因为我必须做进一步的计算。



我试过的是:

  import Foundation 
//扩展集合类型,使得collectiontype被限制为具有可选字符串的元素
extension CollectionType其中Self.Generator.Element ==可选< String> {
func getNonNil() - > [String] {
//过滤掉所有nil元素并强制使用map
打开它们返回self.filter({$ 0!= nil})。map({$ 0!})
}
}

//用法
让x:[String?] = [Er,Err,nil,errr]

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



  x.flatMap {$ 0} 
//返回[Er,Err,errr],它是[String]






对于原始问题,通常您可以将协议引入可选类型(例如,通过 muukii / OptionalProtocol 包):

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

扩展可选:OptionalProtocol {
public var value:Wrapped? {return self}
}

扩展名CollectionType其中Self.Generator.Element:OptionalProtocol {
func getNonNil() - > [Self.Generator.Element.Wrapped] {
...
}
}


I have been trying to extract non-nil values from the String array. Like below. But, my senior wants it to be able to extract non-nil values from other types too.

I read, generics could help me for handling different types. How can I use generics so that I get to use following like extension to work with other types too?

getNonNil must return the extracted non-nil values of the specific type (i.e. if array is [String?] it must return [String], returns [Int] if [Int?])

Because I have to do further calculations.

What I have tried is below:

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)
}

解决方案

For getNonNil you could simply use

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


For the original question, typically you could introduce a protocol to the Optional type (e.g. via the muukii/OptionalProtocol package):

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] {
        ...
    }
}

这篇关于如何使集合类型约束中的泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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