简体   繁体   中英

Generic conforming a protocol array

For a unique object that conforms to a ModelProtocol protocol I can test generic with success by writing :

if let _ = T.self as? ModelProtocol.Type { /* Do some stuff */}

But I'm stuck if I need to test the conformity of [ModelProtocol] protocol. I tried :

if let _ = T.self as? [ModelProtocol.Type] { /* Do some stuff */}

But Xcode throws a warning :

Cast from 'T.Type' to unrelated type '[ModelProtocol.Type]' always fails

How should I handle this case ?

You can do this using generic functions with constraints. For example:

//: Playground - noun: a place where people can play

import Cocoa

protocol ModelProtocol {
    var name: String { get }
}

struct Model: ModelProtocol {
    let name: String
}

func myFunction<T: Sequence>(sequence: T) where T.Iterator.Element == ModelProtocol {
    for model in sequence {
        print(model.name)
    }
}

let models: [ModelProtocol] = [Model(name: "one"), Model(name: "two")]
myFunction(sequence: models)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM