我正在尝试从此转换以下Objective-C代码(源代码)
-(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'
在使用C API的文档交互使用&
的语法,所以我看不出有什么问题.我该如何解决这个错误?
ascent
并且descent
必须是变量才能作为in-out参数传递&
:
var ascent: CGFloat = 0 var descent: CGFloat = 0 let line: CTLineRef = CTLineCreateWithAttributedString(asp) let width = CGFloat(CTLineGetTypographicBounds(line, &ascent, &descent, nil))
返回时CTLineGetTypographicBounds()
,这些变量将设置为线的上升和下降.另请注意,此函数返回a Double
,因此您需要将其转换为CGFloat
.