我有四个变量:
valueOne
、valueTwo
、valueThree
和valueFour
。我想将它们与其他四个变量进行比较(比如说 firstValue
、secondValue
、thirdValue
和 fourthValue
),如果它们不匹配,我想更新它们:
if valueOne != firstValue {
valueOne = firstValue
}
如何对每个变量有效地做到这一点?意义:
if valueOne != firstValue
、valueTwo != secondValue
、valueThree != thirdValue
等等。
试试这个:
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]