ObjectiveC mutableCopy 如何在 swift 中工作

How ObjectiveC mutableCopy work in swift

我是 Swift 和 iOS 开发的新手。最近我试图使用 Swift 编写一个使用 CorePlot(用 ObjectiveC 编写)的 iOS 应用程序。我试图在 Swift 中重写一个 CorePlot iOS 示例代码(在 http://www.raywenderlich.com/13271/how-to-draw-graphs-with-core-plot-part-2 中找到)。示例目标C中有这样一行:

CPTMutableLineStyle *aaplLineStyle = [aaplPlot.dataLineStyle mutableCopy];
aaplLineStyle.lineWidth = 2.5;

我试过这样重写:

var lineStyle = aaplPlot.dataLineStyle.mutableCopy();
lineStyle.lineColor = aaplColor;

问题是我的 Swift 版本的代码出现编译错误

"cannot assign to 'lineColor' in 'lineStyle'". 

我还收到一条警告说

"variable lineStyle inferred to have type 'AnyObject', which may be unexpected"

'applePlot',顺便说一句,在 ObjectiveC 中是这样定义的 CPTLineStyle 类型:

@interface CPTLineStyle : NSObject<NSCoding, NSCopying, NSMutableCopying>

@property (nonatomic, readonly) CGLineCap lineCap;
@property (nonatomic, readonly) CGLineJoin lineJoin;
@property (nonatomic, readonly) CGFloat miterLimit;
@property (nonatomic, readonly) CGFloat lineWidth;
@property (nonatomic, readonly) NSArray *dashPattern;
@property (nonatomic, readonly) CGFloat patternPhase;
@property (nonatomic, readonly) CPTColor *lineColor;
@property (nonatomic, readonly) CPTFill *lineFill;
@property (nonatomic, readonly) CPTGradient *lineGradient;
@property (nonatomic, readonly, getter = isOpaque) BOOL opaque;

/// @name Factory Methods
/// @{
+(instancetype)lineStyle;
/// @}

/// @name Drawing
/// @{
-(void)setLineStyleInContext:(CGContextRef)context;
-(void)strokePathInContext:(CGContextRef)context;
-(void)strokeRect:(CGRect)rect inContext:(CGContextRef)context;
/// @}

@end

任何人都可以告诉我我做错了什么吗?如何正确重写 swift 中的那几行代码?

谢谢

问题是 mutableCopy returns 一个 AnyObject。 AnyObject 没有属性,因此您不能分配给它的 属性。您需要将其转换为 CPTMutableLineStyle。

var lineStyle = aaplPlot.dataLineStyle.mutableCopy() as CPTMutableLineStyle
lineStyle.lineColor = aaplColor;