优化级别会影响比较枚举

时间:2015-10-30 14:40:58

标签: ios swift swift2

由于某些原因,优化级别快我的比较方法返回额外的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)")
    }
}

1 个答案:

答案 0 :(得分: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构建中,打印预期的四次true。在优化的构建中,它打印......

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上提交

相关问题