Swift super.init() - 属性 未在 super.init 调用时初始化

Swift super.init() - Property not initialized at super.init call

我在 super.init() 行收到错误 "Property 'self.directionsCompletionHandler' not initialized at super.init call"。在最近的 Xcode 更新 (11.4) 之前,这一切都很好。删除 init()super.init() 也会导致错误。我不太确定它要我做什么。

import UIKit
import CoreLocation
import MapKit

typealias DirectionsCompletionHandler = ((_ route:MKPolyline?, _ directionInformation:NSDictionary?, _ boundingRegion:MKMapRect?, _ error:String?)->())?

class MapManager: NSObject{

    fileprivate var directionsCompletionHandler:DirectionsCompletionHandler
    fileprivate let errorNoRoutesAvailable = "No routes available"// add more error handling

    override init(){
        super.init()
    }

    ...

替换

fileprivate var directionsCompletionHandler:DirectionsCompletionHandler

fileprivate var directionsCompletionHandler: DirectionsCompletionHandler = nil

我建议不要让 typealias 本身成为可选的,而只是一个简单的闭包:

typealias DirectionsCompletionHandler = (_ route: MKPolyline?, _ directionInformation: NSDictionary?, _ boundingRegion: MKMapRect?, _ error: String?) -> Void

这是为闭包定义类型别名时的标准约定。

然后定义您的 directionCompletionHandler 以使可选行为明确:

fileprivate var directionsCompletionHandler: DirectionsCompletionHandler?

而且编译器很容易判断出它不需要初始化。

或者,当然,如果需要,您可以显式地进行初始化:

fileprivate var directionsCompletionHandler: DirectionsCompletionHandler? = nil