Last active
March 3, 2019 16:50
-
-
Save jjrscott/c03d6d9dbb7d60572804233adada97d2 to your computer and use it in GitHub Desktop.
Shortens `anArray.count ?? 0` to `anArray.count` just like in ObjC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Optional+SupportsCount.swift | |
// | |
// Created by John Scott on 02/03/2019. | |
// | |
/** | |
This file contains a little syntactic sugar to help the Objective-C oldies. | |
When calling `anArray.count` we often relied on ObjC to return `0` when `anArray` | |
was `nil`. These days, in Swift, we're forced to write something like: | |
``` | |
anArray.count ?? 0 | |
``` | |
:-( | |
The following code allows us to go back to the old way, but **just** for `count`. | |
*/ | |
import Foundation | |
protocol SupportsCount { | |
var count: Int { get } | |
} | |
extension ContiguousArray: SupportsCount {} | |
extension ArraySlice: SupportsCount {} | |
extension Array: SupportsCount {} | |
extension Optional where Wrapped: SupportsCount { | |
var count: Int { return self?.count ?? 0 } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment