Created
July 15, 2019 21:02
-
-
Save Uncommon/2dc1a863d79b25d7355c3bc28e4a958e to your computer and use it in GitHub Desktop.
Enum backed with Int and String
This file contains hidden or 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 | |
protocol IntAndString: RawRepresentable where RawValue == (Int, String) | |
{ | |
static var invalidInt: Int { get } | |
static var invalidString: String { get } | |
} | |
extension IntAndString | |
{ | |
var int: Int { return self.rawValue.0 } | |
var string: String { return self.rawValue.1 } | |
static var invalidInt: Int { return -1 } | |
static var invalidString: String { return "" } | |
init?(int: Int) { self.init(rawValue: (int, Self.invalidString)) } | |
init?(string: String) { self.init(rawValue: (Self.invalidInt, string)) } | |
} | |
extension IntAndString where Self: CaseIterable | |
{ | |
init?(rawValue: (Int, String)) | |
{ | |
if let match = Self.allCases.first(where: { $0.rawValue.0 == rawValue.0 || $0.rawValue.1 == rawValue.1 }) { | |
self = match | |
} | |
else { | |
return nil | |
} | |
} | |
} | |
enum Numbering: CaseIterable | |
{ | |
case first | |
case second | |
} | |
extension Numbering: IntAndString | |
{ | |
var rawValue: (Int, String) | |
{ | |
switch self { | |
case .first: return (1, "first") | |
case .second: return (2, "second") | |
} | |
} | |
} | |
let a = Numbering(int: 2) | |
let b = Numbering(string: "first") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment