【问题标题】:Creating a swift struct that determines latitude and longitude using CoreLocation创建一个使用 CoreLocation 确定纬度和经度的快速结构
【发布时间】:2015-01-25 09:13:56
【问题描述】:

如何创建一个结构,其中包含使用CoreLocation 框架确定纬度和经度的方法?

【问题讨论】:

    标签: swift struct core-location


    【解决方案1】:

    为了使用CoreLocation框架,我们必须导入它:

    import CoreLocation
    

    创建一个struct...这是非常基本的 Swift 内容:

    struct CLStruct {
        func fetchCoordinates() -> (latitude: Double, longitude: Double) {
            // do CoreLocation stuff
    
        }
    }
    

    虽然可能更有用的是结构体、纬度和经度属性以及用于实例化这些结构体之一的方法:

    struct CLStruct {
        var latitude: Double
        var longitude: Double
    
        static func structForCurrentPosition() -> CLStruct {
            // do CLStuff to fetch latitude and longitude
            return self(latitude: 37.3318, longitude: -122.0296)
        }
    }
    

    我们可以这样使用它:

    let currentLocation = CLStruct.structForCurrentPosition()
    

    尽管如此,绝对值得一提的是CoreLocation 框架有一个名为CLLocation 的类,它已经具备了表示位置所需的一切。如果有的话,您可能只是想扩展或子类此对象以添加任何您需要的东西。

    【讨论】:

    • 非常感谢,但我是 Swift 的新手,我只是不知道如何将坐标放在纬度和对数变量上,你能告诉我一个如何做的例子吗?这样做?
    【解决方案2】:

    创建:

    struct Location {
        let latitude: Double
        let longitude: Double
    }
    

    实例化:

    let myLocation = Location(latitude: 37.331830, longitude: -122.005792)
    

    访问:

    print(myLocation.latitude) // 37.331830
    print(myLocation.longitude) // -122.005792
    

    【讨论】:

      【解决方案3】:

      您不应该重新创建轮子。 Apple 已经为此提供了一个结构,其中包含几个帮助方法和其他开发人员更广泛的熟悉度。

      CLLocationCoordinate2d

      https://developer.apple.com/documentation/corelocation/cllocationcoordinate2d

      【讨论】:

        猜你喜欢
        • 2023-03-22
        • 1970-01-01
        • 2015-01-08
        • 1970-01-01
        • 2015-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多