Unwrapping with flatMap - swift

I want to get the weekday int of a date that I know exists like this:
let dayOfWeek = Calendar.current.dateComponents([.weekday], from: row.date).weekday
However, this returns an optional, and I'm trying to figure out how to avoid force unwrapping it.
My though was to do:
let dayOfWeek = (row.date).compactMap( { Calendar.current.dateComponents([.weekday], from: $0).weekday!
})
However this gives me the error "value of type 'Date' has no member 'compactMap'"
Can someone tell me what I'm doing wrong, or how I should go about fixing this?

No optionals are needed. It's simply:
let dayOfWeek = Calendar.current.component(.weekday, from: row.date)
Note, flatMap is not relevant here because row.date is not an optional. But even if it were, it's worth noting that the Optional method flatMap has not had its name changed. It's still flatMap. Only the Sequence method of this name has been changed to compactMap.
See Swift Evolution 0187: Introduce Sequence.compactMap(_:)
So, this is still flatMap:
let foo: Int? = 42
let bar: String? = foo.flatMap { i -> String in
return "The value is \(i)"
}
// Optional("The value is 42")
Note, the returned value is an optional String?. In your example, it looks like you're trying to use flatMap to unwrap your optional, but that's not what flatMap is for. It's for calling the closure if it can unwrap foo, but for returning nil if it can't unwrap it. So it just returns another optional (a String? in my above example).
The flatMap that has been renamed to compactMap in Swift 4.1 is the Sequence rendition:
let baz = ["1", "2", "x", "3"]
let qux: [Int] = baz.compactMap { string -> Int? in
return Int(string) // return integer value if it could convert it, return `nil` if not
}
// [1, 2, 3]
To make it even more confusing, there is still flatMap used with sequences:
let letters = ["a", "b", "c"]
let quux = letters.map { Array(repeating: $0, count: 3) }
// [["a", "a", "a"], ["b", "b", "b"], ["c", "c", "c"]]
let quuz = letters.flatMap { Array(repeating: $0, count: 3) }
// ["a", "a", "a", "b", "b", "b", "c", "c", "c"]

There is no need to avoid forced unwrapping in this case. While weekday is optional, it will never be nil when you specifically request the .weekday component.
let dayOfWeek = Calendar.current.dateComponents([.weekday], from: row.date).weekday!

Related

Why do two distinct array literals equal each other in Swift?

Why does the expression
import Foundation
["a", "b", "c"] == ["c", "b", "a"]
evaluate to true in a Swift playground?
(The expression evaluates to false when Foundation is not imported.)
Josh's answer is close, but not quite right. Option-click on the equals operator. Your literals are Foundation.CharacterSets.
public static func == (lhs: CharacterSet, rhs: CharacterSet) -> Bool
For literal resolution, the compiler is going to search
The module you're working in.
Your imports.
The Swift standard library. (Which has some special module-scope-disambiguation rule where implicitly-typed literals are Arrays, because that makes working with the language easier for the most part.)
Is this a bug of ambiguity? Yes. Is it resolvable? I doubt it. I bet it's broken because nobody has been able to get the performance to be good enough if it did an exhaustive search. But please, log a bug, find out, and report back!
Swift.Set conforms to ExpressibleByArrayLiteral and it appears that when you compare two ArrayLiterals the compiler does in fact choose to evaluate them as Set's. you can confirm that its true by doing this:
import Foundation
let a = ["a", "b", "c"]
let b = ["c", "b", "a"]
print(["a", "b", "c"] == ["c", "b", "a"])
print(["a", "b", "c"] as Set<String> == ["c", "b", "a"] as Set<String>)
print(["a", "b", "c"] as [String] == ["c", "b", "a"] as [String])
print(a == b)
true
true
false
false
TLDR if you don't annotate the type of an array literal the compiler is free to coerce the type to any type that it chooses to infer as long as it conforms to ExpressibleByArrayLiteral.

Difference between string array with quotations and without?

UserDefaults.standard.set(["a", "b"], forKey: "xxx")
if let def = UserDefaults.standard.array(forKey: "xxx") as? [String] {
print(def) // ["a", "b"]
}
if let def = UserDefaults.standard.array(forKey: "xxx") {
print(def) // [a, b]
}
In the second example, when you don't explicitly cast the array to [String] (leaving it as [Any]), the print console produces an array without quotation marks which suggests they aren't strings. What is happening here?
If you print out their types, you'll find that the second def is an array of NSTaggedPointerStrings. NSTaggedPointerString is a private subclass of NSString, and NSStrings print out to the console without the double quotes when inside an array.
UserDefaults.standard.set(["a", "b"], forKey: "xxx")
if let def = UserDefaults.standard.array(forKey: "xxx") as? [String] {
print(def) // ["a", "b"]
print(type(of: def)) // Array<String>
for element in def {
print(element, "is a", type(of: element)) // a is a String
// b is a String
}
}
if let def = UserDefaults.standard.array(forKey: "xxx") {
print(def) // [a, b]
print(type(of: def)) // Array<Any>
for element in def {
print(element, "is a", type(of: element)) // a is a NSTaggedPointerString
// b is a NSTaggedPointerString
}
}
print(["a", "b"] as [NSString]) // [a, b]
In the first example, you are optional unwrapping/inferring the array to an array of strings. So it's logged as ["a", "b"] which is the standard representation of string value in double-quotes.
In the second one, the type is not inferred so by default it's logged as an array of Any type values where you don't see any double-quotes.

