swift - 在 Swift 中访问枚举关联值

标签 swift

在这段代码中,我编写了一个非常无用的枚举,它用 Int 或 Float 定义了一个可能的 Number

我不明白如何访问我通过关联设置的值。如果我尝试打印它,我只会得到 (Enum Value)

enum Number {
    case int (Int)
    case float (Float)
}

let integer = Number.int(10)
let float = Number.float(10.5)
println("integer is \(integer)")
println("float is \(float)")

最佳答案

为了完整起见,枚举的关联值也可以使用带有模式匹配的 if 语句来访问。这是原始代码的解决方案:

enum Number {
  case int (Int)
  case float (Float)
}

let integer = Number.int(10)
let float = Number.float(10.5)

if case let .int(i) = integer {
  print("integer is \(i)")
}
if case let .float(f) = float {
  print("float is \(f)")
}

此解决方案在以下内容中有详细描述:https://appventure.me/2015/10/17/advanced-practical-enum-examples/

关于swift - 在 Swift 中访问枚举关联值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24263539/

相关文章:

swift - 当我显示新的 UIView 时,UINavigationBar 失去色调颜色

ios - 在新窗口或选项卡中打开的链接未在 native iOS 中加载

ios - Swift `Decodable` 不适用于嵌套的 JSON 对象,除非嵌套是一个数组

ios - 这是为什么?按钮切换其背景图像被其他单元格重复使用的自定义单元格的状态

ios - CFStreamCreateBoundPair 不能释放

ios - iOS中 "keyChain"和 "iCloud keychain"的区别

swift - 如何在 Swift 中的两个初始化函数之间共享一个初始化函数?

ios - 显示边界外的图像 - iOS/Swift

ios - 函数在完成处理程序完成之前完成它的执行

ios - "Cannot assign value of type ' 无效 ' to type ' PDFAction?为 PDFAnnotation 设置操作时出现 '"错误