swift can show the type of the return value of a function.
This could be useful when implementing type matching by swift, so it is necessary to see the details of this.
see the official document
Here is the very intro part of the explaining.
The function in the example below is called
greet(person:)
, because that’s what it does—it takes a person’s name as input and returns a greeting for that person. To accomplish this, you define one input parameter—a String
value called person
—and a return type of String
, which will contain a greeting for that person:- func greet(person: String) -> String {
- let greeting = "Hello, " + person + "!"
- return greeting
- }
typealias
This will create obviously the alias of a type.
- typealias (String) -> String = greetType
- func callGreet(callback: greetType) {
- let greeting = callback("Hello")
- // this is supposed to be greet(person: String) function
- return greeting
- }
Filter
Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.
let numbers = [1,2,3,4,5]
let greaterThan2 = numbers.filter { $0 > 2}
print(greaterThan2)
[3, 4, 5]
Map
Returns an array containing the results of mapping the given closure over the sequence’s elements.
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
print(lowercaseNames)
["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
print(letterCounts)
[6, 6, 3, 4]
Reduce
Returns the result of combining the elements of the sequence using the given closure.
Declaration
let numbers = [1,2,3,4,5]
let numberSum = numbers.reduce(0, { x, y in
x + y
})
print(numberSum)
15
0 件のコメント:
コメントを投稿