2017-07-18 96 views
0

switch-case用於比較static var s未按預期工作。但是,指定類型或直接比較的作品。請看下面:Swift static var in switch case

class AnimalHelper { 
    func loadAnimal(_ animal: Animal) { 

     // Doesn't compile 
     switch animal { 
      case .squirrel, .deer: loadGrass() 
      case .dolphin: return // not implemented 
      default: loadMeat() 
     } 

     // Direct comparison works 
     if animal == .squirrel || animal == .deer { 
      loadGrass() 
     } else if animal == .dolphin { 
      return // not implemented 
     } else { 
      loadMeat() 
     } 

     // Specifying the type explicitly also works 
     switch animal { 
      case Animal.squirrel, Animal.deer: loadGrass() 
      case Animal.dolphin: return // not implemented 
      default: loadMeat() 
     } 
    } 

    func loadGrass() {} 
    func loadMeat() {} 
} 

class Animal { 
    let id = 6 // Will be generated 
    let hasFourLegs = true 
    let numberOfEyes = 2 
    // ... // 

    static var squirrel: Animal { return .init() } 
    static var dolphin: Animal { return .init() } 
    static var puma: Animal { return .init() } 
    static var deer: Animal { return .init() } 
} 

extension Animal: Equatable { 
    public static func ==(lhs: Animal, rhs: Animal) -> Bool { 
     return lhs.id == rhs.id 
    } 
} 

我相信一些關於上面是不太正確的,因爲它的我得到以下編譯錯誤:

Enum case 'squirrel' not found in type 'Animal' 
Enum case 'deer' not found in type 'Animal' 
Enum case 'dolphin' not found in type 'Animal' 

請讓我知道如何檢查在switch-case中的相同性與if條件中的相同。

+2

用確切的錯誤信息更新您的問題並指出導致錯誤的行。 – rmaddy

回答

3

在斯威夫特,switch-case可以使用幾種不同的規則相匹配的switch - 值和case標籤:

  • enum情況下匹配

    在這種情況下,你可以使用點引線的情況下標籤,但不幸的是,您的Animal不是enum

    (這是不一樣的平等下面,如enum箱子可以具有相關聯的值。)

  • 圖案匹配操作者~=

    夫特搜索過載的switch - 值的類型並且case -label的類型(如果找到)適用運營商並使用Bool結果作爲指示匹配。 爲此,Swift需要推斷case-標籤的類型,而不依賴於switch-值,因此Swift無法推斷帶點引號的case-標籤的類型。

  • 平等==

    switch - 值是Equatable,夫特使用相等操作==switch - 值匹配到case -labels。

(可能還有更多,我現在不能想到的。)

行爲細節並不明確,但很難對編譯器來解決兩個規則 - 模式匹配平等。 (您可能需要定義與~=Equatable類型的自定義匹配。)

所以,斯威夫特3,在case -labels點引線符號只適用於enum類型。

但是,據我檢查,斯威夫特4已經做到了。試試Xcode 9(目前最新版本是beta 3),並且你的代碼會被編譯。此行爲可能在Xcode 9的發行版中發生變化,但您知道如何解決。