NSString boundingRectWithSize:options:attributes:context: not usable in Swift?

The initializers expect named arguments.

extension UIFont {
    func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
        return NSString(string: string).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
            options: NSStringDrawingOptions.UsesLineFragmentOrigin,
            attributes: [NSFontAttributeName: self],
            context: nil).size
    }
}

Note: Strings can be cast to NSStrings.

extension UIFont {
    func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
        return (string as NSString).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
            options: NSStringDrawingOptions.UsesLineFragmentOrigin,
            attributes: [NSFontAttributeName: self],
            context: nil).size
    }
}

or

extension UIFont {
    func sizeOfString (string: NSString, constrainedToWidth width: Double) -> CGSize {
        return string.boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
            options: NSStringDrawingOptions.UsesLineFragmentOrigin,
            attributes: [NSFontAttributeName: self],
            context: nil).size
    }
}

--

UPDATED

For Swift 4 syntax

extension UIFont {
    func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
        return NSString(string: string).boundingRect(
            with: CGSize(width: width, height: .greatestFiniteMagnitude),
            options: .usesLineFragmentOrigin,
            attributes: [.font: self],
            context: nil).size
    }
}

Alternatively you could cast it into an NSString

if let ns_str:NSString = str as NSString? {

   let sizeOfString = ns_str.boundingRectWithSize(
                                 CGSizeMake(self.titleLabel.frame.size.width, CGFloat.infinity), 
                                 options: NSStringDrawingOptions.UsesLineFragmentOrigin, 
                                 attributes: [NSFontAttributeName: lbl.font], 
                                 context: nil).size
}

Latest Swift

func sizeOfString (string: String, constrainedToHeight height: Double) -> CGSize {
    return NSString(string: string).boundingRect(with: CGSize(width: DBL_MAX, height: height),
                                                 options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                                 attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 20)],
                                                 context: nil).size
}

Tags:

Swift