gpt4 book ai didi

swift - 如何使用带有嵌套枚举的 switch 语句?

转载 作者:IT王子 更新时间:2023-10-29 05:16:20 24 4
gpt4 key购买 nike

我为 Instagram 端点创建了一个枚举,其嵌套枚举类似于 Moya .

enum Instagram {
enum Media {
case Popular
case Shortcode(id: String)
case Search(lat: Float, lng: Float, distance: Int)
}
enum Users {
case User(id: String)
case Feed
case Recent(id: String)
}
}

我想返回每个端点的路径。

extension Instagram: TargetType {
var path: String {
switch self {
case .Media.Shortcode(let id):
return "/media/shortcode"
}
}
}

但是,我在上述 path 的 switch 语句中遇到错误。

Enum case Shortcode is not a member of type Instagram

如何修复?

Advanced Practical Enums

最佳答案

出于某些原因,我添加了一个更笼统的答案。

  1. 这是关于嵌套枚举和 switch 语句的唯一未决问题。 The other one is sadly closed .
  2. 唯一合法的答案没有说明如何将嵌套枚举的值分配给符号。语法对我来说不直观。
  3. 其他答案都没有大量案例。
  4. 嵌套 3 层的枚举更能说明所需的语法。使用 efremidze answer 还是花了我一段时间才弄明白。

enum Action {
case fighter(F)
case weapon(W)

enum F {
case attack(A)
case defend(D)
case hurt(H)

enum A {
case fail
case success
}
enum D {
case fail
case success
}
enum H {
case none
case some
}
}
enum W {
case swing
case back
}
}

// Matches "3 deep"
let action = Action.fighter(.attack(.fail))
// Matches "1 deep" because more general case listed first.
let action2 = Action.weapon(.swing)

switch action {
case .fighter(.attack(.fail)):
print("3 deep")
case .weapon:
print("1 deep")
case .weapon(.swing):
print("2 deep to case")
case .fighter(.attack):
print("2 deep to another enum level")
default:
print("WTF enum")
}

关于swift - 如何使用带有嵌套枚举的 switch 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34822345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com