在Swift中有多个类型的变量 [英] Have a variable with multiple types in Swift
本文介绍了在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所述:请注意,这仅按惯例"限制了可能的类型.任何模块(或源文件)都可以添加扩展名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屋!
查看全文