【问题标题】:Swift Error - Type of expression is ambiguous without more contextSwift 错误 - 表达式类型不明确,没有更多上下文
【发布时间】:2021-04-01 07:59:38
【问题描述】:

我已经被这个问题困扰了一段时间,这个主题的类似问题并没有帮助我解决这个问题。

public extension NSString {
    func textRectWithFont(font: UIFont, width: CGFloat) -> CGRect {
        let contraint: CGSize = CGSize(width: width, height: 500000);
        var rect: CGRect

        var attributes: [NSAttributedString.Key: Any] = [
            .font: font
        ]

        rect = self.boundingRect(with: contraint,
                options: [.usesLineFragmentOrigin, .usesFontLeading],
                attributes: attributes,
                context: nil)

        return rect;
    }
}

当我在这一行使用那个方法时

let textHeight = NSString(textLabel?.text).textRectWithFont(font: textLabel?.font, width: textFrame?.size.width).size.height

它给了我错误“表达式类型不明确,没有更多上下文”

我做错了什么?

【问题讨论】:

  • 因为 textLabel 和 textFrame 是可选的,所以您使用可选参数并且编译器无法将调用与采用非可选参数的函数相匹配。首先尝试使用if let 解包值或允许函数的可选参数并在其中添加错误处理。
  • 这是有道理的。谢谢你的解释!

标签: ios swift xcode swift5


【解决方案1】:

您为您的函数提供可选参数,这确实是模棱两可的。 最好的解决方案是在像这样通过之前打开包装。

if let input_textLabel = textLabel?.font, let input_Width = textFrame?.size.width {
let textHeight = NSString(textLabel?.text).textRectWithFont(font: input_textLabel, width: input_Width).size.height
}

或者您也可以将可选参数带入函数,然后将其解包并处理它。

func textRectWithFont(font: UIFont?, width: CGFloat?) -> CGRect {
if let font  = font , let width = width. { your rest of function}

return value
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-01
    • 2022-11-18
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多