在 Swift 中有一个具有多种类型的变量 [英] Have a variable with multiple types in Swift

查看:30
本文介绍了在 Swift 中有一个具有多种类型的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个变量,它可以有多种类型(只有一种,我定义了),比如:

I would like to have a variable, which can have multiple types (only ones, I defined), like:

var example: String, Int = 0
example = "hi"

这个变量应该只能保存 Int 和 String 类型的值.

This variable should be able to hold only values of type Int and String.

这可能吗?

感谢您的帮助;)

推荐答案

这里是您实现它的方法.完全符合您的预期.

protocol StringOrInt { }

extension Int: StringOrInt { }
extension String: StringOrInt { }

var a: StringOrInt = "10"
a = 10 //> 10
a = "q" //> "q"
a = 0.8 //> Error

注意!我不建议您在生产代码中使用它.这可能会让您的队友感到困惑.

NB! I would not suggest you to use it in production code. It might be confusing for your teammates.

UPD: 正如@Martin R 提到的:请注意,这仅按照约定"限制了可能的类型.任何模块(或源文件)都可以添加 extension MyType: StringOrInt { } 一致性.

UPD: as @Martin R mentioned: Note that this restricts the possible types only "by convention." Any module (or source file) can add a extension MyType: StringOrInt { } conformance.

这篇关于在 Swift 中有一个具有多种类型的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