首页 > 解决方案 > 使用 @objc 从 Objective-C 访问 Swift 扩展中的可选变量

问题描述

我正在尝试使用 @objc 前缀从 Objective-C 类访问 NSString 的 Swift 扩展,但无法访问可选的。

现在 Swift 4.2 在从 Objective-C 调用的变量或函数之前需要 @objc 才能访问扩展,我必须添加 @objc 扩展。

虽然这适用于非可选项 - 我在我的项目中广泛使用它,但将 @objc 添加到以下扩展名会产生错误:

我不确定,但我认为这可能是因为 CLLocationCoordinate 是可选的。

任何人都可以看到代码有什么问题吗?感谢您的任何建议。

If I don't put @objc in following, I can't access it from Objective-C. Error is: Property 'asLocationCoord' not found on object of type 'NSString
If I do put it in, Swift compiler complains 'Property cannot be marked @objc because its type cannot be represented in Objective-C'


public extension NSString {
  @objc public var asLocationCoord: CLLocationCoordinate2D? {
    var mylocation: CLLocationCoordinate2D? = nil
        let geoCoder = CLGeocoder()
        geoCoder.geocodeAddressString(self as String) { (placemarks, error) in
            guard
                let placemarks = placemarks,
                let firstlocation = placemarks.first?.location?.coordinate
                else {
                    // handle no location found
                    return
                    }
            mylocation = firstlocation
        }
        return mylocation
        }//end var
}//end extension

标签: iosobjective-cswiftoptionalswift-extensions

解决方案


推荐阅读