boudhayan
5/5/2018 - 7:12 PM

NilCoalescingAutoClosure.swift

import Darwin
//Declare nil-coalescing operator
infix operator ??

/// Nil-coalescing operator defination
///
/// - Parameters:
///   - optional: optinal variable
///   - defaultValue: autoclosure, which returns the unwrapped value & removes the need explicit curly braces for closure
/// - Returns: If optional has some value, it returns the unwrapped value else returns the default value.

func ??<U>(optional: U?, defaultValue: @autoclosure () throws -> U) rethrows ->  U {
    if let value = optional {
        return value
    }else {
        return try defaultValue()
    }
}

//Example usage
let x = population ?? defaultPopulation