gpt4 book ai didi

作为通用参数的 Swift 协议(protocol)

转载 作者:搜寻专家 更新时间:2023-10-31 23:00:46 26 4
gpt4 key购买 nike

给定这个类:

class ServiceRegistry {

var store = [String : AnyObject]()
var allRegisteredType: [String] {
return store.map { $0.0 }
}

func registerInstance<T>(instance:AnyObject, forType type: T.Type) {
store[String(type)] = instance
}

func instanceForType<T>(type: T.Type) -> T? {
return store[String(type)] as? T
}
}

有没有一种方法可以强制 T 必须是协议(protocol),而无需使用 @obj?

最佳答案

这是我的类型断言技术的修改版本。我添加了"as?AnyClass"断言,这样类型只能是协议(protocol)类型。 可能有一种更优雅的方式来做到这一点,但通过我的笔记和关于类断言的研究,这就是我想出的。

import Foundation

protocol IDescribable:class{}
class A:IDescribable{}
class B:A{}

let a = A()
let b = B()

func ofType<T>(instance:Any?,_ type:T.Type) -> T?{/*<--we use the ? char so that it can also return a nil*/
if(instance as? T != nil && type as? AnyClass == nil){return instance as? T}
return nil
}

Swift.print(ofType(a,A.self))//nil
Swift.print(ofType(a,IDescribable.self))//A
Swift.print(ofType(b,B.self))//nil

关于作为通用参数的 Swift 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35787085/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com