Skip to content

Instantly share code, notes, and snippets.

@petrsvihlik
Created August 17, 2022 12:45
Show Gist options
  • Save petrsvihlik/9076c8eb333c0b4617377be50f4fae81 to your computer and use it in GitHub Desktop.
Save petrsvihlik/9076c8eb333c0b4617377be50f4fae81 to your computer and use it in GitHub Desktop.
Some swift enum hocus pocus
import Foundation
public enum ShapeRawEnum: String, RawRepresentable {
case square
case circle
public var requestString: String {
return self.rawValue
}
func callAsFunction() -> String {
return self.rawValue
}
public init?(rawValue: String) {
switch rawValue.lowercased() {
case "square":
self = .square
case "circle":
self = .circle
default:
return nil
}
}
}
public struct ExtensibleStruct<T> where T: RawRepresentable, T.RawValue == String {
private let _rawValue: T
public let value: String
public init(rawValue: T) {
_rawValue = rawValue
value = rawValue.rawValue
}
}
public func switchStructTest(shape: ExtensibleStruct<ShapeRawEnum>) {
switch shape.value
{
case ShapeRawEnum.circle.requestString: // could this be made simpler via an implicit conversion to string?
print("⚫")
case ShapeRawEnum.square.requestString:
print("⬛")
case ShapeRawEnum(rawValue: "triangle")?.rawValue:
print("▶️")
default:
print("default")
}
}
let circleStruct: ExtensibleStruct<ShapeRawEnum> = ExtensibleStruct<ShapeRawEnum>.init(
rawValue: ShapeRawEnum.circle)
switchStructTest(shape: circleStruct)
/// ******** Another approach **********/
public enum ShapeSwiftEnum {
case custom(String)
case square
case circle
public var requestString: String {
switch self {
case let .custom(val):
return val
case .square:
return "square"
case .circle:
return "circle"
}
}
public init(rawValue: String) {
switch rawValue.lowercased() {
case "square":
self = .square
case "circle":
self = .circle
default:
self = .custom(rawValue)
}
}
}
internal class NeverSwitchOnThis {}
public enum Extensible<T> {
case some(T)
case none
case NeverSwitchOnThis
}
public func switchTest(shape: Extensible<ShapeSwiftEnum>) {
switch shape
{
case .some(ShapeSwiftEnum.circle):
print("⚫")
case .some(.square):
print("⬛")
case .some(.custom(let custom)):
print(custom)
case .none:
print(shape)
default:
print(shape)
}
}
let circle: Extensible<ShapeSwiftEnum> = Extensible<ShapeSwiftEnum>.some(.circle)
switchTest(shape: circle)
let square: Extensible<ShapeSwiftEnum> = Extensible<ShapeSwiftEnum>.some(.square)
switchTest(shape: square)
let triangle: Extensible<ShapeSwiftEnum> = Extensible<ShapeSwiftEnum>.some(.custom("triangle"))
switchTest(shape: triangle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment