Created
June 27, 2016 17:22
-
-
Save lastMove/8cda639fe29a4db52ff03201890860d9 to your computer and use it in GitHub Desktop.
Simpler implementation
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
// IBEnum.swift | |
import Foundation | |
public protocol IBEnum { | |
init?(string:String) | |
} | |
public extension IBEnum { | |
/// Helper function that returns a tuple containing the name and params | |
/// | |
/// | |
/// - Discussion | |
/// Since "name(param1,param2,param3)" is the classic IBAnimatable format | |
/// | |
/// this method will return "wave" | |
static func extractNameAndParams(_ string:String) -> (name:String, params:[String]) { | |
let tokens = string.components(separatedBy: CharacterSet(charactersIn: "()")).filter({!$0.isEmpty}) // extract params list self.enumName | |
let maskName = tokens.first ?? ""; | |
let paramsString = tokens.count >= 2 ? tokens[1] : ""; | |
let params = paramsString.components(separatedBy: ","); // params list | |
return (name:maskName, params:params); | |
} | |
} | |
import Foundation | |
import UIKit | |
public enum MaskType: IBEnum { | |
case circle | |
case polygon(sides:Int?) | |
case star(points:Int?) | |
case triangle | |
case wave(direction:WaveDirection?, width:Float?, offset:Float?) | |
case parallelogram(angle:Double?) | |
case none | |
public enum WaveDirection:String { | |
case up | |
case down | |
} | |
} | |
// ---------------------------- MASKType --------------------------------------------------- | |
public extension MaskType { | |
init(string:String) { | |
let paramsAndName = MaskType.extractNameAndParams(string) | |
let name = paramsAndName.name; | |
let params = paramsAndName.params; | |
switch name.lowercased() { | |
case "circle": | |
self = MaskType.circle | |
case "polygon": | |
self = MaskType.polygon(sides: nil) | |
case "star": | |
self = MaskType.star(points: Int(params[0])) | |
case "triangle": | |
self = MaskType.triangle; | |
case "wave": | |
self = MaskType.wave(direction: WaveDirection(rawValue:params[0].lowercased()), width: Float(params[1]), offset:Float(params[2])) | |
case "parallelogram": | |
self = MaskType.parallelogram(angle: Double(params[0])) | |
default: | |
self = MaskType.none | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like this version. +1 I think it is OK to have a custom
init
for every enum, and they can use extension methodextractNameAndParams
to coverString
intoenum
.