创建枚举实例

问题描述 投票:1回答:2

假设我有

enum Example {
  case one(string: String)
  case two(string: String)
}

现在我有

let x = Example.one(string: "Hello")

问题:

let y = ?

如何在e中创建相同枚举的另一个实例,以便最终得到y == .one("World")

swift enums
2个回答
0
投票

具有关联值的enum案例的类型是具有与关联值的类型对应的参数的闭包,并且具有对应于enum的类型的返回(返回的值是特定的case)。即,对于上面的例子,Example.oneExample.two的类型是(String) -> Example,其中这两种情况表达的闭包产生不同的结果; .one(...).two(...)的实例。

因此,您可以简单地使用一个计算属性来返回已经存在的闭包Example.oneExample.two(如果self分别是onetwo),而不是编写自己的方法来“克隆”给定的情况,随后可以调用String参数构造一个新的Example实例(值.one.two;以及提供的相关String值)。

Ef。:

enum Example {
    case one(string: String) // type: (String) -> Example
    case two(string: String) // type: (String) -> Example

    var caseClosure: (String) -> Example {
        switch self {
        case .one: return Example.one
        case .two: return Example.two
        }
    }
}

let x = Example.one(string: "Hello") // .one("Hello")
let y = x.caseClosure("World")       // .one("World")

但是,由于您的示例中的所有情况都是相同类型的闭包,即(String) -> Example(即具有相同数量和类型的关联值),您也可以,as already proposed in a comment by @Hamish,包装一个没有关联值的enum struct以及总是String“相关值”是struct的一个单独成员。例如。用一些初始化器扩展Hamish的例子:

struct S {
    enum E {
        case one
        case two
    }
    var e: E
    var string: String // Since "associated value" is always the same type
    init(_ e: E, string: String) {
        self.e = e
        self.string = string
    }
    init(from s: S, string: String) {
        self.e = s.e
        self.string = string
    }
}

let x = S(.one, string: "Hello")
let y = S(from: x, string: "World")
let z = S(x.e, string: "World")

1
投票

你可以通过调用初始化程序,就像你为x做的那样:

enum Example {
    case one(string: String)
    case two(string: String)
}

let x = Example.one(string: "Hello")
print(x) // Prints one("Hello")

let y = Example.one(string: "World")
print(y) // Prints one("World")

此外,你的枚举声明中的,是错误的,必须删除。


更新:

评论更详细地解释了这个问题,所以这是我更新的答案:

解决此问题的一种优雅方法是在原始枚举类型Example上使用函数。

enum Example {
    case one(string: String)
    case two(string: String)

    func cloneWith(string: String) -> Example {
        switch self {
        case .one:
            return .one(string: string)
        case .two:
            return .two(string: string)
        }
    }
}

let x = Example.one(string: "Hello")
print(x) // Prints one("Hello")

let y = x.cloneWith(string: "World")
print(y) // Prints one("World")
© www.soinside.com 2019 - 2024. All rights reserved.