从'CLLocation?'下载?到'CLLocation'只解开可选项;你的意思是使用'!'吗?

问题描述:

我试图在地图视图中显示用户当前的位置,但我的位置管理器功能从'CLLocation?'下载?到'CLLocation'只解开可选项;你的意思是使用'!'吗?

这里的第一线得到一个错误是我的代码

import UIKit 
import MapKit 

class FirstViewController: UIViewController, CLLocationManagerDelegate { 

@IBOutlet weak var mapkitView: MKMapView! 
var locationManager: CLLocationManager! 

override func viewDidLoad() 
{ 
    super.viewDidLoad() 

    if (CLLocationManager.locationServicesEnabled()) 
    { 
     locationManager = CLLocationManager() 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.requestAlwaysAuthorization() 
     locationManager.startUpdatingLocation() 
    } 
} 

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
{ 
    let location = locations.last as! CLLocation 

    let center = CLLocationCoordinate2DMake(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) 

    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) 

    self.mapkitView.setRegion(region, animated: true) 
} 
} 

错误我'越来越是'从'CLLocation'降级了吗?'以“CLLocation”只有解开自选;“!”吗?你的意思是使用

上线让位置= locations.last作为CLLocation

我才开始迅速的今天,所以请裸跟我 任何帮助!赞赏

+0

你不需要'作为!因为数组包含'CLLocation',所以你可以说'locations.last!'但请不要。使用条件解包'如果让位置= locations.last {'。但是,如果您阅读了“MKMapView”的文档,您会发现如果启用用户跟踪模式,它可以为您完成所有这些工作。 – Paulw11

+0

谢谢我现在没有收到任何错误,但是当它运行时,它只显示没有我的位置的地图,为什么? – Will

+0

您是否被提示允许位置访问?您是在模拟器还是真实设备上测试?如果模拟器,你是否从菜单模拟了一个位置?如果一个真实的设备,它有一个位置修复? – Paulw11

您是力铸造OptionalCLLocationCLLocation,这就是为什么斯威夫特建议简单地强制解开它:

let location = locations.last! 

这个版本(和你)无线如果locations为空,则会崩溃。

因此,我建议从来没有强迫任何东西展开,并使用guard代替:

guard let location = locations.last else { 
    return 
} 
+0

谢谢我现在没有得到任何错误,但是当它运行时,它只显示没有我的位置的地图,为什么? – Will

+0

这是另一个话题。按照@ Paulw11的建议(启用用户跟踪模式)和/或发布另一个问题。 – shallowThought