efr*_*dze 17 enums switch-statement swift
我已经为Instagram端点创建了一个枚举,其嵌套枚举类似于Moya.
enum Instagram {
    enum Media {
        case Popular
        case Shortcode(id: String)
        case Search(lat: Float, lng: Float, distance: Int)
    }
    enum Users {
        case User(id: String)
        case Feed
        case Recent(id: String)
    }
}
我想返回每个端点的路径.
extension Instagram: TargetType {
    var path: String {
        switch self {
        case .Media.Shortcode(let id):
            return "/media/shortcode"
        }
    }
}
但是我在上面的switch语句中遇到错误path.
枚举案例
Shortcode不是类型的成员
怎么修?
Jef*_*eff 37
由于一些原因,我正在添加更一般的答案.
enum Action {
    case fighter(F)
    case weapon(W)
    enum F {
        case attack(A)
        case defend(D)
        case hurt(H)
        enum A {
            case fail
            case success
        }
        enum D {
            case fail
            case success
        }
        enum H {
            case none
            case some
        }
    }
    enum W {
        case swing
        case back
    }
}
// Matches "3 deep"
let action = Action.fighter(.attack(.fail))
// Matches "1 deep" because more general case listed first.
let action2 = Action.weapon(.swing)
switch action {
case .fighter(.attack(.fail)):
    print("3 deep")
case .weapon:
    print("1 deep")
case .weapon(.swing):
    print("2 deep to case")
case .fighter(.attack):
    print("2 deep to another enum level")
default:
    print("WTF enum")
}
efr*_*dze 14
通过为嵌套枚举添加关联值,可以使用switch语句访问它.
enum Instagram {
    enum MediaEndpoint {
        case Search(lat: Float, lng: Float, distance: Int)
    }
    case Media(MediaEndpoint)
}
extension Instagram: TargetType {
    var path: String {
        switch self {
        case .Media(.Search):
            return "/media/search"
        }
    }
}
// Demo
protocol TargetType {
    var path: String { get }
}
class MoyaProvider<Target: TargetType> {
    func request(_ target: Target, completion: @escaping () -> ()) {}
}
let provider = MoyaProvider<Instagram>()
provider.request(.Media(.Search(lat: 0, lng: 0, distance: 0))) {}