【发布时间】:2020-04-19 10:35:25
【问题描述】:
目前我有多个具有相同签名但在调用 base 时执行不同操作的函数:
func drawPath(from: JMapDestination, to: JMapDestination) {
guard let fromWaypoint = navigationManager.getWaypointForDestination(destination: from),
let toWaypoint = navigationManager.getWaypointForDestination(destination: to) else {
return
}
drawPath(from: fromWaypoint, to: toWaypoint)
}
func drawPathFrom(_ from: CGPoint, to: JMapDestination) {
guard let fromWaypoint = getWaypointForPoint(point: from),
let toWaypoint = navigationManager.getWaypointForDestination(destination: to) else {
return
}
drawPath(from: fromWaypoint, to: toWaypoint)
}
func drawPath(from: CGPoint, to: JMapWaypoint) {
guard let fromWaypoint = getWaypointForPoint(point: from) else { return }
drawPath(from: fromWaypoint, to: to)
}
我决定使用 switch 语句创建一个枚举和一个主函数来处理不同的情况:
enum pathType {
case jMapWaypoint
case jMapDestination
case cgPoint
}
func drawPath(pathType: pathType, fromJMap: JMapWaypoint?, toJMap: JMapWaypoint?, fromJDestination: JMapDestination?, toJDestination: JMapDestination?, fromCGPoint: CGPoint?) {
switch pathType {
case .jMapWaypoint:
guard let mapController = viewModel?.mapController else {
return
}
let pathStyle = setPathStyle(style: JMapStyle.init())
if let from = fromJMap, let to = toJMap {
checkPathsBetweenWaypoints(mapController: mapController, pathStyle: pathStyle, from: from, to: to)
}
if let currentMap = mapController.currentMap {
mapController.zoomToPath(on: currentMap, withPadding: 100, withAnimationDuration: 1)
}
case .jMapDestination:
if let from = fromJDestination, let to = toJDestination {
guard let fromWaypoint = getWaypointForDestination(destination: from),
let toWaypoint = getWaypointForDestination(destination: to) else {
return
}
drawPath(pathType: .jMapWaypoint, fromJMap: fromWaypoint, toJMap: toWaypoint, fromJDestination: nil, toJDestination: nil, fromCGPoint: nil)
}
case .cgPoint:
if let from = fromCGPoint, let to = toJMap {
guard let fromWaypoint = getWaypointForPoint(point: from) else { return }
drawPath(pathType: .jMapWaypoint, fromJMap: fromWaypoint, toJMap: to, fromJDestination: nil, toJDestination: nil, fromCGPoint: nil)
}
}
}
带有 switch 语句的函数正在工作,但我想知道是否有更清洁、更有效的方法来执行此操作?仅供参考,所有功能都在同一个 viewController 上,我在考虑协议,但如果协议函数签名相同(即 drawPath)但参数不同,如何做到这一点?
【问题讨论】:
-
你有一个方法也接受
JMapWaypoint作为 from 和 to 参数吗? -
@Harsh 我有,因为功能很大,所以我没有在帖子中包含它
-
这里没有什么低效的地方,但这是一种糟糕的编码风格。根据类型向自己发送秘密消息是一个非常糟糕的主意。说出你的意思,是我的建议。
标签: ios swift switch-statement overloading