使用未解析的标识符 'boundingRect'

Use of unresolved identifier 'boundingRect'

我在使用以下代码时遇到了非常奇怪的问题。

extension String {
        func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
            let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
            let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)

            return ceil(boundingBox.height)
        }
}

它总是抛出以下编译器错误。

但是如果我使用 self.boundingRect 然后它编译成功并且 运行 应用程序但是在模拟器上启动应用程序后它会自动恢复到再次 boundingRect (删除 self ).

所以每次我需要添加self.来执行app.

因为boundingRectNSStringextension方法

extension NSString {

    @available(iOS 7.0, *)
    open func draw(with rect: CGRect, options: NSStringDrawingOptions = [], attributes: [NSAttributedStringKey : Any]? = nil, context: NSStringDrawingContext?)

    @available(iOS 7.0, *)
    open func boundingRect(with size: CGSize, options: NSStringDrawingOptions = [], attributes: [NSAttributedStringKey : Any]? = nil, context: NSStringDrawingContext?) -> CGRect
}

因此,如果您将 String 更改为 NSString extension,它将起作用

extension NSString {
    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        
        let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)
        
        return ceil(boundingBox.height)
    }
}

编辑来自 Swift 团队

https://bugs.swift.org/browse/SR-8408

The code in the compiler that says "NSString's members show up on String values" is specifically looking for member syntax, i.e. "foo.bar"—or in this case, "self.bar". It probably shouldn't have been written that way, but it was.

I think we'd still recommend being explicit here, even if it's ugly: (self as NSString).boundingRect(…) or let nsSelf = self as NSString; nsSelf.boundingRect(…).