How to make an enum conform to a protocol in Swift?
This is my attempt:
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
enum ExampleEnum : ExampleProtocol {
case Base, Adjusted
var simpleDescription: String {
return self.getDescription()
}
func getDescription() -> String {
switch self {
case .Base:
return "A simple description of enum"
case .Adjusted:
return "Adjusted description of enum"
}
}
mutating func adjust() {
self = ExampleEnum.Adjusted
}
}
var c = ExampleEnum.Base
c.adjust()
let cDescription = c.simpleDescription
How to require an enum be defined in Swift Protocol
Protocols can have associatedtypes
which would just need to be adhered to in any subclass:
enum MyEnum: String {
case foo
case bar
}
protocol RequiresEnum {
associatedtype SomeEnumType: RawRepresentable where SomeEnumType.RawValue: StringProtocol
func doSomethingWithEnum(someEnumType: SomeEnumType)
}
class MyRequiresEnum: RequiresEnum {
typealias SomeEnumType = MyEnum
func doSomethingWithEnum(someEnumType: SomeEnumType) {
switch someEnumType {
case .foo:
print("foo")
case .bar:
print("bar")
}
}
}
let mre = MyRequiresEnum()
mre.doSomethingWithEnum(.bar)
Edit: The associatedtype
must be adhered to
Unable to make a protocol for enum
Enums get their raw value via the RawRepresentable
protocol, so that's what you should use when constraining your extension:
extension Named where Self: RawRepresentable, RawValue == String {
var name: String {
let str: String = self.rawValue
return str.prefix(1).uppercased() + str.dropFirst()
}
}
You also need to declare that your enum uses a String
as the type of its rawValue
:
enum Furniture: String, Named {
case table, chair, lamp
}
Swift Enum associated values conforming to single protocol
I've found the solution in case anyone will need this too.
enum ContentType {
case content1(Type1 & Refreshable)
case content2(Type2 & Refreshable)
case content3(someLabel: Type3 & Refreshable)
func refreshMe() {
let caseReflection = Mirror(reflecting: self).children.first!.value
(caseReflection as? Refreshable)?.refresh() //If associated type doesn't have label
let refreshable = Mirror(reflecting: caseReflection).children.first?.value as? Refreshable
refreshable?.refresh() //If associated type has label
}
}
Enum conforming to protocol with stored property
OK, so the error you are getting is because all properties must be computed. So, in your simple example, you could do something like this:
enum SimpleEnum: ExampleProtocol {
case foo, bar
var simpleDescription: String {
switch self {
case .foo: return "Foo"
case .bar: return "Bar"
}
}
func adjust() {
}
}
Swift: Make Int Enum conform to Plottable protocol in order to show a legend using Swift Charts
As documentation states for enum
it should be String
as raw type
so making next works (tested with Xcode 14b5 / iOS 16)
enum Type: String, CaseIterable, Identifiable, Plottable {
init?(primitivePlottable: String) {
self.init(rawValue: primitivePlottable)
}
var primitivePlottable: String {
return rawValue
}
var id: String {
return rawValue
}
case first = "32"
case second = "434"
}
Array of enum types conforming to a protocol with an associated type
I want to display a menu listing all the possible options.
So you want Strings, not the cases themselves. That's absolutely doable. First, start by saying what you really want the type to do in the form of a protocol:
protocol CaseNamed {
static var caseNames: [String]
}
If you had that, you could build what you want:
var enums: [CaseNamed.Type] = [A.self, B.self]
enums.flatMap { $0.caseNames }
(I call this "wish driven development." I wish I had a type that could....)
Now you just need to conform types to CaseNamed by implementing caseNames
. Luckily that's easy if the type also happens to conform to CaseIterable:
extension CaseNamed where Self: CaseIterable {
static var caseNames: [String] {
self.allCases.map { "\($0)" }
}
}
But you can have CaseNamed types that don't conform to CaseIterable. CaseIterable isn't a requirement. It's just nice if you have it. Here's the full code:
protocol CaseNamed {
static var caseNames: [String] { get }
}
enum A: String, CaseIterable, CaseNamed {
case a1, a2, a3
}
enum B: String, CaseIterable, CaseNamed {
case b1, b2, b3
}
extension CaseNamed where Self: CaseIterable {
static var caseNames: [String] {
self.allCases.map { "\($0)" }
}
}
var enums: [CaseNamed.Type] = [A.self, B.self]
enums.flatMap { $0.caseNames }
Now of course you might also want this CaseNamed protocol to do other things, so you can add those other things. But you need to think in terms of the calling code and what it fundamentally needs to do its job.
Swift: Make Int Enum conform to Plottable protocol in order to show a legend using Swift Charts
As documentation states for enum
it should be String
as raw type
so making next works (tested with Xcode 14b5 / iOS 16)
enum Type: String, CaseIterable, Identifiable, Plottable {
init?(primitivePlottable: String) {
self.init(rawValue: primitivePlottable)
}
var primitivePlottable: String {
return rawValue
}
var id: String {
return rawValue
}
case first = "32"
case second = "434"
}
Related Topics
Swiftui - in Sheet Have a Fixed Continue Button That Is Not Scrollable
Nsimage Getting Resized When I Draw Text on It
Create View Based Nstableview Programmatically Using Bindings in Swift
How to Open a Screen Directly in Xcuitest
Cross Platform Aes Encryption Between iOS and Kotlin/Java Using Apples Cryptokit
Map and Flatmap Difference in Optional Unwrapping in Swift 1.2
Uitextview Change Text Color of Specific Text
Generatesdecimalnumbers for Numberformatter Does Not Work
System Volume Change Observer Not Working on iOS 15
How to Set Exit Code Value for a Command Line Utility in Swift
Skaction Completion Handlers; Usage in Swift
Realitykit - How to Set a Modelentity's Transparency
Use Multiple Codingkeys for a Single Property
Dynamic/Runtime Dispatch in Swift, or "The Strange Way Structs Behave in One Man's Opinion"