与Set完全相同的代码会得到不同的结果吗?Swift中的实际问题是什么? [英] Different results with Set altough similar code? What is the excact problem in Swift?

查看:63
本文介绍了与Set完全相同的代码会得到不同的结果吗?Swift中的实际问题是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题.我有两个数组,我试图在其中找到相同的内容.因此,我决定将其转换为Set,然后将这些漂亮的函数与"subtract"一起使用.但是我得到了非常不同的结果.有人可以告诉我为什么会这样吗?当我使用减"时,而不是减去"我没问题,但是这对我来说很奇怪,我真的不知道为什么会这样.

i have a small problem. I have two Arrays where i try to find the same content in it. So i decided to convert it to a Set and then using those nice functions with "subtract". However i get very different results. Can someone tell me why this happens? When i use "subtracting" instead of "subtract" i get no problems however this is very weird for me and i really have no clue why this happens.

   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"

令人惊讶的是,这是一个可行的示例.但是我还是不知道为什么吗?

And this is the one sample which works, surprisingly. However i still dont know really why???

    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"

推荐答案

都计算2个集合的差,但是变异,而不是.

这意味着 x.subtract(y) 集合 x 更改为计算出的差,而 x.subtracting(y)完全不更改 x ,而是返回差异.另一方面,不返回任何内容( Void ).

This means that x.subtract(y) changes the set x to the computed difference, whereas x.subtracting(y) doesn't change x at all, and instead returns the difference. On the other hand, subtract returns nothing (Void).

这样做的时候

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

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

you see () being printed, because that is what the string representation of Void looks like - an empty tuple.

这有效

employees.subtract(neighbors)
print(employees)

因为减去会更改员工.

这也有效:

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

因为 subtracting 的返回值-设置差-被分配给 different .请注意,这不会更改 setA .

because the return value of subtracting - the set difference - is assigned to different. Note that this doesn't change setA.

这不起作用:

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

因为减法不会改变员工,因此您忽略了它的返回值.

Because subtracting doesn't change employees, and you are ignoring its return value.

还有许多其他的此类突变与非突变方法,例如

There are many other pairs of such mutating vs non-mutating methods, like

  • Set.formUnion Set.union
  • String.append String.appending

相关文章

这篇关于与Set完全相同的代码会得到不同的结果吗?Swift中的实际问题是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