[英]Extensions May not contain Stored properties
Can I implement this in Swift with Extensions without the need to inheritance?. 我可以在Swift with Extensions中实现它而不需要继承吗? I get this error Extensions May not contain Stored properties
我得到此错误扩展可能不包含存储的属性
extension UIButton
{
@IBInspectable var borderWidth : CGFloat
{
didSet{
layer.borderWidth = borderWidth
}
}
}
You can override the setter/getter so that it isn't a stored property and just forwards the set/get to the layer. 您可以覆盖setter / getter,使其不是存储属性,只是将set / get转发给图层。
extension UIButton {
@IBInspectable var borderWidth : CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
}
Extensions cannot add stored properties. 扩展无法添加存储的属性。 From the docs (Computed Properties section):
从文档 (计算属性部分):
Note
注意
Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.
扩展可以添加新的计算属性,但不能添加存储的属性,也不能将属性观察者添加到现有属性。
If you have a need for stored properties, you should create a subclass, like so: 如果您需要存储属性,则应创建子类,如下所示:
class CustomButton : UIButton
{
@IBInspectable var borderWidth : CGFloat
{
didSet{
layer.borderWidth = borderWidth
}
}
}
In Swift, I'm importing a static library written in Objective-C. 在Swift中,我正在导入一个用Objective-C编写的静态库。 The protocol below, in that library, has a method and a property.
该库中的协议具有方法和属性。
@class Message;
@protocol LocalService
@property (readonly) int action;
- (Message *)getResponse:(Message *)request;
@end
Trying to have a class conform to that protocol, delivers the messages below: 尝试使类符合该协议,提供以下消息:
1-) Type 'ShowInitialViewLocalService' does not conform to protocol 'LocalService
1-)类型'ShowInitialViewLocalService'不符合协议'LocalService
2-) Extensions may not contain stored properties
2-)扩展名可能不包含存储的属性
The code provided below, fixes this issue: 下面提供的代码修复了此问题:
import UIKit
class ShowInitialViewLocalService: NSObject{
}
extension ShowInitialViewLocalService : LocalService {
var action: Int32 {
get { return View.InitialView.rawValue }
}
func getResponse(_ request: Message) -> Message {
let response = Response(source: request.target, target: request.source, relatedView: View.InitialView.rawValue, action: request.action, data: request.data)
return response
}
}
I hope this will help someone. 我希望这会对某人有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.