简体   繁体   English

在 Swift 中访问 function 之外的变量

[英]Accessing a variable outside of a function in Swift

I want to call a variable (var view) that it is defined in another function (func mapView).我想调用一个在另一个 function (func mapView) 中定义的变量 (var view)。

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{
   if annotation is MapSeismometerAnnotation{
     if let annotation = annotation as? MapSeismometerAnnotation{
        var view: MKPinAnnotationView
        view = MKPinAnnotationView(annotation: annotation,reuseIdentifier:annotation.identifier)
        ...
        ...
}
@IBAction func pressPlay(_ sender: Any){
    //I want to call here the variable view
}

My class is:我的 class 是:

class MapViewController: UIViewController,MKMapViewDelegate,CLLocationManagerDelegate,SCSEarthquakesHandler,SCSPublicSeismometersHandler{

If I define the variable var view: MKPinAnnotationView under the class (outside the function), Xcode return me this error:如果我在 class(函数外)下定义变量var view: MKPinAnnotationView ,则 Xcode 会返回此错误:

Cannot override mutable property 'view' of type 'UIView?'无法覆盖“UIView”类型的可变属性“视图”? with covariant type 'MKPinAnnotationView'具有协变类型“MKPinAnnotationView”

How can I solve this?我该如何解决这个问题?

Set another name设置其他名称

var otherName: MKPinAnnotationView

view variable name conflicts with the vc's UIView property view变量名与vc的UIView属性冲突

View is not overridable because it is used by the UIViewController .视图不可覆盖,因为它由UIViewController使用。 Therefore you need to assign another name to the variable than view .因此,您需要为变量分配另一个名称而不是view

For example: var annotationView: MKAnnotationView is allowed.例如: var annotationView: MKAnnotationView是允许的。

view is already defined variable in UIViewController. Pick another name for your MKPinAnnotationView view 已经在 UIViewController 中定义了变量。为您的 MKPinAnnotationView 选择另一个名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM