ObjectiveC mutableCopy如何在swift中工作

时间:2015-01-13 04:46:39

标签: ios objective-c swift core-plot

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

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中重写那行代码?

由于

1 个答案:

答案 0 :(得分:5)

问题是mutableCopy返回AnyObject。 AnyObject没有属性,因此您无法将其分配给它的属性。您需要将其强制转换为CPTMutableLineStyle。

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