Evaluate string width and return CGFloat (Swift, OSX)

This morning I’ve been working in a Swift function to detect the width of a given text and return a CGFloat. 

I’ve not found that many examples on the web for OSX, so here you have what I’ve done in all of its glory:

func evaluateStringWidth (textToEvaluate: String) -> CGFloat{

    letfont = NSFont.userFontOfSize(NSFont.systemFontSize())

    let attributes = NSDictionary(object: font!, forKey:NSFontAttributeName)

    let sizeOfText = textToEvaluate.sizeWithAttributes((attributes as! [String : AnyObject]))

    

    return sizeOfText.width

}

 

If you would have any suggestions on how to improve you know where to reach me, @MarcMasVi in Twitter.