首页 > 解决方案 > Binary operator '+' cannot be applied to two 'Set' operands Error

问题描述

I have 2 Arrays and I want to merge them after converting them to Sets, this is my code:

var before = Array(Set(beforevalues))
var first = Array(Set(myvalues))


let save1 = first{ ($0.rangeOfString("today") != nil) }
let save2 = Set(save1)
var mynewarray = Set(save2)

let merge = Array(Set(before + mynewarray)) // THIS LINE ERROR

but it gives:

Binary operator '+' cannot be applied to two 'Set' operands

How can I fix it?

标签: arraysswiftstringset

解决方案


You need to use union to merge two Sets as there's no + operator defined for Sets. Moreover, before is an Array while mynewarray is a Set, but since Set.union accepts an input argument of type Sequence you can solve that issue by calling union on the Set.

let merged = Array(mynewarray.union(before))

推荐阅读