首页 > 解决方案 > “Roll”类型的表达式模式与“Requests.RawValue”(又名“Roll”)类型的值不匹配

问题描述

我正在尝试创建一个返回结构的枚举,但我没有成功。我已经检查了一些与我的问题类似的问题,例如这里这里,它们并没有解决我遇到的问题。这是我的代码:

import Foundation

struct Roll {
    let times: String

    init(with times: String) {
        self.times = times
    }

}

fileprivate enum Requests {
    case poker
    case cards
    case slots
}

extension Requests: RawRepresentable {

    typealias RawValue = Roll

    init?(rawValue: RawValue) {
        switch rawValue {
        case Roll(with: "once"): self = .poker
        case Roll(with: "twice"): self = .cards
        case Roll(with: "a couple of times"): self = .slots
        default: return nil
        }
    }

    var rawValue: RawValue {
        switch self {
        case .poker: return Roll(with: "once")
        case .cards: return Roll(with: "twice")
        case .slots: return Roll(with: "a couple of times")
        }
    }
}

然后我想像这样使用它:Requests.cards.rawValue

标签: swiftstructenums

解决方案


那是因为您的结构Roll不符合Equatable协议,并且您正在尝试对其进行比较,只需将其更改为

struct Roll: Equatable {
    let times: String

    init(with times: String) {
        self.times = times
    }    
}

推荐阅读