gpt4 book ai didi

Swift 隐式协议(protocol)

转载 作者:搜寻专家 更新时间:2023-11-01 07:34:17 25 4
gpt4 key购买 nike

有什么方法可以在 Swift 中描述一个具有 max 属性的 IntegerType 吗? (类似于go中隐式接口(interface)的东西)

没有描述max 属性的协议(protocol),即使我创建了一个,IntegerType 也没有明确实现它。

所以基本上我在寻找类似的东西:

class Test<T: IntegerType where ?> { // <- ? = something like 'has a "max: Self"' property
}

let t = Test<UInt8>()

或者类似的东西:

implicit protocol IntegerTypeWithMax: IntegerType {
static var max: Self { get }
}

class Test<T: IntegerTypeWithMax> {
}

let t = Test<UInt8>()

最佳答案

Swift 编译器不会自动推断协议(protocol)一致性即使一个类型实现了所有必需的属性/方法。所以如果你定义

protocol IntegerTypeWithMax: IntegerType {
static var max: Self { get }
}

你仍然需要制作你感兴趣的整数类型符合该协议(protocol):

extension UInt8 : IntegerTypeWithMax { }
extension UInt16 : IntegerTypeWithMax { }
// ...

扩展 block 是空的,因为UInt8UInt16已经有了静态 max 方法。

然后

class Test<T: IntegerTypeWithMax> {
}

let t = Test<UInt8>()

按预期编译和工作。

关于Swift 隐式协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30963581/

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