Last active
July 22, 2019 06:43
-
-
Save freshking/086a031b3a0aebbb65aef61944c3d393 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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