簡體   English   中英

在Swift中具有固定返回類型的子類objc數組中需要轉換

[英]Cast needed in subclassed objc array with fixed return type in Swift

我有一個NSArray的子​​類,標簽數組:

@interface LabelArray : NSArray
  - (UILabel*)objectAtIndex:(NSUInteger)index;
  - (UILabel*)objectAtIndexedSubscript:(NSUInteger)index;
@end

@interface ViewController : UIViewController
  @property (nonatomic,readonly) LabelArray* labels;
@end

當我嘗試從帶有0索引的Swift代碼訪問它時,一切正常:

someObject!.labels[0].textColor = UIColor.redColor()

但是當我使用索引變量

var Index: Int = 0
someObject!.labels[Index].textColor = UIColor.redColor()

xcode給出一個錯誤:“找不到成員'textColor'”,並迫使我使用像這樣的丑陋代碼:

(someObject!.labels[Index] as! UILabel).textColor = UIColor.redColor()

我對數組進行了子類化,以便能夠一次修改一組標簽,例如labels.textColor = UIColor.redColor()將修改數組中的每個標簽。

我在做什么錯,有辦法避免這種丑陋的演員嗎?

好吧,我找到了答案。

問題出在Swift強類型系統中。

覆蓋的objectAtIndex:的參數類型為Unsigned Integer,並且調用程序中的Index被聲明為Integer。 這就是為什么編譯器考慮使用Swift Array的objectAtIndex:過程,該過程帶有Int參數,返回AnyObject類型。

橋接聲明如下所示: func objectAtIndex(index: Int) -> AnyObject

該解決方案是重新聲明objectAtIndexedSubscript:(NSInteger)index ,而不是NSUInteger

或使用UInt()轉換: someObject!.labels[UInt(Index)].textColor = ...

我們還可以重載subscript屬性(重載方括號運算符),但是我們不能直接擴展LabelArray,因為subscript將與obj-c objectAtIndexedSubscript方法沖突。

相反,我們可以聲明一個協議,使用新方法對其進行擴展,然后使用該協議對LabelArray進行擴展:

protocol LabelArrayProtocol { }

extension LabelArrayProtocol {
  subscript(index: Int) -> UILabel {
    return (self as! NSArray).objectAtIndex(index) as! UILabel
  }
}

extension LabelArray: LabelArrayProtocol { }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM