带有Optional AssociatedType的协议扩展

时间:2017-03-28 10:10:55

标签: swift generics swift-protocols

我想扩展具有关联类型Optional<Something>的协议。换句话说:我想扩展具有声明的具体泛型SomeType

var a: SomeType<Optional<Something>>

但不扩展以下类型:

var b: SomeType<Something>

这是我想要实现的更详细的例子。 显然这个例子是错误的。使用Any尤其错误,但我希望这个例子能突出意图:

var thisSequenceIWantToExtend: [Optional<String>] = []
var alsoWantToExtend: [Optional<Int>] = []
var dontWantToExtend: [Int] = []


extension Sequence where Iterator.Element == Optional<Any>
{
    func somethingWithOptionalSequence(){
        print("XXX")
    }
}

//these should work
thisSequenceIWantToExtend.somethingWithOptionalSequence()
alsoWantToExtend.somethingWithOptionalSequence()

//this shouldn't be extended
//dontWantToExtend.somethingWithOptionalSequence()

回答(Swift3):

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

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

}

extension Collection where Self.Iterator.Element: OptionalProtocol {
    func nonNil()->[Iterator.Element.Wrapped] {
        return self.flatMap{ $0.value }
    }
}


var a: [Optional<String>] = ["a",nil,"B"]
var b: [Optional<Int>] = [1,2,3]
var c: [Int] = [1,2,3]

a.nonNil()
b.nonNil()

// can't do that
//c.nonNil()

0 个答案:

没有答案