This article is based on the introduction to swift practice and the ios Academy.
--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
}
Prepare a function and closure that returns True if it is greater than 3.
--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)
--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)
}
--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)
}
--Introduction to swift practice
Recommended Posts