比较2个数组并根据是否存在创建一个新数组,迅速5

我有2个数组:

其中一个包含保留字列表

var reservedWords = ["var","if","for","switch","int","class"];

下一个包含可能的变量名(包括一些“保留字”)

var varNames = ["if","var","identifier,"thisIsAnIdentifier","b13","a","i","number_1","class"];

我想比较两个数组,并使用不在“ reservedWords”中的单词创建一个新数组。新数组应如下所示:

var newArray = ["identifier,"number_1"]
hillingzhou 回答:比较2个数组并根据是否存在创建一个新数组,迅速5

您可以简单地执行以下操作:

// this doesn't compile,but SomeClass is a class and it should work
class ClassA<T> where T: SomeClass
{
    // here,you get the classic:
    // Only non-nullable value type could be underlying of 'System.Nullable'
    // What this makes clear is that the compiler doesn't understand that
    // T is strictly a reference Type now
    public GenericType<T?> DoSomething()
    {
        thrown new NotImplementedException();
    }
}
,

您可以使用.filter进行此操作:

var reservedWords = ["var","if","for","switch","int","class"]
var varNames = ["if","var","identifier","thisIsAnIdentifier","b13","a","i","number_1","class"]

let newArray = varNames.filter {!reservedWords.contains($0)}

这是输出:

enter image description here

,

另一种方法是you use Sets,特别是Set.subtract(修改列表)或Set.subtracting(创建新列表)。由于集合是唯一的,因此它应该表现更好。

let employees: Set = ["Alicia","Bethany","Chris","Diana","Eric"]
let neighbors = ["Bethany","Eric","Forlani","Greta"]
let nonNeighbors = employees.subtracting(neighbors)
print(nonNeighbors)
  

“ [[” Chris“,” Diana“,” Alicia“]”

本文链接:https://www.f2er.com/3084072.html

大家都在问