且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用带有嵌套枚举的switch语句?

更新时间:2022-11-21 22:21:55

通过添加嵌套枚举的关联值,您可以使用switch语句访问它。

  enum Instagram {
enum MediaEndpoint {
case Search(lat:Float,lng:Float,distance:Int)
}
case Media(MediaEndpoint)
}

扩展Instagram:TargetType {
var path:String {
switch self {
case .Media(.Search):
return/ media /搜索
}
}
}

//演示

协议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))){}


I'm getting an error on the switch statement below for the path.

Enum case Search is not a member of type Instagram

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.Search(let _, let _, let _):
            return "/media/search"
        }
    }
}

I want to use a switch statement to return the path, however the cases are giving me errors. Is there any way this could work?

This is using advanced enums: https://github.com/terhechte/appventure-blog/blob/master/resources/posts/2015-10-17-advanced-practical-enum-examples.org#api-endpoints

By adding an associated value for the nested enum you can access it using a switch statement.

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))) {}