Shuffle array in a class

This entry is part 33 of 41 in the series Swift

import UIKit

class ArrayObject : NSObject {
    
    var numbers = [1,2,3,4,5]
    
    func shuffleNumbers() {
        numbers.shuffle()
    }
}

extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }
        
        for (unshuffledCount, firstUnshuffled) in zip(stride(from: c, to: 1, by: -1), indices) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}

let array = ArrayObject()

array.shuffleNumbers()

print(array.numbers[1])

Swift: Using append method to add item

For an array list, we could also use append method to add an item to the end of the list.

var list = ["David", "Derek", "Dragon"];

print("Total no of members: \(list.count)\n");

list += ["Emily", "Evan"];
list.insert("Amy", atIndex:0);

var item:String;

for item in list {
    print(item);
}

list.append("Michelle")

print("\nNow the updated list is:")

for item in list {
    print(item);
}

swift

Swift: Test if an array is empty

This entry is part 19 of 41 in the series Swift

Here we create 2 arrays and one of them empty to test out our code.

var array1: [String: Int] = ["Eng": 90, "Math": 80,"History":85]
if array1.isEmpty {
    print("empty.")
} else {
    print("not empty.")
}

var array2 = [Int]()
if array2.isEmpty {
    print("empty.")
} else {
    print("not empty.")
}

swift