ios – 优化级别会影响比较枚举

前端之家收集整理的这篇文章主要介绍了ios – 优化级别会影响比较枚举前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
出于某些原因,优化级别快速我的比较方法返回额外的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)")
    }
}

解决方法

我一直在玩这个.这是一个最小的例子:

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构建此打印预期的四倍真.在优化的构建中,它打印…

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

错误在以下情况下消失:

>测试在外部文件范围内执行(不在函数中)
>使用普通函数代替operator ==
>枚举不是嵌套在另一种类型中
>删除案例C或关联类型
>打印语句插入到开关案例中

我一直在测试Xcode 7.1.这个bug肯定应该在bugreport.apple.com上提交

猜你在找的iOS相关文章