Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to declare Sets in Swift

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.59k
    Comment on it

    Hi Readers!

    Let us first understand what Sets means.

    Sets

    A set stores unique values of same type in a collection with no ordering. Sets should be used when there is no defined order, such as in Array. Secondly Array can store multiple same values but Sets can't. Sets are distinct."

    Hash Values for Set Types

    Whatever type you take it should be hashable to be stored in a set. It means that the type must provide a way to compute a hash value. A hash value is an Int value so that same objects can be compared equally, such as if `a == b`, if follows that `a.hashValue == b.hashValue`.

    All basic swift types (Int, String, Bool and Double) are hashable by default. Enumerations case values are also hashable by default.

    Set Type Syntax

    Swift Set is written as `Set` where `Element` is the type that the set will store.

    Creating and Initializing an Empty Set

    var pets = Set<String>()
    

    Here pets is set which can store String values

    Creating a Set with values The example below creates a set called pets to Store String values:

    var pets:Set<String> = ["Cat","Dog","Parrot"]
    

    The pets variable is declared as "set of String values" written as Set<String>. It is only allowed to store String values. You can skip the type String from the Set notation while declaring as it will infer automatically as String because it contains all String values.

    var pets:Set = ["Cat","Dog","Parrot"]
    

    Accessing and Modifying a Set

    Sets can be modified by using its methods and properties.

    Find the number of elements in a set by using count property which is read-only.

    print("I have \(pets.count) pets") 
    

    Inserting a new element

    pets.insert("Cow")
    

    Removing an element

    pets.remove("Cow")
    

    Checking a set contains an element

    if pets.contains("Dog") {
        print("I am fond of Dog")
    }else{
        print("I am not a fond of Dog")
    }
    

    Iterating a set

    Iterating a set using for-in loop.

    for pet in pets {
        print("\(pet)")
    }
    

    Set type does not have a predefined ordering. So to iterate in a specific order use sort() method.

    for pet in pets.sort() {
            print("\(pet)")
        }
    

    Performing Set Operations

    1. Intersecting 2 sets will result in a set containing common elements in 2 sets.
    2. Example:

      var animals:Set = ["Cat","Dog","Parrot","Cheetah","Lion","Ox"]
      var pets:Set = ["Dog","Parrot"]
      
      var intersect = pets.intersect(animals)
      print("\(intersect)") // will print "Dog" & "Parrot"
      
    3. Exclusive Or - This will result in values in either set but not both.
    4. Example:

      var animals:Set = ["Cat","Dog","Parrot","Cheetah","Lion","Ox"]
      var pets:Set = ["Dog","Parrot","Cow"]
      
      var exclusive = pets.exclusiveOr(animals)
      print("\(exclusive)") -  will print {"Cheetah", "Ox", "Cat", "Lion","Cow"}
      
    5. union - It will create a new set with values in both sets.
    6. Example:

      var animals:Set = ["Cat","Dog","Parrot","Cheetah","Lion","Ox"]
      var pets:Set = ["Dog","Parrot","Cow"]
      
      var union = pets.union(animals)
      print("\(union)") - will print {"Dog", "Cow", "Lion", "Cheetah", "Ox", "Cat", "Parrot"}
      
    7. subtract - It will create a new set with values not in the specified set.
    8. Example:

      var animals:Set = ["Cat","Dog","Parrot","Cheetah","Lion","Ox"]
      var pets:Set = ["Dog","Parrot","Cow"]
      
      var subtract = pets.subtract(animals)
      print("\(subtract)") - will print {"Cow"}
      

    Thats it for now. Hope the blog will help you in understanding Sets in Swift. You can comment if you face any difficulty or need more information.

    Happy Swifting!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: