Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.