gpt4 book ai didi

swift - 你能只扩展使用字符串作为原始值类型的 RawRepresentables 吗?

转载 作者:行者123 更新时间:2023-11-28 06:07:30 28 4
gpt4 key购买 nike

我正在尝试编写一个基于字符串扩展枚举的扩展。我知道扩展所有枚举的方法是扩展 RawRepresentable,但我希望它仅限于字符串。

extension RawRepresentable where RawRepresentable.RawValue == String{

func foo(){

let myRawValue:String = self.rawValue

}
}

那么如何指定“where”子句来实现这一点?

最佳答案

要仅基于 String 扩展 RawRepresentablewhere 子句就是 where RawValue == String:

extension RawRepresentable where RawValue == String {

func foo() {
let myRawValue:String = self.rawValue
print(myRawValue)
}
}


enum Flintstone: String {
case fred, wilma, pebbles
}

Flintstone.fred.foo() // fred

关于swift - 你能只扩展使用字符串作为原始值类型的 RawRepresentables 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47804169/

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