我有一个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()
但是当我使用Index变量
时var Index: Int = 0
someObject!.labels[Index].textColor = UIColor.redColor()
xcode给出了一个错误:“无法找到成员'textColor'”并迫使我使用这样一个丑陋的代码:
(someObject!.labels[Index] as! UILabel).textColor = UIColor.redColor()
我正在对数组进行子类化,以便能够一次修改一组标签,例如labels.textColor = UIColor.redColor()
将修改数组中的每个标签。
我做错了什么,有没有办法避免这种丑陋的演员?
答案 0 :(得分:0)
好吧,我找到了答案。
问题在于Swift强类型系统。
重写grep
中的参数类型是无符号整数,调用程序过程中的objectAtIndex:
声明为整数。这就是为什么编译器正在考虑使用Swift数组的Index
过程和objectAtIndex:
参数,返回AnyObject类型。
Bridged声明如下所示:
Int
解决方案是使用func objectAtIndex(index: Int) -> AnyObject
重新声明objectAtIndexedSubscript:
而不是(NSInteger)index
OR
使用NSUInteger
转化:UInt()
我们也可以重载someObject!.labels[UInt(Index)].textColor = ...
属性(重载方括号运算符),但我们不能直接扩展LabelArray,因为subscript
会与obj-c subscript
方法冲突。
相反,我们可以声明一个协议,使用新方法扩展它,然后使用此协议扩展LabelArray:
objectAtIndexedSubscript