How to write this code in swift?

I have this code written in Objective c :

NSRect textRect = NSMakeRect(42, 35, 117, 55);
{
    NSString* textContent = @"Hello, World!";
    NSMutableParagraphStyle* textStyle = NSMutableParagraphStyle.defaultParagraphStyle.mutableCopy;
    textStyle.alignment = NSCenterTextAlignment;

    NSDictionary* textFontAttributes = @{NSFontAttributeName: [NSFont fontWithName: @"Helvetica" size: 12], NSForegroundColorAttributeName: NSColor.blackColor, NSParagraphStyleAttributeName: textStyle};

    [textContent drawInRect: NSOffsetRect(textRect, 0, 1 - (NSHeight(textRect) - NSHeight([textContent boundingRectWithSize: textRect.size options: NSStringDrawingUsesLineFragmentOrigin attributes: textFontAttributes])) / 2) withAttributes: textFontAttributes];
}

now, i want to write this code in swift . This is what i’ve got until now :

  • Search NSArray for value matching value
  • How to parse strings containing ampersands with NSXMLParser?
  • What is modern runtime?
  • CardIO cant get my card Info
  • this class is not key value coding-compliant for the key authView
  • Xcode crashes when I open a specific XIB file
  • let textRect = NSMakeRect(42, 35, 117, 55)
    let textTextContent = NSString(string: "Hello, World!")
    let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle
    textStyle.alignment = NSTextAlignment.CenterTextAlignment
    
    let textFontAttributes = [NSFontAttributeName: NSFont(name: "Helvetica", size: 12), NSForegroundColorAttributeName: NSColor.blackColor(), NSParagraphStyleAttributeName: textStyle]
    
    textTextContent.drawInRect(NSOffsetRect(textRect, 0, 1 - (NSHeight(textRect) - NSHeight(textTextContent.boundingRectWithSize(textRect.size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes))) / 2), withAttributes: textFontAttributes)
    

    this line is wrong :

       let textFontAttributes = [NSFontAttributeName: NSFont(name: "Helvetica", size: 12), NSForegroundColorAttributeName: NSColor.blackColor(), NSParagraphStyleAttributeName: textStyle]
    

    What is wrong with that line ?

    This is the error from the compiler :

    “Could not find an overload for “init” that accepts the supplied arguments”.

    Solutions Collect From Internet About “How to write this code in swift?”

    Swift’s type inference is failing you because the font you’re adding to the dictionary is an optional. NSFont(name:size:) returns an optional NSFont?, and you need an unwrapped version. To code defensively, you’ll want something like this:

    // get the font you want, or the label font if that's not available
    let font = NSFont(name: "Helvetica", size: 12) ?? NSFont.labelFontOfSize(12)
    
    // now this should work
    let textFontAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: NSColor.blackColor(), NSParagraphStyleAttributeName: textStyle]