【问题标题】:how to subtract and get the difference of two arrays in swift 3?如何在swift 3中减去并获得两个数组的差异?
【发布时间】:2018-03-10 22:47:12
【问题描述】:

在这里,我需要获取这两个数组的差异,并需要将其保存在单独的数组中,例如 60 - 50 = 10,并且在 dollarRemovedArray 中具有“及以上”的一个值可以在两个数组中的相同索引处跳过任何人都可以帮助我如何获得这些数组的差异?

var dollarRemovedArr = [50, 30, 0, 20, 90, 40, 80, 70, 10, 60]
var dollarRemovedArray = [Optional("60"), Optional("40"), Optional("10"), Optional("30"), Optional("and above"), Optional("50"), Optional("90"), Optional("80"), Optional("20"), Optional("70")]

【问题讨论】:

  • one value having 'and above' in dollarRemovedArray can be skipped 是什么意思?
  • 该值我将手动设置为 90+,所以我需要跳过该 @Lion
  • 还是不清楚!你想像dollarRemovedArray - dollarRemovedArr一样做减法吗?
  • 这意味着在两个数组中排除该索引,所以我提到了@Lion
  • 哪个索引但是?

标签: ios arrays swift3


【解决方案1】:

请尝试以下代码

var outputArray = [Int]()

for var index in (0 ..< dollarRemovedArr.count) {
    guard let  dollarRemovedArrayString =  dollarRemovedArray[index] as? String,let dollarRemovedArrayItem = Int(dollarRemovedArrayString),   dollarRemovedArr.count > index  else {
        continue
    }
    outputArray.append(dollarRemovedArrayItem - dollarRemovedArr[index])

}
print(outputArray)

输出

[10, 10, 10, 10, 10, 10, 10, 10, 10]

【讨论】:

    【解决方案2】:

    这将对您有所帮助:

    var dollarRemovedArr = [50, 30, 0, 20, 90, 40, 80, 70, 10, 60]
        var dollarRemovedArray = [Optional("60"), Optional("40"), Optional("10"), Optional("30"), Optional("and above"), Optional("50"), Optional("90"), Optional("80"), Optional("20"), Optional("70")]
    
        var resulTArray = [Int]()
        var index = 0
        for value1 in dollarRemovedArr {
    
            if dollarRemovedArray.count < index {
                // checking if dollarRemovedArray count less then dollarRemovedArr then adding value as default result
                resulTArray.append(value1)
                index += 1
            } else if let value2 = Int("\(dollarRemovedArray[index] ?? "")") {
                // checking if dollarRemovedArray value is in int
                resulTArray.append(value2 - value1)
                index += 1
            } else {
                // else adding default value as result
                resulTArray.append(value1)
                index += 1
            }
        }
        print(resulTArray)
    

    结果将是: [10, 10, 10, 10, 90, 10, 10, 10, 10, 10]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多