Swift 5.X - Set collection

1.Set the defined set

import UIKit

var a: Set = [1,2,3,4]
print(a)

var b:Set<String> = ["hello","world"]
print(b)

var c:Set<Int> = []
print(c)

Set of basic operations 2.Set

import UIKit

var a:Set<String> = ["hello","world","swift"]
print(a.count)//3
a.insert ( "aaa") // end of the insert elements s
print(a)//["hello", "world", "aaa", "swift"]
print (a.contains ( "hello")) // true. Check if a certain element
a.remove ( "hello") // delete an element
print(a)//["swift", "aaa", "world"]

Advanced Operations 3.Set collection

import UIKit

var a:Set<String> = ["hello","world","swift"]
var b:Set<String> = ["hello","world","Object-C"]

print(a.union(b))//["hello", "swift", "world", "Object-C"]。g合并
print (a.intersection (b)) // [ "world", "hello"]. Return the same element
print (a.symmetricDifference (b)) // Object-C "," swift "]. return different elements
print (a == b) // false. Set to determine whether the two are equal
var c = a.filter({(item)->Bool in
    if(item=="hello"||item=="swift"){
        return false
    }else{
        return true
    }
})
print (c) // [ "world"]. Set filters
for item in b{
    print (item) // Object-C hello world. Set traversal
}

Guess you like

Origin www.cnblogs.com/yangyh26/p/11826365.html