【发布时间】:2017-05-24 06:31:30
【问题描述】:
我试图在 Swift 中使用一个函数的值来设置一个变量/常量,该函数在应用程序打开时查找用户的当前位置。当我取消注释打印函数时,它成功打印了坐标,但我无法访问函数之外的值。
我目前将此作为我的代码的一部分,它在 MainVC.swift 文件中作为 MainVC 类的一部分:
import UIKit
import MapKit
import CoreLocation
class MainVC: UIViewController, CLLocationManagerDelegate {
//Map
@IBOutlet weak var map: MKMapView!
let manager = CLLocationManager()
let coordinates = locationManager()
//I've also tried using let coordinates = currentCoords
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) -> String {
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
map.setRegion(region, animated: true)
lat = String(myLocation.latitude)
long = String(myLocation.longitude)
let currentCoords:String = "\(lat);\(long)"
//print(currentCoords)
self.map.showsUserLocation = true
return currentCoords
}
}
但是我遇到了这个错误:
“不能在属性初始化器中使用实例成员 'locationManager';属性初始化器在 'self' 可用之前运行”。
当我更改代码并使用时
let coordinates = currentCoords
我得到另一个错误显示:
“使用未解析的标识符‘currentCoords’”
我也尝试过使用lazy var 和lazy let。
【问题讨论】:
-
您需要为您发布的代码提供更多上下文。
-
你的错误不是来自初始化程序吗?将代码从 initializer 粘贴到出现错误的位置。
-
@rmaddy 对此感到抱歉,最初发布时忘记添加它,更新了主帖子并提供了一些上下文希望对您有所帮助。
-
发布包含您发布的代码的整个函数。请注意,“坐标”对于位置管理器的实例来说是一个可怕的名称。
-
@DuncanC 这是整个功能,我在应用程序中使用了不同的标识符,我只是在发布时更改了它以提高可读性。我在原始帖子中添加了更多信息,希望对您有所帮助。
标签: ios swift swift3 core-location