如何避免对 2 个不同的 类 使用相同方法的两个扩展

How to avoid using two extensions with the same method for 2 different classes

我想知道处理这种情况的最佳方法是什么。我有两个不同的视图控制器,它们都将使用来自 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)")
        }
}

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

如果我没理解错的话,您有两个符合 CLLocationManagerDelegate 的视图控制器,并且为两者重复了相同的代码。如果这是您要解决的问题,我的建议是创建一个符合 CLLocationManagerDelegateBaseViewController,然后让您的 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
}