Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Session 13 Tasks

import Foundation
import Glibc

//Task 1
func applyKTimes(_ K: Int, _ closure: () -> ()){
    for _ in 1...K {
        closure()
    }
}
applyKTimes(3) { 
print("Hello Swift")
}


//Task 2

var numbers = [1, 2, 3, 4, 6, 8, 9, 3, 12, 11]
var result = numbers.filter{$0 % 3 == 0}
print(result)

//OR
// func filter(_ Number: [Int], _ closure: (Int) -> (Bool)) -> [Int]{
// var multiples: [Int] = []
//     for i in Number {
//         if closure(i) {
//           multiples.append(i)
//         }
//     }
//     return multiples
// }   
// var result = filter([3, 6, 9, 3, 12], { $0 % 3 == 0}) 
// print(result)


//Task 3

var numbers2 = [4, 7, 1, 9, 6, 5, 6, 9]
numbers2.sort{$0 > $1}
print(numbers2[0])

//OR
// var numbers2 = [4, 7, 1, 9, 6, 5, 6, 9]
// let max = numbers2.reduce(numbers2[0]){
//     if $0 > $1 {
//         return $0
//     }else{
//         return $1
//     }
// }
// print(max)


//Task 4

var strings = ["We", "Love", "iOS"]
let string =  strings.reduce(""){
    if $0 != "" {
    return $0 + " " + $1
    }else{
        return $1
    }
}
print(string)


//Task 5
var nums = [1, 2, 3, 4, 5, 6]
func countDivisors(_ num: Int) -> Int {
        var count = 0
        for i in 1...num {
            if num % i == 0 {
                count += 1
            }
        }
        return count
    }
nums.sort{countDivisors($0) < countDivisors($1)}
print(nums)


//Task 6
var numberss = [1, 2, 3, 4, 5, 6]
let sum = numberss.filter{$0 % 2 != 0}.map{$0 * $0}.reduce(0){$0 + $1}
print(sum)


//Task 7
func forEach(_ array: [Int], _ closure: (Int) -> ()) {
    for num in array {
        closure(num)
    }
}
forEach([1, 2, 3, 4]) {
print($0 + 1)
}

//Task 8
func combineArrays(_ array1: [Int], _ array2: [Int], _ closure: (Int,Int) -> Int) -> [Int]{
var newArray: [Int] = []
for i in 0..<array1.count{
    newArray.append(closure(array1[i], array2[i]))
}
 return newArray   
}
var resultt = combineArrays([1,2,3,4], [5,5,5,3]) {
$0 * $1
}
print(resultt)

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.