目前我有多个具有相同签名但在调用 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 上,我在考虑协议(protocol),但如果协议(protocol)功能签名相同(即 drawPath)但参数不同,将如何做到这一点?
最佳答案
更清晰的版本(恕我直言)是一个包含路径开始和结束的结构,例如:
struct MyPath {
var start: JMapWaypoint
var end: JMapWaypoint
init(start: CGPoint, end: CGPoint)
{
//Your logic here
}
init(start: JMapWaypoint, end: JMapWaypoint)
{
self.start = start
self.end = end
}
init(start: JMapDestination, end: JMapDestination)
{
//Your logic here
}
}
然后你可以简单地用你想要的任何类型初始化这个对象,得到最终想要的类型并用这个对象实例绘制你的路径。
关于ios - 处理具有相同签名但参数不同的多个函数的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59534925/