【问题标题】:Swift error: '&' used with non-inout argument of type 'UnsafeMutablePointer'Swift 错误:“&”与“UnsafeMutablePointer”类型的非输入参数一起使用
【发布时间】:2016-03-18 05:58:42
【问题描述】:

我正在尝试从中转换以下 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 );

    // ...
}

进入斯威夫特:

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)

'&' 与 'UnsafeMutablePointer' 类型的非 inout 参数一起使用

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

无法将“CGFloat”类型的值转换为预期的参数类型“UnsafeMutablePointer”

Interacting with C APIs documentation 使用& 语法,所以我看不出问题出在哪里。如何解决此错误?

【问题讨论】:

  • CTLineGetTypographicBounds 函数需要一个UnsafeMutablePointer<CGFloat>,因此例如使用withUnsafeMutablePointer,您应该创建一个UnsafeMutablePointer<CGFloat>,并将其用作输入参数。
  • 我的问题是我没有使用 var 关键字将它们声明为变量。

标签: ios objective-c swift unsafe-pointers


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多