【问题标题】:Different results with Set altough similar code? What is the excact problem in Swift?尽管代码相似,但 Set 的结果不同? Swift 中的确切问题是什么?
【发布时间】:2021-03-16 04:09:45
【问题描述】:

我有一个小问题。我有两个数组,我试图在其中找到相同的内容。所以我决定将它转换为一个集合,然后使用那些带有“减法”的好函数。但是我得到了非常不同的结果。有人能告诉我为什么会这样吗?当我使用“减法”而不是“减法”时,我没有遇到任何问题,但这对我来说很奇怪,我真的不知道为什么会发生这种情况。

   var objectIDsWhichExist = [ "kjugsJHL6JYoByOreUQ0wUefsbX2", "18ixZ21PJDXA1WzeJqZzctl7tTk2", "ZeQPYGfDvWMLSVykb4M5FQ6miGX2"]
    var helperObjectIDsWhichExistInAdded = [ "kjugsJHL6JYoByOreUQ0wUefsbX2", "18ixZ21PJDXA1WzeJqZzctl7tTk2"]
    


    var setA = Set(objectIDsWhichExist) /* Updated Data*/
    var setB = Set(helperObjectIDsWhichExistInAdded) /* Standard Data*/
    let different = setA.subtract(setB) // I GET HERE ()  
    print(different) // I GET THIS RESULT "()\n"

令人惊讶的是,这是一个有效的示例。但是我还是不知道为什么???

    var employees: Set = Set(objectIDsWhichExist)
    let neighbors: Set = Set(helperObjectIDsWhichExistInAdded)
    employees.subtract(neighbors)
    print(employees) // HERE IT DOES WORK because i get this -> ["ZeQPYGfDvWMLSVykb4M5FQ6miGX2"]\n"

【问题讨论】:

    标签: arrays swift set intersection hashable


    【解决方案1】:

    subtractsubtracting 都计算 2 个集合的差异,但 subtract变异,而 subtracting 不是。

    这意味着x.subtract(y) 将集合x 更改为计算出的差值,而x.subtracting(y) 根本不会更改x,而是返回 区别。另一方面,subtract 不返回任何内容 (Void)。

    当你这样做时

    let different = setA.subtract(setB) // I GET HERE ()  
    print(different)
    

    您会看到 () 正在打印,因为这就是 Void 的字符串表示形式 - 一个空元组。

    这行得通

    employees.subtract(neighbors)
    print(employees)
    

    因为subtract 改变了employee

    这也有效:

    let different = setA.subtracting(setB)
    print(different)
    

    因为subtracting 的返回值——设置的差异——被分配给different。请注意,这不会改变 setA

    这不起作用:

    employees.subtracting(neighbors)
    print(employees) // still shows the original employees
    

    因为subtracting 不会改变employees,而你忽略了它的返回值。

    还有很多其他这样的变异方法与非变异方法,比如

    • Set.formUnionSet.union
    • String.appendString.appending

    Related post

    【讨论】:

    • 非常感谢您详细解释这一点。非常感谢您花时间给我这样一个很好的答案!
    猜你喜欢
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    相关资源
    最近更新 更多