Skip to content

Instantly share code, notes, and snippets.

@ashikahmad
Created July 31, 2017 09:22
Show Gist options
  • Save ashikahmad/de1dab36043ffa633fd735a019cc1c61 to your computer and use it in GitHub Desktop.
Save ashikahmad/de1dab36043ffa633fd735a019cc1c61 to your computer and use it in GitHub Desktop.
Using optionals easily: save you from frequent coelsing
//
// SafeOptional.swift
// TodoMVVM
//
// Created by Ashik uddin Ahmad on 7/20/17.
// Copyright © 2017 Ashik uddin Ahmad. All rights reserved.
//
import Foundation
protocol SafeUnwrappable { static func nilValue()->Self }
extension Optional where Wrapped:SafeUnwrappable {
var safe: Wrapped {
switch self {
case .some(let value): return value
case .none: return Wrapped.nilValue()
}
}
}
extension Int:SafeUnwrappable {
static func nilValue() -> Int { return 0 }
}
extension Float:SafeUnwrappable {
static func nilValue() -> Float { return 0 }
}
extension Double:SafeUnwrappable {
static func nilValue() -> Double { return 0 }
}
extension String: SafeUnwrappable {
static func nilValue() -> String { return "" }
}
extension Array: SafeUnwrappable {
static func nilValue() -> Array<Element> { return [] }
}
extension Dictionary: SafeUnwrappable {
static func nilValue() -> Dictionary<Key, Value> { return [:] }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment