如何在 Swift 中比较多个变量到多个变量?

问题描述 投票:0回答:1

我有四个变量:

valueOne
valueTwo
valueThree
valueFour
。我想将它们与其他四个变量进行比较(比如说
firstValue
secondValue
thirdValue
fourthValue
),如果它们不匹配,我想更新它们:

if valueOne != firstValue {
    valueOne = firstValue
}

如何对每个变量有效地做到这一点?意义:

if valueOne != firstValue
valueTwo != secondValue
valueThree != thirdValue
等等。

swift xcode variables compare
1个回答
0
投票

试试这个:

func compareable<T: Comparable>(baseValues: [T], valueToCompare values: [T]) -> [T] {
    assert(baseValues.count == values.count, "Total elements must equal")
    var _baseValues: [T] = baseValues
    for i in 0..<_baseValues.count {
        if _baseValues[i] != values[i] {
            _baseValues[i] = values[i]
        } else {
            continue
        }
    }
    return _baseValues
}

//Type check
compareable(baseValues: [1,2,3,4], valueToCompare: [false,false,true,true]) //Error
compareable(baseValues: [1,2,3,4], valueToCompare: ["1","2","3","4"]) //Error

//Use
compareable(baseValues: [1,2,3,4], valueToCompare: [1.0, 2.0, 3.0, 4.0]) //Return [Double] = [1.0, 2.0, 3.0, 4.0]
compareable(baseValues: [1,2,3,4], valueToCompare: [5,6,7,8]) //Return [Int] = [5,6,7,8]
© www.soinside.com 2019 - 2024. All rights reserved.