首页 > 解决方案 > 如何避免对 2 个不同的类使用具有相同方法的两个扩展

问题描述

我想知道处理这种情况的最佳方法是什么。我有两个不同的视图控制器,它们都将使用来自 CLlocationManagerDelegate 的相同 didUpdateLocations 方法。我对它们都使用了扩展,并使它们符合 CLManagerDelegate。我想知道是否有另一种方法可以获得相同的结果。感谢所有的解释和回复。

第一个视图控制器


extension FirstViewController: CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[locations.count - 1]
        
        if location.horizontalAccuracy > 0 {
            locationManager.stopUpdatingLocation()
            print("\(location.coordinate.longitude), \(location.coordinate.latitude)")
            
        }
    }
}

第二个视图控制器

extension SecondViewController: CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[locations.count - 1]

        if location.horizontalAccuracy > 0 {
            locationManager.stopUpdatingLocation()
            print("\(location.coordinate.longitude), \(location.coordinate.latitude)")

        }
    }
}

我正在考虑下面的代码,但我不知道它是否比以前更好,并且对第二个视图控制器做同样的事情。

protocol localisation {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    
}

extension FirstViewController: localisation, CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[locations.count - 1]
        
        if location.horizontalAccuracy > 0 {
            locationManager.stopUpdatingLocation()
            print("\(location.coordinate.longitude), \(location.coordinate.latitude)")
        }
}

标签: iosswiftswift-protocolsswift-extensions

解决方案


我认为您的问题中有错字,因为代码SecondViewController用作FirstViewController名称。

如果我理解正确,您有两个视图控制器符合CLLocationManagerDelegate相同的代码,两者都重复。如果这就是您要解决的问题,我的建议是创建一个BaseViewController符合的CLLocationManagerDelegate,然后让您ViewControllers继承自BaseViewController.

class BaseViewController: UIViewController {
    //Common code here
}

extension BaseViewController: CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[locations.count - 1]

        if location.horizontalAccuracy > 0 {
            locationManager.stopUpdatingLocation()
            print("\(location.coordinate.longitude), \(location.coordinate.latitude)")

        }
    }
}

class FirstViewController: BaseViewController {
    //Your code here
}

class SecondViewController: BaseViewController {
    //Your code here
}

推荐阅读