Skip to content

Instantly share code, notes, and snippets.

@freshking
Last active July 22, 2019 06:43
Show Gist options
  • Save freshking/086a031b3a0aebbb65aef61944c3d393 to your computer and use it in GitHub Desktop.
Save freshking/086a031b3a0aebbb65aef61944c3d393 to your computer and use it in GitHub Desktop.
import Foundation
/// operator declaration
infix operator <-
/// Maps right instance to left if of same type
///
/// - Parameters:
/// - left: optional instance to be mapped
/// - right: optional mapping value
func <- <T>(left: inout T?, right: Any?) {
if right != nil {
left = right as? T
} else {
()
}
}
// Maps right instance to left if of same type
//
// - Parameters:
/// - left: optional instance to be mapped
/// - right: optional mapping value
func <- <T: RawRepresentable>(left: inout T?, right: Any?) {
if let right = right as? T {
left = right
return
}
if let right = right as? T.RawValue {
left = T(rawValue: right)
} else {
()
}
}
// MARK:- Example
/// Gender enumeration
enum Gender: String {
case male
case female
case lgbt
}
/// Person structure containing name, age and gender
struct Person {
var firstName: String?
var lastName: String?
var age: Int?
var gender: Gender?
init(dictionary: [String : Any]) {
firstName <- dictionary["firstName"]
lastName <- dictionary["lastName"]
age <- dictionary["age"]
gender <- dictionary["gender"]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment