扩展中的Swift自定义函数可用性

时间:2016-03-19 21:50:46

标签: swift

我想编写一个自定义函数,它应该在整个Swift应用程序中可用。当我使用扩展时,我需要扩展某个类。但是,如果我想编写一个应该在所有类中都可用的自定义函数呢?我该把它放在哪里?

这是我想要提供的功能:

extension MapViewController {
    func calculateDistanceToAED(latitude latitude: Double, longitude: Double) -> CLLocationDistance {
        let currentLocation: CLLocation = self.currentLocation
        let aedLocation: CLLocation = CLLocation(latitude: latitude, longitude: longitude)

        return currentLocation.distanceFromLocation(aedLocation)
    }
}

2 个答案:

答案 0 :(得分:2)

你想要的只是一个我相信的全球功能:

func calculateDistanceToAED(currentLocation:CLLocation, latitude: Double, longitude: Double) -> CLLocationDistance {
    let aedLocation: CLLocation = CLLocation(latitude: latitude, longitude: longitude)

    return currentLocation.distanceFromLocation(aedLocation)
}

答案 1 :(得分:-1)

你可以在Swift中使用全局函数 -

public struct MyGolobalFunctions {
    public static func calculateDistanceToAED(latitude latitude: Double, longitude: Double, currentLocation: CLLocation) -> CLLocationDistance {
        let aedLocation: CLLocation = CLLocation(latitude: latitude, longitude: longitude)
        return currentLocation.distanceFromLocation(aedLocation)
    }
}

致电GlobalFunction

  let currentLocation = CLLocation()
  MyGolobleFunctions.calculateDistanceToAED(latitude: 75.22, longitude: 73.22, currentLocation: currentLocation)