[Swift] Closure basics (personal memo)

Notes about closures

This article is based on the introduction to swift practice and the ios Academy.

What is a closure?

--Reusable group processing --Functions are a type of closure

Closure format
{ (Argument name 1:Mold,Argument name 2:Mold) ->Return type in
Execution statement
Return is required when setting the return value
}

Compare with function

Prepare a function and closure that returns True if it is greater than 3.

Feature

--Closers cannot specify external arguments --Closers cannot specify default arguments

//function
func isGreaterThanThree(enter number: Int) -> Bool {
    if number > 3 {
        return true
    }
    return false
}

isGreaterThanThree(enter: 4)

//Closure type
var myFunction: ((Int) -> Bool) = { number in
    if number > 3 {
        return true
    }
    return false
}

//Closures don't need external arguments
let result = myFunction(4)

Closure that does not require a return value

--If you set the return value to Void, you don't need return.

var myFunction2: ((Int) -> (Void))? = { number in
    if number > 3 {
        print("It's bigger than 3!")
    }
}

//Unwrap
if let myrealfunc = myFunction2 {
    myrealfunc(4)
}

Closure with two arguments

--The closure when there are two arguments is as follows

//The process of comparing two values
var myFunction3: ((Int, Int) -> (Void))? = { number, other in
    if number > other {
        print("\(number)Is bigger!")
    }
    else {
        print("\(other)Is bigger!")
    }
}

if let unwrappedFunc3 = myFunction3 {
    unwrappedFunc3(3, 4)
}

reference

--Introduction to swift practice

Recommended Posts

[Swift] Closure basics (personal memo)
[Swift] Closure
[Personal memo] About Spring framework
Personal memo Progate Ruby I (2)
Personal memo Eclipse plug-in installation
[Personal memo] Number guessing game
Personal memo Lombok's typical annotation
Personal memo Progate Ruby I (1)
Java HashMap, entrySet [Personal memo]
Personal memo: Metaprogramming with Java reflection
Swift beginner Debugging memo with Xcode