Reputation: 37
Is Map
function of Optional
in Swift just used to transform
?
If I want do something just Optional has some value, Can I Use map
function? if not, why?
According to apples examples, we used map
like this
let possibleNumber: Int? = Int("42")
possibleNumber.map { $0 * $0 }
Can I use it like this? : (If it's not proper, how to explain it)
func setImage(with data: Data?) {
data.flatMap { UIImage(data: $0) }
.map { imageView.image = $0 }
}
Furthermore map
function should return a value, but why this function does not have any warning
about not used of result ( such as result of call map{...} is unused
) ?
Upvotes: 1
Views: 200
Reputation: 63264
You certainly can do it, it's just not very conventional. When people see map
, they have a pre-conceived expectation that it'll be doing a transformation. You're violating that expectation, but there's nothing technically "wrong" about it.
Personally, I prefer using this extension:
extension Optional {
/// An enum used to ensure that `ifNone` is never called before `ifSome`.
enum IfSomeResult {
case some
case none
func ifNone(_ closure: () throws -> Void) rethrows -> Void {
switch self {
case .some: return
case .none: try _ = closure()
}
}
}
@discardableResult
func ifSome(then closure: (Wrapped) throws -> Void) rethrows -> IfSomeResult {
if let wrapped = self {
try _ = closure(wrapped)
return IfSomeResult.some
}
else {
return IfSomeResult.none
}
}
func ifNone(then closure: () throws -> Void) rethrows -> Void {
if case nil = self { try _ = closure() }
}
}
And writing code like:
data.flatMap { UIImage(data: $0) }
.ifSome { imageView.image = $0 }
The closure is inferred to return Void
(the empty tuple type, whose only value is the empty tuple, ()
). The compiler never emits warnings about Void
values being unused`. Here's an example:
Optional(123).map { _ in () }
Upvotes: 2