Swift: A struct with a closure

This entry is part 22 of 41 in the series Swift

When Swift was introduced last year by Apple in one of its events, it mentioned about closure, and I have no idea what that was.  I have looked at Swift for a couple of days and I am still a bit confused about how it is going to be used.

Closure is a piece of very concise code and it is actually quite easy to construct as shown in this example.

struct Square{
    var width = 0
    var height = 0
    
    func area()->Int{
        return width*height
    }
    
    func printArea(){
        print("area \(area())")
    }
    
    //closure
    func repeatTill(count count:Int , _ delimiter:String) {
        for _ in 1...count {
            print(delimiter)
            printArea()
        }
    }
    
}

var square = Square(width: 10, height: 5)

square.repeatTill(count:3,"***")

swift

Swift: Simple inheritance with a method

This entry is part 21 of 41 in the series Swift

This is an inherited class with a call to the parent’s method.

class Person {
    var name = ""
    var age = 0
    
    init(){
        self.name = ""
        self.age = 0
    }
    
    init(name:String,age:Int){
        self.name = name
        self.age = age
    }
    
    func printIntro(){
        print("My name is \(self.name) My age is \(self.age)")
    }

}


class Student : Person {
    
}

var student = Student(name: "Taylor Swift", age: 20)

student.printIntro()

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

Swift: Getting the average

This entry is part 18 of 41 in the series Swift

Here we show how we could get the average of a few or more numbers. In this example, we are using a for loop and a swift function called reduce.

func averageLoop(numbers: Int...) -> Int {
    
    var sum = 0
    
    for number in numbers {
        sum += number
    }
    
    return sum / numbers.count
}

func averageReduce(numbers: Int...) -> Int {
    
    return numbers.reduce(0, combine: +) / numbers.count
    
}

var avgLoop = averageLoop(100, 200, 300)
var avgReduce = averageReduce(100, 200, 300,400,500,600)

swift