ios - 使用 @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
解决方案
推荐阅读
- angular - Angular Reactive Forms 使用服务中的 Observable 进行异步验证
- javascript - 使用 jquery/javascript 将带有下拉列表的 html 表导出到 CSV 文件
- python - 如何在 python 中加载在 matlab 中训练的深度学习模型
- node.js - 我们可以调整自适应卡片中按钮的大小吗?
- linux - 有没有办法让这个跨平台?
- git - 在这种情况下如何避免这么多合并冲突?
- java - 增加 Thorntail 中的计划任务超时时间
- java - 将 poll() 应用于 LinkedList 的 Java 错误
- python - 在python中为多个子类别绘制多个直方图
- azure - 获取有关 Azure 文件共享文件句柄的详细信息 - Get-AzStorageFileHandle