Swift에서 앱이 열려있는 동안 사용자의 현재 위치를 찾는 함수의 값을 사용하여 변수/상수를 설정하려고합니다. 인쇄 기능의 주석을 제거하면 좌표가 성공적으로 인쇄되지만 함수 외부의 값에는 액세스 할 수 없습니다.별도의 변수/상수로 CLLocationManager에서 좌표를 가져올 수 없습니다.
나는 현재 MainVC 클래스의 일부로서 MainVC.swift 파일에 내 코드의 일부로서이 있습니다
:이 오류에 직면하고 있습니다 그러나"Cannot use instance member 'locationManager' within property initializer; property initializers run before 'self' is available".
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
}
}
내가 코드를 변경하고
let coordinates = currentCoords
를 사용하는 경우
나는 다른 오류 보여주는를 얻을 :
"Use of unresolved identifier 'currentCoords'"
저는 게으른 var 및 lazy let을 사용해 보았습니다.
게시 한 코드의 컨텍스트를 조금 더 제공해야합니다. – rmaddy
이니셜 라이저에 오류가 있습니까? ** 이니셜 라이저 **에서 오류를 가져 오는 코드를 붙여 넣으십시오. – Honey
@rmaddy 그 점에 대해 사과드립니다. 원래 게시 할 때 추가하는 것을 잊어 버렸습니다. 메인 포스트를 도움이되는 정보로 업데이트했습니다. – Miles