Skip to content

Instantly share code, notes, and snippets.

@TheDarkCode
Last active February 20, 2016 17:45
Show Gist options
  • Save TheDarkCode/1dd35f0baeaedf9592b7 to your computer and use it in GitHub Desktop.
Save TheDarkCode/1dd35f0baeaedf9592b7 to your computer and use it in GitHub Desktop.
Example of alternative method for doing if / else statements using Nil Coalescing Operator.
//
// NilCoalescingOperator.swift
// Example of alternative method for doing if / else statements using Nil Coalescing Operator.
//
// Created by Mark Hamilton on 2/20/16.
// Copyright © 2016 dryverless. All rights reserved.
//
private var _otherObject: OtherObject? // returns nil unless set
private let _defaultObject: DefaultObject! = DefaultObject() // create a default
var publicObject: AnyObject {
// if _otherObject is not nil, return it, otherwise return _defaultObject
// short hand version of doing the line as: if let object = _otherObject != nil ? _otherObject! : _defaultObject
if let object = _otherObject ?? _defaultObject {
return object
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment