add post about Optional.or(_:)

This commit is contained in:
Sami Samhuri 2017-10-06 14:31:59 -07:00
parent 34cbede753
commit b213a04010
No known key found for this signature in database
GPG key ID: F76F41F04D99808F
5 changed files with 56 additions and 11 deletions

View file

@ -19,6 +19,17 @@
"title": "Curriculum vitae"
},
"posts": [
{
"title": "A nil-coalescing alternative for Swift",
"date": "6th October, 2017",
"timestamp": 1507324813,
"tags": [
"ios",
"swift"
],
"author": "Sami J. Samhuri",
"url": "/posts/2017/10/swift-optional-or"
},
{
"title": "Easy Optimization Wins",
"date": "10th August, 2016",
@ -116,17 +127,6 @@
"author": "Sami J. Samhuri",
"url": "/posts/2015/07/scripts-to-rule-them-all",
"link": "http://githubengineering.com/scripts-to-rule-them-all/"
},
{
"title": "→ Debugging Layouts with Recursive View Descriptions in Xcode",
"date": "2nd June, 2015",
"timestamp": 1433288135,
"tags": [
],
"author": "Sami J. Samhuri",
"url": "/posts/2015/06/debugging-layouts-with-recursive-view-descriptions-in-xcode",
"link": "http://jeffreysambells.com/2013/01/24/debugging-layouts-with-recursive-view-descriptions-in-xcode"
}
]
}

View file

@ -0,0 +1,15 @@
{
"swift-optional-or": {
"id": "swift-optional-or",
"author": "Sami J. Samhuri",
"title": "A nil-coalescing alternative for Swift",
"date": "6th October, 2017",
"timestamp": 1507324813,
"link": null,
"url": "/posts/2017/10/swift-optional-or",
"tags": [
"ios",
"swift"
]
}
}

View file

@ -0,0 +1 @@
<%- partial('../../_month') %>

View file

@ -0,0 +1,28 @@
Swift compile times leave something to be desired and a common culprit is the affectionately-named [nil-coalescing operator][nilop]. A small extension to `Optional` can improve this without sacrificing a lot of readability.
```Swift
extension Optional {
func or(_ defaultValue: Wrapped) -> Wrapped {
switch self {
case .none: return defaultValue
case let .some(value): return value
}
}
}
```
And you use it like so:
```Swift
let dict: [String : String] = [:]
let maybeString = dict["not here"]
print("the string is: \(maybeString.or("default"))")
let otherString = dict["not here"].or("something else")
```
I'm sure someone else has come up with this already but I haven't seen it yet.
_([gist available here][gist])_
[nilop]: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6-ID72
[gist]: https://gist.github.com/samsonjs/c8933c07ad985b74aba994f2fdab8b47

View file

@ -0,0 +1 @@
<%- partial('../_year') %>