Wex*_*Wex 3 enums tuples swift
如果我有以下枚举:
enum FruitTuple
{
static let Apple = (shape:"round",colour:"red")
static let Orange = (shape:"round",colour:"orange")
static let Banana = (shape:"long",colour:"yellow")
}
Run Code Online (Sandbox Code Playgroud)
然后我有以下功能:
static func PrintFruit(fruit:FruitTuple)
{
let shape:String = fruit.shape
let colour:String = fruit.colour
print("Fruit is \(shape) and \(colour)")
}
Run Code Online (Sandbox Code Playgroud)
在fruit.shape和fruit.colour我得到错误:
Value of type 'FruitTuple' has no member 'shape'
很公平,所以我改变枚举有一个类型:
enum FruitTuple:(shape:String, colour:String)
{
static let Apple = (shape:"round",colour:"red")
static let Orange = (shape:"round",colour:"orange")
static let Banana = (shape:"long",colour:"yellow")
}
Run Code Online (Sandbox Code Playgroud)
但是在枚举声明中我得到了错误:
Inheritance from non-named type '(shape: String, colour: String)'
所以,问题是:是否有可能在枚举中有一个元组并且能够以这种方式引用它的组成部分?我只是错过了一些基本的东西吗?
正如@MartinR所指出的那样.此外,根据Apple文档,"枚举案例可以指定要与每个不同案例值一起存储的任何类型的关联值".如果您想继续使用enum,您可能需要执行以下操作:
static func PrintFruit(fruit:FruitTuple.Apple)
{
let shape:String = fruit.shape
let colour:String = fruit.colour
print("Fruit is \(shape) and \(colour)")
}
Run Code Online (Sandbox Code Playgroud)
我不确定你想要什么,但我想使用typealias可以帮助你实现目标.
typealias FruitTuple = (shape: String, colour: String)
enum Fruit
{
static let apple = FruitTuple("round" , "red")
static let orange = FruitTuple("round", "orange")
static let banana = FruitTuple("long", "yellow")
}
func printFruit(fruitTuple: FruitTuple)
{
let shape:String = fruitTuple.shape
let colour:String = fruitTuple.colour
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1031 次 |
| 最近记录: |