2020年1月25日土曜日

swift, function type. prepare for functional programming with Swift - 1

Function Type
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:
  1. func greet(person: String) -> String {
  2. let greeting = "Hello, " + person + "!"
  3. return greeting
  4. }

typealias
This will create obviously the alias of  a type.


  1. typealias (String) -> String = greetType
  2. func callGreet(callback: greetType) {
  3. let greeting = callback("Hello")
  4. // this is supposed to be greet(person: String) function
  5. return greeting
  6. }

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


func reduce(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result


let numbers = [1,2,3,4,5]
let numberSum = numbers.reduce(0, { x, y in
    x + y
})
print(numberSum)
15


0 件のコメント:

コメントを投稿