【问题标题】:What are the advantages/use cases of optional patterns introduced in swift 2?swift 2 中引入的可选模式有哪些优点/用例?
【发布时间】:2016-04-27 04:06:49
【问题描述】:

对于像if letguard 这样的简单情况,我看不到优势,

if case let x? = someOptional where ... {
  ...
}

//I don't see the advantage over the original if let

if let x = someOptional where ... {
  ...
}

对于for-case-let 案例,为了简化可选集合的使用,我真的希望 swift 可以更进一步:

for case let x? in optionalArray {
  ...
}

//Wouldn't it be better if we could just write

for let x? in optionalArray {
  ...
}

在google了一段时间后,我发现唯一有用的是这个“Swift 2 Pattern Matching: Unwrapping Multiple Optionals”:

switch (username, password) {
case let (username?, password?):
    print("Success!")
case let (username?, nil):
    print("Password is missing")
...

那么引入可选模式还有其他好处吗?

【问题讨论】:

  • 在我的观察中,如果你想在没有完整的 switch-case 的情况下检查枚举的值,这个 'if case' 或 'while case' 或 'for case' 是很方便的构造。

标签: swift swift2 switch-statement pattern-matching optional


【解决方案1】:

我相信您将两个不同的概念混为一谈。诚然,语法不是立即直观的,但我希望它们的用途在下面得到澄清。 (我推荐阅读关于Patterns in The Swift Programming Language的页面。)

case条件

“案例条件”指的是写作能力:

  • if <strong>case</strong> <em>«pattern»</em> = <em>«expr»</em> { ... }
  • while <strong>case</strong> <em>«pattern»</em> = <em>«expr»</em> { ... }
  • for <strong>case</strong> <em>«pattern»</em> in <em>«expr»</em> { ... }

这些特别有用,因为它们让您无需使用switch即可提取枚举值。

您的示例if case let x? = someOptional ... 是一个有效的示例,但我相信它对 除可选枚举之外的枚举 最有用。

enum MyEnum {
    case A
    case B(Int)
    case C(String)
}

func extractStringsFrom(values: [MyEnum]) -> String {
    var result = ""

    // Without case conditions, we have to use a switch
    for value in values {
        switch value {
        case let .C(str):
            result += str
        default:
            break
        }
    }

    // With a case condition, it's much simpler:
    for case let .C(str) in values {
        result += str
    }

    return result
}

实际上,您几乎可以将 case 条件与您通常在 switch 中使用的任何模式一起使用。有时会很奇怪:

  • if case let str as String = value { ... }(相当于if let str = value as? String
  • if case is String = value { ... }(相当于if value is String
  • if case 1...3 = value { ... }(相当于if (1...3).contains(value)if 1...3 ~= value

可选模式,又名let x?

另一方面,可选模式是一种模式,除了简单的if let 之外,它还允许您在上下文中展开可选选项。它在 switch 中使用时特别有用(类似于您的用户名/密码示例):

func doSomething(value: Int?) {
    switch value {
    //case 2:  // Not allowed
    case 2?:
        print("found two")

    case nil:
        print("found nil")

    case let x:
        print("found a different number: \(x)")
    }
}

【讨论】:

  • 比苹果文档好多了!谢谢。
  • 好答案。然而,一件奇怪的事情是,case 2,您在上一个示例中注释为不允许的,实际上有效。似乎编译器正在幕后进行一些向上转换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-18
  • 2011-01-12
相关资源
最近更新 更多