What does the swift keyword Wrapped mean in the Optional extension? - swift

What does the swift keyword Wrapped mean in the Optional extension?
extension Optional {
func flatMap<U>(_ transform: (Wrapped) -> U?) -> U? {
guard let x = self else { return nil }
return transform(x)
}
}

In extensions, the generic parameters of the type that you are extending can be referenced by just writing their simple names, and notice that Optional is a generic type.
#frozen enum Optional<Wrapped>
So Wrapped in the function declaration refers to the generic parameter declared there.
As you may know, optional types are usually written as T? (where T is some type), which is a syntactic sugar for Optional<T>. For example, Int? is the same as Optional<Int>, and String? is the same as Optional<String>, etc.
In other words, Wrapped basically just means the type that precedes the ?, whatever that may be. If you have a String? (aka Optional<String>), then the signature of flatMap for that would be:
func flatMap<U>(_ transform: (String) -> U?) -> U?

There is no keyword "Wrapped." This is a type parameter. This is similar to runtime parameters. If you see:
func f(x: Int) { ... }
x is not a keyword. It's just a parameter name. In the same way, Optional is defined as:
enum Optional<Wrapped>
"Wrapped" is just the type parameter passed to Optional. So in this extension:
func flatMap<U>(_ transform: (Wrapped) -> U?) -> U? {
"Wrapped" just refers to whatever Optional is wrapping.

Related

Overload dictionary subscript two times and forward call

I'm trying to extend Dictionary and allow extracting values casted to a certain types and with a given default value. For this I added two overloads for the subscript function, one with a default value, one without:
extension Dictionary {
subscript<T>(_ key: Key, as type: T.Type, defaultValue: T?) -> T? {
// the actual function is more complex than this :)
return nil
}
subscript<T>(_ key: Key, as type: T.Type) -> T? {
// the following line errors out:
// Extraneous argument label 'defaultValue:' in subscript
return self[key, as: type, defaultValue: nil]
}
}
However when calling the three-argument subscript from the two-argument one I get the following error:
Extraneous argument label 'defaultValue:' in subscript
Is this a Swift limitation? Or am I missing something?
I'm using Xcode 10.2 beta 2.
P.S. I know there are other alternatives to this, like dedicated functions or nil coalescing, trying to understand what went wrong in this particular situation.
Subscripts have different rules than functions when it comes to argument labels. With functions, argument labels default to the parameter name – for example if you define:
func foo(x: Int) {}
you would call it as foo(x: 0).
However for subscripts, parameters don't have argument labels by default. Therefore if you define:
subscript(x: Int) -> X { ... }
you would call it as foo[0] rather than foo[x: 0].
Therefore in your example with the subscript:
subscript<T>(_ key: Key, as type: T.Type, defaultValue: T?) -> T? {
// the actual function is more complex than this :)
return nil
}
The defaultValue: parameter has no argument label, meaning that the subscript would have to be called as self[key, as: type, nil]. In order to add the argument label, you need to specify it twice:
subscript<T>(key: Key, as type: T.Type, defaultValue defaultValue: T?) -> T? {
// the actual function is more complex than this :)
return nil
}

Optional`s Equatable in Swift

We can compare two Optional variables through
public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool
But when i compare a String? and a String, it goes into the same function above. Why not:
public func ==<T : Equatable>(lhs: T?, rhs: T) -> Bool
In general, a function with arguments of some optional Type (Type?) does not imply the necessity of a variable of optional type as an input. In other words, take some function foo such that
func foo(in: Type?) { ... }
What this really means is that the function accepts both nil and Type variables as inputs (when unwrapped). Logically this is nil || Type, so of course a variable of class Type? can be taken as an input because it is identically nil or Type when unwrapped. However, even further, Type (non-optional) works just fine too because it satisfies one of the conditions in the logical expression.

Return any type from a function in Swift

I am attempting to create a function that can return any type. I do not want it to return an object of type Any, but of other types, i.e. String, Bool, Int, etc. You get the idea.
You can easily do this using generics in this fashion:
func example<T>(_ arg: T) -> T {
// Stuff here
}
But is it possible to do it without passing in any arguments of the same type? Here is what I am thinking of:
func example<T>() -> T {
// Stuff here
}
When I try to do this, everything works until I call the function, then I get this error:
generic parameter 'T' could not be inferred
is it possible to do it without passing in any arguments of the same type?
The answer is yes, but there needs to be a way for the compiler to infer the correct version of the generic function. If it knows what it is assigning the result to, it will work. So for instance, you could explicitly type a let or var declaration. The below works in a playground on Swift 3.
protocol Fooable
{
init()
}
extension Int: Fooable {}
extension String: Fooable {}
func foo<T: Fooable>() -> T
{
return T()
}
let x: String = foo() // x is assigned the empty string
let y: Int = foo() // y is assigned 0

What is the syntax for a closure argument in swift

In Swift headers, the isSeparator: argument accepts a closure
public func split(maxSplit: Int = default, allowEmptySlices: Bool = default, #noescape isSeparator: (Self.Generator.Element) throws -> Bool) rethrows -> [Self.SubSequence]
But in the documentation, it lists closure syntax differently
{ (parameters) -> return type in
statements
}
How are you supposed to know that (Self.Generator.Element) throws -> Bool rethrows refers to a closure / requires a closure? Are there other ways that the headers/docs might list argument as meaning a closure?
The "thing" giving away that this is a closure is the ->. The full type is
(Self.Generator.Element) throws -> Bool
It means that the closure takes a variable of type Self.Generator.Element and has to return a Bool upon some calculation based on the input. It may additionally throw some error while doing so - that is what the throws is for.
What you then write
{ (parameters) -> return type in
statements
}
would be an actual implementation, a value of some generic closure type.
The type of a closure is for example (someInt:Int, someDouble:Double) -> String:
var a : ((someInt:Int, someDouble:Double) -> String)
Once again the thing giving away that a is actually a closure is the -> in the type declaration.
Then you assign something to a via some code snippet following your second code block:
a = { (integer, floating) -> String in
return "\(integer) \(floating)"
}
You can tell by the argument's type. Everything in Swift has a type, including functions and closures.
For example, this function...
func add(a: Int, to b: Int) -> Int { return a + b }
...has type (Int, Int) -> Int. (It takes two Ints as parameters, and returns an Int.)
And this closure...
let identity: Int -> Int = { $0 }
...has type Int -> Int.
Every function and closure has a type, and in the type signature there is always a -> that separates the parameters from the return value. So anytime you see a parameter (like isSeparator) that has a -> in it, you know that the parameter expects a closure.
the isSeparator definition means (Self.Generator.Element) throws -> Bool that you will be given an Element and you should return a Bool. When you will call split, you then can do the following :
[1,2,3].split(…, isSeparator : { element -> Bool in
return false
})
This is a pure silly example but that illustrates the second part of your question

Generic within a generic in Swift

Trying to make sense of the code below.
I understand that T is passed by when instantiating the Optional, as in Optional, but what about the U type in map. What type does that assume?
enum Optional<T> : LogicValue, Reflectable {
case None
case Some(T)
init()
init(_ some: T)
/// Allow use in a Boolean context.
func getLogicValue() -> Bool
/// Haskell's fmap, which was mis-named
func map<U>(f: (T) -> U) -> U?
func getMirror() -> Mirror
}
The type U comes from the f parameter to the map function. So if you pass a closure that returns a Int, then map returns a Int?. If you pass a closure that returns a Array<Int>, then map returns a Array<Int>?.
For example, try this:
var opt1: Optional<Int> = .Some(1)
var opt2 = opt1.map { (i: Int) -> String in return "String: \(i)" }
You'll find that opt1 is an Int? and opt2 is a String?.
When calling the map function the caller must provide a single argument which is a closure that:
Has a single argument that is the same type as the one used to
instantiate Optional, i.e. T
Has a return value of some type.
U will then be the type of said return value.