Skip to content

Instantly share code, notes, and snippets.

@Moximillian
Last active March 30, 2016 18:21
Show Gist options
  • Save Moximillian/4566d20b5b89bff68d3b to your computer and use it in GitHub Desktop.
Save Moximillian/4566d20b5b89bff68d3b to your computer and use it in GitHub Desktop.
New valuetype for enums to convert a minimum and maximum value into Range<Int>
import Foundation
/// StringRangeRawValue – new valuetype that is compatible with RawValue => can be used as enum valuetype
struct StringRangeRawValue: StringLiteralConvertible, Equatable {
let range: Range<Int>
static func convert(value: String) -> Range<Int> {
let values = value.componentsSeparatedByString(",")
return Int(values[0])! ..< Int(values[1])!
}
init(range: Range<Int>) {
self.range = range
}
init(stringLiteral value: String) {
self.init(range: StringRangeRawValue.convert(value))
}
init(extendedGraphemeClusterLiteral value: String) {
self.init(range: StringRangeRawValue.convert(value))
}
init(unicodeScalarLiteral value: String) {
self.init(range: StringRangeRawValue.convert(value))
}
func isEqualTo(other: StringRangeRawValue) -> Bool {
return self.range == other.range
}
}
func == (lhs: StringRangeRawValue, rhs: StringRangeRawValue) -> Bool { return lhs.isEqualTo(rhs) }
// enum that uses StringRangeRawValue as value type to convert a string range to actual Range<Int> type
enum AgeGroup: StringRangeRawValue {
case Infant = "0,1"
case Toddler = "1,5"
case Child = "5,12"
var value: Range<Int> { return rawValue.range }
}
// EXAMPLE 1: matching with the right age category (switch cases with ranges)
let personsAge = 2
switch personsAge {
case AgeGroup.Infant.value: print(AgeGroup.Infant)
case AgeGroup.Toddler.value: print(AgeGroup.Toddler)
case AgeGroup.Child.value: print(AgeGroup.Child)
default: break
}
// EXAMPLE 2: checking whether an age matches with an age category (if + "within range" operator)
let toddlerAge = AgeGroup.Toddler
if toddlerAge.value ~= 3 {
print ("yea")
} else {
print ("nope")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment