gpt4 book ai didi

swift - 比较强制展开的可选数组

转载 作者:可可西里 更新时间:2023-11-01 02:17:05 24 4
gpt4 key购买 nike

我正在写一个测试:

    func test_arrayFromShufflingArray() {

var videos = [MockObjects.mockVMVideo_1(), MockObjects.mockVMVideo_2(), MockObjects.mockVMVideo_3()]
let tuple = ShuffleHelper.arrayFromShufflingArray(videos, currentIndex:1)

var shuffledVideos = tuple.0
let shuffleIndexMap = tuple.1


// -- test order is different
XCTAssert(videos != shuffledVideos, "test_arrayFromShufflingArray fail")
}

但是在最后一行我得到了最后一行:

Binary operator '!=' cannot be applied to two '[VMVideo!]' operands

最佳答案

数组可以比较==如果元素类型是 Equatable :

/// Returns true if these arrays contain the same elements.
public func ==<Element : Equatable>(lhs: [Element], rhs: [Element]) -> Bool

但都不是 ImplicitlyUnwrappedOptional<Wrapped>也不Optional<Wrapped>符合 Equatable , 即使底层类型 Wrapped

可能的选项是(假设 VMVideo 符合 Equatable ):

  • 更改您的代码,使 videosshuffledVideos[VMVideo]数组而不是 [VMVideo!] .

  • 按元素比较数组:

    XCTAssert(videos.count == shuffledVideos.count
    && !zip(videos, shuffledVideos).contains {$0 != $1 })
  • 定义一个 ==隐式解包等式数组的运算符元素:

    func ==<Element : Equatable> (lhs: [Element!], rhs: [Element!]) -> Bool {
    return lhs.count == rhs.count && !zip(lhs, rhs).contains {$0 != $1 }
    }

关于swift - 比较强制展开的可选数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36726486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com