且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

swift 2 中引入的可选模式有哪些优点/用例?

更新时间:2023-01-31 18:29:25

我相信您将两个不同的概念混为一谈.诚然,语法并不是很直观,但我希望它们的用途在下面得到澄清.(我建议阅读关于 Patterns in 中的页面Swift 编程语言.)

I believe you're conflating two different concepts. Admittedly, the syntax isn't immediately intuitive, but I hope their uses are clarified below. (I recommend reading the page about Patterns in The Swift Programming Language.)

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

The "case condition" refers to the ability to write:

  • 如果 case «pattern» = «expr» { ... }
  • while case «pattern» = «expr» { ... }
  • for case «pattern» in «expr» { ... }
  • if case «pattern» = «expr» { ... }
  • while case «pattern» = «expr» { ... }
  • for case «pattern» in «expr» { ... }

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

These are particularly useful because they let you extract enum values without using switch.

你的例子,if case let x?= someOptional ...,是一个有效的例子,但是我相信它对 除 Optional 之外的枚举 最有用.

Your example, if case let x? = someOptional ..., is a valid example of this, however I believe it's most useful for enums besides Optional.

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 中使用的几乎任何模式一起使用.有时会很奇怪:

You can actually use case conditions with pretty much any pattern that you might normally use in a switch. It can be weird sometimes:

  • 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)如果 1...3 ~= 值)
  • if case let str as String = value { ... } (equivalent to if let str = value as? String)
  • if case is String = value { ... } (equivalent to if value is String)
  • if case 1...3 = value { ... } (equivalent to if (1...3).contains(value) or if 1...3 ~= value)

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

The optional pattern, on the other hand, is a pattern that lets you unwrap optionals in contexts besides a simple if let. It's particularly useful when used in a switch (similar to your username/password example):

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)")
    }
}