Skip to content

Instantly share code, notes, and snippets.

@jjrscott
Last active March 3, 2019 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjrscott/c03d6d9dbb7d60572804233adada97d2 to your computer and use it in GitHub Desktop.
Save jjrscott/c03d6d9dbb7d60572804233adada97d2 to your computer and use it in GitHub Desktop.
Shortens `anArray.count ?? 0` to `anArray.count` just like in ObjC
//
// 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