![](/img/trans.png)
[英]Objective C & Swift Interoperability causes error “Extensions may not contain stored properties”
[英]Extensions May not contain Stored properties
我可以在Swift with Extensions中實現它而不需要繼承嗎? 我得到此錯誤擴展可能不包含存儲的屬性
extension UIButton
{
@IBInspectable var borderWidth : CGFloat
{
didSet{
layer.borderWidth = borderWidth
}
}
}
您可以覆蓋setter / getter,使其不是存儲屬性,只是將set / get轉發給圖層。
extension UIButton {
@IBInspectable var borderWidth : CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
}
擴展無法添加存儲的屬性。 從文檔 (計算屬性部分):
注意
擴展可以添加新的計算屬性,但不能添加存儲的屬性,也不能將屬性觀察者添加到現有屬性。
如果您需要存儲屬性,則應創建子類,如下所示:
class CustomButton : UIButton
{
@IBInspectable var borderWidth : CGFloat
{
didSet{
layer.borderWidth = borderWidth
}
}
}
在Swift中,我正在導入一個用Objective-C編寫的靜態庫。 該庫中的協議具有方法和屬性。
@class Message;
@protocol LocalService
@property (readonly) int action;
- (Message *)getResponse:(Message *)request;
@end
嘗試使類符合該協議,提供以下消息:
1-)類型'ShowInitialViewLocalService'不符合協議'LocalService
2-)擴展名可能不包含存儲的屬性
下面提供的代碼修復了此問題:
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
}
}
我希望這會對某人有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.