避免隐性枚举原始价值转换

发布于 2025-02-12 08:43:49 字数 705 浏览 0 评论 0原文

在这种情况下,我试图避免将枚举的隐式转换为字符串:

enum Animal {
    case cat
}

func getTag(forAnimal animal: Animal) -> String {
    // fails with "Cannot convert value of type 'Animal' to specified type 'String' which is good!!!"
    // return animal

    // does return "cat" which I don't want developers to be able to do!!!
    return "\(animal)"
}

print(getTag(forAnimal: .cat)) // prints "cat"

第二个返回起作用是因为在对象上打印呼叫.description。 Swift显然会自动采用CustomStringConvertible,并将案例名称返回为string。编辑:显然,打印不调用.description

我考虑过符合协议并提醒开发人员(可能会引发错误)。

但是我真正想做的是让枚举不符合所述协议,或者有编译时间错误。这可能吗?

I am attempting to avoid the implicit conversion of an enum into a string in a case like this:

enum Animal {
    case cat
}

func getTag(forAnimal animal: Animal) -> String {
    // fails with "Cannot convert value of type 'Animal' to specified type 'String' which is good!!!"
    // return animal

    // does return "cat" which I don't want developers to be able to do!!!
    return "\(animal)"
}

print(getTag(forAnimal: .cat)) // prints "cat"

The 2nd return works because print calls .description on the object.
Swift apparently adopts CustomStringConvertible for enums automatically and returns the case name as a String. Edit: Apparently , print does not call .description.

I thought about conforming to the protocol and alert developers (with something that throws an error perhaps).

But what I am wanting to do really is to have the enum NOT conform to said protocol, or have a compile-time error. Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瀞厅☆埖开 2025-02-19 08:43:49

您可以扩展String Interpolation并为该特定类型实现AppendInterpolation方法。这样,您可以简单地确定枚举将如何插值其价值。如果您不希望生成任何字符串,您只需要创建一个虚拟方法:

enum Animal {
    case cat
}

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: Animal) { }
}

测试:

"\(Animal.cat)"  // "" it results in an empty string

如果要编译时间错误,则可以添加不弃用的可用性警告:

“在此处输入图像说明”

@available(swift, deprecated: 2)
extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: Animal) { }
}

You can extend StringInterpolation and implement an appendInterpolation method for that specific type. This way you can simply determine how your enumeration would interpolate its value. If you don't want any string to be generated you just need to create a dummy method:

enum Animal {
    case cat
}

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: Animal) { }
}

Testing:

"\(Animal.cat)"  // "" it results in an empty string

If you want a compile-time error you can add a deprecated availability warning:

enter image description here

@available(swift, deprecated: 2)
extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: Animal) { }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文