Joannes
Joannes

Reputation: 2940

allCase enum with parameter

How can I implement a protocol, or alternative solutions, to have in each case all those of the parameter. Something like League.teamA (.allCases)

import Cocoa

enum PlayerA: CaseIterable {
    case center
    case powerForward
    case smallForward
}

enum PlayerB: CaseIterable {
    case pointGuard
    case shootingGuard
}

protocol EnumProtocol {
    var description: String { get }
}

enum League: EnumProtocol {
    case teamA(PlayerA)
    case teamB(PlayerB)
}

extension League {
    var description: String {
        switch self {
        case let .teamA(player):
            switch player {
            case .center: return "Center"
            case .smallForward: return "Small Forward"
            case .powerForward: return "Power Forward"
            }
        case let .teamB(player):
            switch player {
            case .pointGuard: return "Point Guard"
            case .shootingGuard: return "Shooting Guard"
            }
        }
    }
}

League.teamA(.smallForward).description

//League.teamA(.allCases)
//League.teamB(.allCases)

Upvotes: 0

Views: 91

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

If you want to be able to pass both a single instance an an array of instances, the easiest solution is to declare the associated type as an array, since then you can pass an array with a single element in case you just want to pass a single instance, or you can pass allCases as well.

enum PlayerA: CaseIterable {
    case center
    case powerForward
    case smallForward
}

extension PlayerA: CustomStringConvertible {
    var description: String {
        switch self {
        case .center: return "Center"
        case .smallForward: return "Small Forward"
        case .powerForward: return "Power Forward"
        }
    }
}

enum PlayerB: CaseIterable {
    case pointGuard
    case shootingGuard
}

extension PlayerB: CustomStringConvertible {
    var description: String {
        switch self {
        case .pointGuard: return "Point Guard"
        case .shootingGuard: return "Shooting Guard"
        }
    }
}

protocol EnumProtocol {
    var description: String { get }
}

enum League: EnumProtocol {
    case teamA([PlayerA])
    case teamB([PlayerB])
}

extension League: CustomStringConvertible {
    var description: String {
        switch self {
        case let .teamA(players):
            return players.description
        case let .teamB(players):
            return players.description
        }
    }
}

League.teamA([.smallForward]).description
League.teamA(PlayerA.allCases)
League.teamB(PlayerB.allCases)

Upvotes: 1

Related Questions