XCT assert case of enum - swift

I'd like to assert whether a value is a specific enum case.
For example, if I have the following enum class, and a variable let value: MyEnum:
enum MyEnum {
case firstCase(value: Int)
case secondCase
}
I'd like to check whether value is an instance of firstCase.
In essence, I'd like to be able to write the following or something equivalent:
let value: MyEnum = .firstCase(value: 3)
XCTAssertEnumCase(value, .firstCase)
How can I achieve this? I'm looking for an already existing XCT function, or for instructions how to write XCTAssertEnumCase myself.

You can easily create a function that works for specific enums, however, creating a generic assert function that works for any enums will be quite hard to achieve, because there's no protocol/type constraint that could represent any enum. You can use RawRepresentable for enums with raw values, but that won't cover all enums, such as the one in your question.
This is the function for your specific enum.
func XCTAssertEnumCase(_ testValue: MyEnum, _ expectedValue: MyEnum) -> Bool {
switch (testValue, expectedValue) {
case (.firstCase, .firstCase):
return true
case (.secondCase, .secondCase):
return true
default:
return false
}
}
Alternatively, you can make your enum conform to Equatable in your test target (if it doesn't already conform in your actual production target) and only check case equality in your Equatable conformance, but then you won't be able to easily test "full equality" (including the associated values). Also, the solution will require you to manually implement Equatable conformance for all protocols that you are testing.
You cannot instantiate an enum case that has an associated value without actually supplying an associated value. So XCTAssertEnumCase(value, .firstCase) cannot be achieved.
You can do XCTAssertEnumCase(testValue, .firstCase(value: 3313) where you can pass in any Int to the associated value of firstCase and as long as testValue is also firstCase, the func will return true, regardless of the associated values.
Alternatively, you could create separate functions for asserting each case of your enum.
extension MyEnum {
func assertFirstCase() -> Bool {
switch self {
case .firstCase:
return true
default:
return false
}
}
func assertSecondCase() -> Bool {
switch self {
case .secondCase:
return true
default:
return false
}
}
}
And then use it like this:
let value: MyEnum = .firstCase(value: 3)
value.assertFirstCase() // returns true
value.assertSecondCase() // returns false

Related

Understanding CaseIterable in swift

I've read the documentation, and seen perhaps only a part of what the protocol is. I just am not following the logic. Can someone help me understand this?
What I see in xcode when I examine the protocol
/// Conforming to the CaseIterable Protocol
/// =======================================
///
/// The compiler can automatically provide an implementation of the
/// `CaseIterable` requirements for any enumeration without associated values
/// or `#available` attributes on its cases. The synthesized `allCases`
/// collection provides the cases in order of their declaration.
///
/// You can take advantage of this compiler support when defining your own
/// custom enumeration by declaring conformance to `CaseIterable` in the
/// enumeration's original declaration. The `CompassDirection` example above
/// demonstrates this automatic implementation.
public protocol CaseIterable {
/// A type that can represent a collection of all values of this type.
associatedtype AllCases : Collection = [Self] where Self == Self.AllCases.Element
/// A collection of all values of this type.
static var allCases: Self.AllCases { get }
}
I'm struggling to follow what is happening here and why. Can someone walk me through the logic of this please?
One of the other big struggles I'm having because of this is if I conform a protocol to be CaseIterable.
protocol Foo: CaseIterable {}
I can't use it as a variable anymore.
struct Bar {
var foo: Foo
}
I get this error
Protocol 'Foo' can only be used as a generic constraint because it has Self or associated type requirements.
It does have Self requirements but I can't figure out how to get around this problem. If someone could help me understand why this happens and how to fix it too, I'd be very grateful.
Edit: - This is the playground code copied directly. I've updated it to use the some, but I'm not quite sure how to proceed past this error.
import Foundation
protocol Zot: CaseIterable {
var prop: Data { get }
}
enum Bar: Zot {
case thing3
case thing4
var prop: Data {
switch self {
case .thing3, .thing4: return Data()
}
}
init() {}
}
enum Baz: Zot {
case thing1
case thing2
var prop: Data {
switch self {
case .thing1, .thing2: return Data()
}
}
init() {}
}
enum Foo {
case bar
case baz
var otherValues: some Zot {
switch self {
case .bar:
return Bar
case .baz:
return Baz
}
}
}
CaseIterable exists to allow you to programmatically walk through all the possible cases of an enum, allowing you use the enum type as a Collection of its cases:
enum CardinalDirection: CaseIterable { case north, south, east, west }
for direction in CardinalDirection.allCases {
// Do something with direction which is one of north, south, east, west
print("\(direction)")
}
This prints
north
south
east
west
There is nothing that prevents you from making other kinds of types conform to CaseIterable; however, the compiler will only synthesize conformance for enum types. It's not useful for most other kinds of types; however, I have occasionally found it useful for types that conform to OptionSet. In that case you have to manually implement conformance.
struct AssetFlags: OptionSet, CaseIterable
{
typealias RawValue = UInt8
typealias AllCases = [AssetFlags]
let rawValue: RawValue
static let shouldPreload = AssetFlags(rawValue: 0x01)
static let isPurgeable = AssetFlags(rawValue: 0x02)
static let isLocked = AssetFlags(rawValue: 0x04)
static let isCached = AssetFlags(rawValue: 0x08)
static var allCases: AllCases = [shouldPreload, isPurgeable, isLocked, isCached]
}
Note that OptionSet is conceptually similar to an enum. They both define a small set of distinct values they can have. With one they are mutually exclusive, while for the other they may be combined. But the key thing for CaseIterable to be useful is the finite nature of the set of possible distinct values. If your type has that characteristic, conforming to CaseIterable could be useful, otherwise, it wouldn't make sense. Int or String, for example, are not good candidates for CaseIterable.
In my own code, I don't bother conforming to CaseIterable, even for enum types, until a specific need arises that requires it. Actually I take that approach to all protocol conformance. It's a specific case of the more general YAGNI rule of thumb: "You ain't gonna need it."
Regarding your Bar struct, the problem is not specifically related to CaseIterable, but rather to using a protocol with Self or associated type requirements, which for Foo happens to be inherited from CaseIterable.
Swift 5.7 relaxed the rules concerning Self and associated type requirements a bit, allowing you to use the any keyword to tell the compiler you want to use an existential Foo instead of a concrete Foo to write
struct Bar {
var foo: any Foo
}
If you want a concrete Foo you could use some. The original way to do it though, which still works, is to make Bar explicitly generic
struct Bar<T: Foo> {
var foo: T
}
Update based on revised question code
The way you're using enums is... well, let's say it's out of the ordinary. There are two problems. The first is that you're returning types not values:
enum Foo {
case bar
case baz
// Will return a *value* of a type that conforms to Zot
var otherValues: some Zot
{
switch self {
case .bar:
return Bar // Bar is a *type* not a value
case .baz:
return Baz // Baz is a *type* not a value
}
}
}
I'll fix this is in a way that is almost certainly wrong for what you want to do, but allows moving forward to the other problem. We need to return values, so I'll just pick the first of the corresponding cases of Bar and Baz, and that will expose the other problem.
enum Foo {
case bar
case baz
var otherValues: some Zot
{
switch self {
case .bar: return Bar.thing3
case .baz: return Baz.thing1
}
}
}
The problem here is that some means that there will be one specific concrete type that conforms to Zot, so the compiler will be able to access its properties and methods directly rather than via its protocol witness table... it's basically a way to have the efficiency of having the calling code use the concrete types without having to tie to calling code to the concrete type at the source code level. otherValues, however, returns a value of either of two types, so the return type would have to be an existential type rather than a concrete one. You could do this if you return any Zot instead of some Zot.
Of course even using any, this version is wrong, because it doesn't take into account half of the cases of Bar and Baz. I assume that you want to be able to construct a Foo from a Bar or Baz while preserving its original value somehow, and I guess retrieve it later.
Before I present solutions, I want to mention that without knowing exactly what you are trying to accomplish, your code feels like it took a wrong design turn at some point. It would probably be better to rethink how you're doing what you want to do to see if there is a better way.
If I understand what your trying to do, I can think of at least three of ways, none of which requires CaseIterable, but maybe that's needed for other reasons.
Option 1
The first is to define Foo so that it explicitly contains all of the cases of Bar and Baz:
enum Foo: Zot
{
case thing1, thing2, thing3, thing4
init(_ value: Bar)
{
switch value
{
case .thing3: self = .thing3
case .thing4: self = .thing4
}
}
init(_ value: Baz)
{
switch value
{
case .thing1: self = .thing1
case .thing2: self = .thing2
}
}
var prop: Data
{
switch self
{
case .thing1: return Baz.thing1.prop
case .thing2: return Baz.thing2.prop
case .thing3: return Bar.thing3.prop
case .thing4: return Bar.thing4.prop
}
}
var bazValue: Baz?
{
switch self
{
case .thing1: return .thing1
case .thing2: return .thing2
default: return nil
}
}
var barValue: Bar?
{
switch self
{
case .thing3: return .thing3
case .thing4: return .thing4
default: return nil
}
}
}
This has the advantage of being straight-forward, but will require more maintenance if you add/remove cases from Bar or Baz - or even add a whole other enum that conforms to Zot.
Option 2
The second way is to define Foo so that it uses associated values:
enum Foo
{
case bar(value: Bar)
case baz(value: Baz)
init(_ value: Bar) { self = .bar(value: value) }
init(_ value: Baz) { self = .baz(value: value) }
}
I think this second case is cleaner, and you don't need otherValues because usage code can do:
switch foo
{
case let .bar(value: bar):
// do whatever with bar
case let .baz(value: baz):
// do whatever with baz
}
Still assuming second version of Foo, maybe an even cleaner way is:
extension Foo
{
func withZotValue<R>(_ code: (any Zot) throws -> R) rethrows -> R
{
switch self
{
case let .bar(value: value): return try code(value)
case let .baz(value: value): return try code(value)
}
}
}
That allows you to eliminate a lot of switch statements in usage code. To use it:
foo.withZotValue { zotValue in
// Do something with zotValue that the Zot protocol supports.
}
If you need this second version of Foo to conform to CaseIterable, Swift won't synthesize conformance for you because of the associated values, but you can write the conformance yourself.
extension Foo: CaseIterable
{
typealias AllCases = [Self]
static var allCases: AllCases {
[
Baz.allCases.map { .baz(value: $0) },
Bar.allCases.map { .bar(value: $0) },
].joined()
}
}
Option 3:
The last possible solution, which actually should probably be the first, if it applies, would be to define whatever you're trying to do that's common to both Bar and Baz in Zot. Whether that's a good idea or not depends on what you're trying to do, but let's assume it does make sense. For example, I notice that both Bar and Baz support a prop property, but the Zot protocol doesn't list prop. Why not? Is it unrelated to "Zotness"? If anything that conforms to Zot should have a prop property, then add it to the protocol:
protocol Zot: CaseIterable {
var prop: Data { get }
}
You still provide implementations of prop in Bar and Baz - that's kind of like overriding a base class method in subclasses.
Let's say the Data returned from prop is encoded JSON and you want be able to decode a Codable thing from a Zot. You can now do that without caring if its a Bar or a Baz (or any other new Zot-conforming type you might add later):
func decode<T: Codable>(_ type: T.Type, from src: some Zot) throws -> T {
return try JSONDecoder().decode(T.self, from: src.prop)
}

Equatable with enum - Swift

How can I validate equal with below source code?
enum ErrorAPI: Equatable, Error {
case CannotFetch(String)
}
func ==(lhs: ErrorAPI, rhs: ErrorAPI) -> Bool {
switch (lhs, rhs) {
case (.CannotFetch(let a), .CannotFetch(let b)) where a == b:
return true
default:
return false
}
}
The enum case CannotFetch has an associated value of type String. That means, when the enum case is set to CannotFetch, a specific String is associated with that case. Read through the official Swift documentation about Enumerations if you need to understand Associated Values.
The func ==() method is a so called Equivalence Operator. You can read more about it in the official Swift documentation about Advanced Operators.
When comparing two enums, lets call them enumOne and enumTwo, this function is implemented to be able to compare those two enums if both cases are CannotFetch(String).
Example:
let enumOne = ErrorAPI.CannotFetch("Hi")
let enumTwo = ErrorAPI.CannotFetch("Hello")
if enumOne != enumTwo {
print("They are not equal!")
} else {
print("They are equal")
}
The line case (.CannotFetch(let a), .CannotFetch(let b)) where a == b: works as follows:
This case is only proceeded if both, enumOne and enumTwo, are set to the case CannotFetch(String)
Take the associated value (=String) of the left hand sided enum, i.e. "Hi" and assign it to the new constant let a.
Take the associated value (=String) of the left hand sided enum, i.e. "Hello" and assign it to the new constant let b.
Additionally, Check if the values behind the constants a and b are equal, i.e. Check if the Strings Hi and Hello are equal.
If all this is true, execute the code block in the case, i.e. return true

Filter array of items by enum property with associated value

class MyClass: Decodable {
let title: String?
let type: MyClass.MyType?
enum MyType {
case article(data: [Article])
case link(data: [LinkTile])
case none
}
}
I would like to filter an array of MyClass items, so the filtered array won't contain instances with type .none
let filteredArray = array.filter { $0.type != .none } // this doesn't work
Unfortunately, you can't use == with enums with associated values. You need to use pattern matching, but that needs to be done in a switch or if statement.
So, that leads to something ugly like this:
let filteredArray = array.filter { if case .none = $0.type! { return false }; return true }
Notes:
You can't name your enum Type because it conflicts with the built-in Type. Change it to something like MyType.
It is terribly confusing to use none as a case in a custom enum because it gets confused (by the humans) with none in an optional. This is made worse by the fact that your type property is optional. Here I have force unwrapped it, but that is dangerous of course.
You could do:
if case .none? = $0.type
This would match the none case explicitly and treat nil as something you want to keep.
To filter out nil and .none, you could use the nil coalescing operator ??:
if case .none = ($0.type ?? .none)
I would suggest declaring type as MyClass.MyType instead of MyClass.MyType?.
I made you a simple example of how to use enum in your context with a filter function.
enum Foo {
case article(data: [Int])
case link(data: [String])
case `none`
static func myfilter(array: [Foo]) -> [Foo]{
var newArray:[Foo] = []
for element in array {
switch element {
case .article(let article):
newArray.append(.article(data: article))
case .link(let link):
newArray.append(.link(data: link))
case .none:
break
}
}
return newArray
}
}
let foo: [Foo] = [.article(data: [1,2,3]), .link(data: ["hello", "world"]), .none]
print(Foo.myfilter(array: foo))
I made a code which you can compile and test, you have to change the type for Foo, articleand link.
When you want to use an enum, you have to use switch case.
If you absolutely want to use the filter in swift you can, but you need to implement the protocol Sequence which is more complicated in this case.
For each case of your enum, you have to manage a case which use the concept of pattern matching. It is very powerful.

Swift: Index of an element in enum (CaseIterable)

The following code (compiles without errors) retrieves index of an element
in a particular CaseIterable enum type
public enum MyEnum : CaseIterable {
case ONE, TWO, THREE
public func ordinal() -> Int? {
return MyEnum.allCases.firstIndex(of: self)
}
}
I want to make a generic function to work with all CaseIterable enums.
If I try:
public extension CaseIterable {
public func ordinal() -> Int? {
return CaseIterable.allCases.firstIndex(of: self)
}
}
I get a compiler error "Member 'allCases' cannot be used on value of protocol type 'CaseIterable'; use a generic constraint instead" which is quite logical, as the actual enum type is unknown".
When I try CaseIterable<T>, I get another error, as CaseIterable is not declared as generic type.
Is there a way?
Couple of changes are necessary:
The return type needs to be Self.AllCases.Index? rather than Int?. In practice, these types will be equivalent, as seen below.
You also need to constrain any types to Equatable, because you need to be equatable in order to use firstIndex(of:). Again, in practice, any CaseIterable will usually be an enum without associated values, meaning it will be equatable automatically.
(Optional change) This function will never return nil, because you're finding one case in a CaseIterable. So you can remove the optionality on the return type (Self.AllCases.Index) and force unwrap.
Example:
public extension CaseIterable where Self: Equatable {
public func ordinal() -> Self.AllCases.Index {
return Self.allCases.firstIndex(of: self)!
}
}
enum Example: CaseIterable {
case x
case y
}
Example.y.ordinal() // 1
type(of: Example.y.ordinal()) // Int
Personally, I'd add that "Ordinal" usually means something different than what you're doing, and I'd recommend changing the function name to elementIndex() or something. But that's an aside.

How can I create a function in Swift that returns a Type which conforms to a protocol?

How can I create a function in Swift that returns a Type which conforms to a protocol?
Here is what I'm trying right now, but it obviously won't compile like this.
struct RoutingAction {
enum RoutingActionType{
case unknown(info: String)
case requestJoinGame(gameName: String)
case requestCreateGame(gameName: String)
case responseJoinGame
case responseCreateGame
}
// Any.Type is the type I want to return, but I want to specify that it will conform to MyProtocol
func targetType() throws -> Any.Type:MyProtocol {
switch self.actionType {
case .responseCreateGame:
return ResponseCreateGame.self
case .responseJoinGame:
return ResponseJoinGame.self
default:
throw RoutingError.unhandledRoutingAction(routingActionName:String(describing: self))
}
}
}
I would personally prefer returning an instance instead of a type but you can do it that way too. Here's one way to achieve it:
protocol MyProtocol:class
{
init()
}
class ResponseCreateGame:MyProtocol
{
required init() {}
}
class ResponseJoinGame:MyProtocol
{
required init() {}
}
enum RoutingActionType
{
case unknown(info: String),
requestJoinGame(gameName: String),
requestCreateGame(gameName: String),
responseJoinGame,
responseCreateGame
// Any.Type is the type I want to return, but I want to specify that it will conform to MyProtocol
var targetType : MyProtocol.Type
{
switch self
{
case .responseCreateGame:
return ResponseCreateGame.self as MyProtocol.Type
case .responseJoinGame:
return ResponseJoinGame.self as MyProtocol.Type
default:
return ResponseJoinGame.self as MyProtocol.Type
}
}
}
let join = RoutingActionType.responseJoinGame
let objectType = join.targetType
let object = objectType.init()
Note that your protocol will need to impose a required init() to allow creation of instances using the returned type.
Note2: I changed the structure a little to make my test easier but i'm sure you'll be able to adapt this sample to your needs.
Why do you not want to use simple:
func targetType() throws -> MyProtocol
?
EDIT:
I think you can't. Because if you return Type actually you return an instance of class Class and it can't conform your protocol. This runtime's feature was inherited from objective-c. You can see SwiftObject class.