2015-10-30 76 views
4

對於優化級別快速的一些原因,我的比較方法返回額外的3個元素。這是我的代碼問題,還是Swift 2.0中的錯誤? XCode 7.0和XCode 7.1(2個不同的Mac)出現問題。優化級別影響比較枚舉

func ==(lhs: ViewController.ItemType, rhs: ViewController.ItemType) -> Bool { 
    // For some reasons for different types e.g. .CType and .AType it returns true 
    switch(lhs, rhs) { 
    case (.AType, .AType): 
     return true 
    case (let .BType(type1), let .BType(type2)): 
     return type1 == type2 
    case (.CType,.CType): 
     return true 
    case (.DType, .DType): 
     return true 
    case (.EType,.EType): 
     return true 
    default: 
     return false 
    } 
} 

class ViewController: UIViewController { 
    enum ItemType { 
     case AType 
     case BType(Int) 
     case CType 
     case DType 
     case EType 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     let array:[ItemType] = [.AType, .BType(10), .CType, .DType, .EType] 
     let array2 = array.filter { (itemType:ItemType) -> Bool in 
      return itemType == .CType 
     } 

     // Prints 1 on [-ONone] optimization and 4 for [-OFast] optimization. 
     print("Items \(array2.count):\n\(array2)") 
    } 
} 
+0

你更新到Xcode 7.1嗎? – matt

+0

它在不同的XCode版本上進行了測試,結果相同。 – Szu

+0

我問,因爲它看起來與此相關:http://stackoverflow.com/questions/32533909/accessor-gives-the-wrong-value-in-swift-1-2-2-0-release-build-only它很可能是這個bug的一部分仍然沒有修復。枚舉以高度優化的方式存儲,這可能有副作用。 – matt

回答

0

我一直在玩這個。這裏有一個簡單的例子:

struct Foo { 
    enum Enum { 
     case A 
     case B 
     case C(Int) 
    } 
} 

func ==(lhs: Foo.Enum, rhs: Foo.Enum) -> Bool { 
    print("comparing \(lhs) == \(rhs) -> ", terminator: "") 

    switch(lhs, rhs) { 
    case (.A, .A): 
     return true 
    case (.B,.B): 
     return true 
    default: 
     return false 
    } 
} 

func test() { 
    print( Foo.Enum.A   == .B) 
    print([ Foo.Enum.A ][0]  == .B) 
    print([ Foo.Enum.A ].first! == .B) 
    for itemType in [ Foo.Enum.A ] { print(itemType == .B) } 
} 

test() 

在-Onone builds中,這打印出預期的四次。在優化的構建它打印...當

comparing A == B -> false 
comparing A == B -> false 
comparing A == B -> true 
comparing A == B -> true 

該缺陷消失:

  • 該測試是在外部文件範圍(不是在功能)
  • 執行的正常功能是用來代替操作者的==
  • 枚舉不是嵌套在另一種類型的
  • case C或相關聯的類型被移除
  • print語句插入switch案件

我已經和Xcode 7.1測試。這個bug絕對應該在bugreport.apple.com提交