We're going to learn about:
- Closures
- Optionals
- Swift's Named Parameters
- TypeCast
Functions inside other functions
func calculator (n1: Int, n2:Int, operation:(Int,Int) -> Int) -> Int{
return operation(n1,n2)
}
let result = calculator(n1: 2, n2: 3){$0*$1}
let array = [6,2,3,9,4,1]
Filtrate something and generate another Array as Output
let arrayEvenNumbers = array.filter{$0 % 2 == 0}
[6, 2, 4]
Got the even numbers from the main array
Change it all and generate another Array as Output
let arrayPlusOne = array.map{$0+1}
[7, 3, 4, 10, 5, 2]
Reduce it and generate a singular result
let arraySum = array.reduce(0){$0 + $1}
Begins from 0 and add each element of the Array
25
Map + (Flat the collection)
let arrays = [array,array]
let DoubledArray = arrays.flatMap{$0.map{$0}}
[6, 2, 3, 9, 4, 1, 6, 2, 3, 9, 4, 1]
It can be return Nil
We can see that the returned value can be Nil if there's no C in S. So, it's putted the "?" to mean the sentence "is Nil?"
func Search(ifContains c:Character, in s:String) -> String.Index?{
return s.lastIndex(of: c)
}
Besides that, we use external and interval paramaters to leave the function more readable: "Search ifContains C in S"
Search(ifContains: "á", in: "Olá")?.encodedOffset
the output of this code will remain a Optional()
, until you UNWRAP
This is not highly recommended, as it is going to crash the app if the value is "Nil".
Search(ifContains: "á", in: "Olá")!.encodedOffset
But, you can use it if you're sure about the value
This is more recommended
if let s = Search(ifContains: "á", in: "Olá"){ //safe unwrapping the optional
print("let ",s.encodedOffset)
}
When the value is Nil, it will replace it with -1
Search(ifContains: "á", in: "Olá")?.encodedOffset ?? -1
Change the variables Type!
class Animal{
var name:String
init(n: String){
self.name = n
}
}
class Human:Animal{
func code(){
print("Typing away...")
}
}
class Fish:Animal{
func breatheUnderWater(){
print("Glup Glup!")
}
}
let joao = Human(n: "João Victor Ipirajá")
let jack = Human(n: "Jack Bauer")
let darwin = Fish(n: "Darwin Watterson")
let neighbours:[Animal] = [joao,jack,darwin]
func findDarwin(from animals: [Animal]){
for animal in animals{
if(animal is Fish){ //check the type
print(animal.name)
let fish = animal as! Fish
fish.breatheUnderWater()
}
}
}
func findDarwin(from animals: [Animal]){
for animal in animals{
if let fish = animal as? Fish{
print(fish.name)
fish.breatheUnderWater()
}
}
}
func findDarwin(from animals: [Animal]){
for animal in animals{
if(animal is Fish){ //check the type
print(animal.name)
let fish = animal as! Fish // force downcast
fish.breatheUnderWater()
let animalFish = fish as Animal
}
}
}
You can put anything in the Array
let num = 1
let neighbours:[Any] = [joao,jack,darwin,num]
You can put Any Class in the Array
class Human{
func code(){
print("Typing away...")
}
}
class Fish{
func breatheUnderWater(){
print("Glup Glup!")
}
}
let neighbours:[AnyObject] = [joao,jack,darwin]
You can put Any Foundation Data Type in the Array