如何使用带有嵌套枚举的switch语句? [英] How do you use a switch statement with a nested enum?
本文介绍了如何使用带有嵌套枚举的switch语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
枚举情况
搜索
不是Instagram的成员
enum Instagram {
/ pre>
enum Media {
case Popular
case Shortcode(id:String)
case搜索(lat:Float,lng:Float,distance:Int)
}
枚举用户{
case User(id:String)
case Feed
case最近(id:String)
}
}
扩展Instagram:TargetType {
var path:String {
switch self {
case .Media。搜索(let _,let _,let _):
return/ media / search
}
}
}
我想使用switch语句来返回路径,但是这种情况给我的错误。
有没有办法可以工作?
解决方案通过添加嵌套枚举的关联值,您可以使用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
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))) {}
这篇关于如何使用带有嵌套枚举的switch语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文