我正在尝试从此转换以下 Objective-C 代码( source )

-(CGRect) dimensionsForAttributedString: (NSAttributedString *) asp {

    CGFloat ascent = 0, descent = 0, width = 0;
    CTLineRef line = CTLineCreateWithAttributedString( (CFAttributedStringRef) asp);

    width = CTLineGetTypographicBounds( line, &ascent, &descent, NULL );

    // ...
}

进入 swift :
func dimensionsForAttributedString(asp: NSAttributedString) -> CGRect {

    let ascent: CGFloat = 0
    let descent: CGFloat = 0
    var width: CGFloat = 0
    let line: CTLineRef = CTLineCreateWithAttributedString(asp)

    width = CTLineGetTypographicBounds(line, &ascent, &descent, nil)

    // ...
}

但是我在这一行中收到了 &ascent 的错误:
width = CTLineGetTypographicBounds(line, &ascent, &descent, nil)



Xcode 建议我通过删除 & 来修复它。但是,当我这样做时,我收到错误



Interacting with C APIs documentation 使用 & 语法,所以我看不出问题是什么。我该如何解决这个错误?

最佳答案

ascentdescent 必须是变量才能被传递
作为 & 的输入输出参数:

var ascent: CGFloat = 0
var descent: CGFloat = 0
let line: CTLineRef = CTLineCreateWithAttributedString(asp)
let width = CGFloat(CTLineGetTypographicBounds(line, &ascent, &descent, nil))

CTLineGetTypographicBounds() 返回时,这些变量将被设置为
线路的上升和下降。还要注意这个函数返回Double ,因此您需要将其转换为 CGFloat

关于ios - Swift 错误 : '&' used with non-inout argument of type 'UnsafeMutablePointer' ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34238493/

10-14 20:35
查看更多