How do I duplicate the content of a list in swift

I can't seem to find the answer to this question (I keep getting answers for multiplying a list). I'm new to swift so bear with me.
I have a list say
a = ['a']
in python I can just do a*3 and then I end up with ['a','a','a'] however swift doesn't seem to like this. What is the correct syntax to get the same result in swift?
Note: Suppose that a always has a length of 1.
You can't multiply an array by an Int in Swift, but that isn't hard to add:
func *<T>(_ array: [T], _ count: Int) -> [T] {
return Array(Array(repeating: array, count: count).joined())
}
Examples:
let a = ["a", "b"]
let a3 = a * 3
print(a3)
["a", "b", "a", "b", "a", "b"]
print(["b"] * 5)
["b", "b", "b", "b", "b"]
For people who also have a similar problem, credit goes to matt for finding the solution. Below is the example in the documentation.
let fiveZs = Array(repeating: "Z", count: 5)
print(fiveZs)
// Prints "["Z", "Z", "Z", "Z", "Z"]"

Difference between flatMap and compactMap in Swift

It seems like in Swift 4.1 flatMap is deprecated. However there is a new method in Swift 4.1 compactMap which is doing the same thing?
With flatMap you can transform each object in a collection, then remove any items that were nil.
Like flatMap
let array = ["1", "2", nil]
array.flatMap { $0 } // will return "1", "2"
Like compactMap
let array = ["1", "2", nil]
array.compactMap { $0 } // will return "1", "2"
compactMap is doing the same thing.
What are the differences between these 2 methods? Why did Apple decide to rename the method?
The Swift standard library defines 3 overloads for flatMap function:
Sequence.flatMap<S>(_: (Element) -> S) -> [S.Element]
Optional.flatMap<U>(_: (Wrapped) -> U?) -> U?
Sequence.flatMap<U>(_: (Element) -> U?) -> [U]
The last overload function can be misused in two ways:
Consider the following struct and array:
struct Person {
var age: Int
var name: String
}
let people = [
Person(age: 21, name: "Osame"),
Person(age: 17, name: "Masoud"),
Person(age: 20, name: "Mehdi")
]
First Way: Additional Wrapping and Unwrapping:
If you needed to get an array of ages of persons included in people array you could use two functions :
let flatMappedAges = people.flatMap({$0.age}) // prints: [21, 17, 20]
let mappedAges = people.map({$0.age}) // prints: [21, 17, 20]
In this case the map function will do the job and there is no need to use flatMap, because both produce the same result. Besides, there is a useless wrapping and unwrapping process inside this use case of flatMap.(The closure parameter wraps its returned value with an Optional and the implementation of flatMap unwraps the Optional value before returning it)
Second Way - String conformance to Collection Protocol:
Think you need to get a list of persons' name from people array. You could use the following line :
let names = people.flatMap({$0.name})
If you were using a swift version prior to 4.0 you would get a transformed list of
["Osame", "Masoud", "Mehdi"]
but in newer versions String conforms to Collection protocol, So, your usage of flatMap() would match the first overload function instead of the third one and would give you a flattened result of your transformed values:
["O", "s", "a", "m", "e", "M", "a", "s", "o", "u", "d", "M", "e", "h", "d", "i"]
So, How did they solve it? They deprecated third overload of flatMap()
Because of these misuses, swift team has decided to deprecate the third overload to flatMap function. And their solution to the case where you need to to deal with Optionals so far was to introduce a new function called compactMap() which will give you the expected result.
There are three different variants of flatMap. The variant of Sequence.flatMap(_:) that accepts a closure returning an Optional value has been deprecated. Other variants of flatMap(_:) on both Sequence and Optional remain as is. The reason as explained in proposal document is because of the misuse.
Deprecated flatMap variant functionality is exactly the same under a new method compactMap.
See details here.
High-order function - is a function which operates by another function in arguments or/and returned. For example - sort, map, filter, reduce...
map vs compactMap vs flatMap
[RxJava Map vs FlatMap]
map - transform(Optional, Sequence, String)
flatMap - flat difficult structure into a single one(Optional, Collection)
compactMap - next step of flatMap. removes nil
flatMap vs compactMap
Before Swift v4.1 three realisations of flatMap had a place to be(without compactMap). That realisation were responsible for removing nil from a sequence. And it were more about map than flatMap
Experiments
//---------------------------------------
//map - for Optional, Sequence, String, Combine
//transform
//Optional
let mapOptional1: Int? = Optional(1).map { $0 } //Optional(1)
let mapOptional2: Int? = Optional(nil).map { $0 } //nil
let mapOptional3: Int?? = Optional(1).map { _ in nil } //Optional(nil)
let mapOptional4: Int?? = Optional(1).map { _ in Optional(nil) } //Optional(nil)
//collection
let mapCollection1: [Int] = [1, 2].map { $0 } //[1, 2]
let mapCollection2: [Int?] = [1, 2, nil, 4].map { $0 } //Optional(1), Optional(2), nil, Optional(4),
let mapCollection3: [Int?] = ["Hello", "1"].map { Int($0) } //[nil, Optional(1)]
//String
let mapString1: [Character] = "Alex".map { $0 } //["A", "l", "e", "x"]
//---------------------------------------
//flatMap - Optional, Collection, Combime
//Optional
let flatMapOptional1: Int? = Optional(1).flatMap { $0 } //Optional(1)
let flatMapOptional2: Int? = Optional(nil).flatMap { $0 } //nil
let flatMapOptional3: Int? = Optional(1).flatMap { _ in nil }
let flatMapOptional4: Int? = Optional(1).flatMap { _ in Optional(nil) }
//Collection
let flatMapCollection1: [Int] = [[1, 2], [3, 4]].flatMap { $0 } //[1, 2, 3, 4]
let flatMapCollection2: [[Int]] = [[1, 2], nil, [3, 4]].flatMap { $0 } //DEPRECATED(use compactMap): [[1, 2], [3, 4]]
let flatMapCollection3: [Int?] = [[1, nil, 2], [3, 4]].flatMap { $0 } //[Optional(1), nil, Optional(2), Optional(3), Optional(4)]
let flatMapCollection4: [Int] = [1, 2].flatMap { $0 } //DEPRECATED(use compactMap):[1, 2]
//---------------------------------------
//compactMap(one of flatMap before 4.1) - Array, Combine
//removes nil from the input array
//Collection
let compactMapCollection1: [Int] = [1, 2, nil, 4].compactMap { $0 } //[1, 2, 4]
let compactMapCollection2: [[Int]] = [[1, 2], nil, [3, 4]].compactMap { $0 } //[[1, 2], [3, 4]]
[Swift Optional map vs flatMap]
[Swift Functor, Applicative, Monad]

