New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add convenience protocol for enums #112

Merged
merged 3 commits into from May 16, 2018
Merged
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.
+51 −0
Diff settings

Always

Just for now

@@ -29,3 +29,54 @@ extension MySQLText: MySQLColumnDefinitionStaticRepresentable {
return .text()
}
}

// MARK: Enum
/// This type-alias makes it easy to declare nested enum types for your `MySQLModel`.
///
/// enum PetType: Int, MySQLEnumType {
/// case cat, dog
/// }
///
/// `MySQLEnumType` can be used easily with any enum that has a `MySQLType` conforming `RawValue`.
///
/// You will need to implement custom `ReflectionDecodable` conformance for enums that have non-standard integer
/// values or enums whose `RawValue` is not an integer.
///
/// enum FavoriteTreat: String, MySQLEnumType {
/// case bone = "b"
/// case tuna = "t"
/// static func reflectDecoded() -> (FavoriteTreat, FavoriteTreat) {
/// return (.bone, .tuna)
/// }
/// }
///
public protocol MySQLEnumType: MySQLType, ReflectionDecodable, Codable, RawRepresentable where Self.RawValue: MySQLDataConvertible { }

/// Provides a default `MySQLColumnDefinitionStaticRepresentable` implementation where the type is also
/// `RawRepresentable` by a `MySQLColumnDefinitionStaticRepresentable` type.
extension MySQLColumnDefinitionStaticRepresentable where Self: RawRepresentable, Self.RawValue: MySQLColumnDefinitionStaticRepresentable
{
public static var mySQLColumnDefinition: MySQLColumnDefinition { return RawValue.mySQLColumnDefinition }
}

/// Provides a default `MySQLDataConvertible` implementation where the type is also
/// `RawRepresentable` by a `MySQLDataConvertible` type.
extension MySQLDataConvertible where Self: RawRepresentable, Self.RawValue: MySQLDataConvertible
{
/// See `MySQLDataConvertible.convertToMySQLData()`
public func convertToMySQLData() throws -> MySQLData {
return try rawValue.convertToMySQLData()
}

/// See `MySQLDataConvertible.convertFromMySQLData(_:)`
public static func convertFromMySQLData(_ data: MySQLData) throws -> Self {
guard let extractedCase = try self.init(rawValue: .convertFromMySQLData(data)) else {
throw MySQLError(
identifier: "rawValue",
reason: "Could not create `\(Self.self)` from: \(data)",
source: .capture()
)
}
return extractedCase
}
}
ProTip! Use n and p to navigate between commits in a pull request.