gpt4 book ai didi

ios - ObjectiveC mutableCopy 如何在 swift 中工作

转载 作者:搜寻专家 更新时间:2023-11-01 06:09:53 26 4
gpt4 key购买 nike

我是 Swift 和 iOS 开发的新手。最近我在尝试使用 Swift 编写一个使用 CorePlot(用 ObjectiveC 编写)的 iOS 应用程序。我试图在 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',顺便说一句,CPTLineStyle 类型在 ObjectiveC 中定义如下:

@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

任何人都可以告诉我我做错了什么吗?如何正确地快速重写这些代码行?

谢谢

最佳答案

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

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

关于ios - ObjectiveC mutableCopy 如何在 swift 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27915039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com