Generic in general in Swift

Trying to understand the code below. I understand that T is passed when the Option instance is created, as in optional, but what about the type U on the map. What type does this suggest?

enum Optional<T> : LogicValue, Reflectable { case None case Some(T) init() init(_ some: T) /// Allow use in a Boolean context. func getLogicValue() -> Bool /// Haskell fmap, which was mis-named func map<U>(f: (T) -> U) -> U? func getMirror() -> Mirror } 
+6
source share
2 answers

Type U comes from the parameter f to the map function. Therefore, if you pass a closure that returns Int , then map returns a Int? . If you pass the closure that Array<Int> returns, then map returns Array<Int>? .

For example, try the following:

 var opt1: Optional<Int> = .Some(1) var opt2 = opt1.map { (i: Int) -> String in return "String: \(i)" } 

You will find that opt1 is Int? and opt2 is String? .

+6
source

When calling the map function, the caller must provide a single argument, which is a closure that:

  • It has one argument, which is the same type as the one used for the Optional instance, i.e. T
  • Has a return value of some type.

U will then be the return type.

+4
source

Source: https://habr.com/ru/post/971307/


All Articles