Can swift optionals be mapped to new values?

In java 8, you can do the following: -
Optional<String> foo = Optional.empty(); // or Optional.of("hello");
foo.map(String::toUpperCase).orElse("Empty String")
edit - another example
class Bar {
public Bar(final String baz) { ... }
}
foo.map(f -> new Bar(f)) // has mapped into an optional Bar
That toUpperCase was a little too simplified; I'm thinking more like being able to specify a lambda or function that can provide a mutated value based on an optional present.
I see that you can do the following in swift: -
guard let foo = optional else { return "Empty String" }
which is massively useful, and also
optional ?? "Empty String"
but is there any way to map a value based on the value being optionally present? i.e. so if a value is present, you can return a mutated value?
This functionality is also available for java/c# collections
Say for a given array of optional strings, you can make use of optional chaining within your map operation
let foo: [String?] = ["foo", "bar", nil, "baz"]
let bar = foo.map { $0?.uppercaseString ?? "Empty string" }
print(bar) // ["FOO", "BAR", "Empty string", "BAZ"]
A possibly more useful alternative is to apply a flatMap operation to simply remove nil-valued optional entries from the string array
let foo: [String?] = ["foo", "bar", nil, "baz"]
let bar = foo.flatMap { $0?.uppercaseString }
print(bar) // ["FOO", "BAR", "BAZ"]
W.r.t. your comment, you could e.g. call a failable initializer for, say, some structure Foo, within the flatMap operation, yielding an array of Foo instances given that the initializer succeeds.
struct Foo {
let foo: String
init?(bar: String?) {
guard let foo = bar else {
return nil
}
self.foo = foo
}
}
let foo: [String?] = ["foo", "bar", nil, "baz"]
let bar = foo.flatMap { Foo(bar: $0) }
print(bar) // [Foo(foo: "foo"), Foo(foo: "bar"), Foo(foo: "baz")]
In your example, that's just:
optional?.uppercaseString ?? "EMPTY STRING"
or if you'd prefer to modify after defaulting:
(optional ?? "empty string").uppercaseString
Did you have something more complicated in mind?
(You may be unfamiliar with the ?. operator. It's called optional chaining in Swift, and is similar to map.)