Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift 4: cannot subscript a value of type '[UIFontDesciptor.AttributeName : Any]' with an index of type 'String'

I am trying to init my custom font here, but it showing the error.

extension UIFont {
@objc convenience init(myCoder aDecoder: NSCoder) {
    if let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor {
        if let fontAttribute = fontDescriptor.fontAttributes["NSCTFontUIUsageAttribute"] as? String { // HERE SHOWING THE ERROR
            var fontName = ""
            switch fontAttribute {
            case "CTFontRegularUsage":
                fontName = appFontName
            case "CTFontEmphasizedUsage", "CTFontBoldUsage":
                fontName = appFontBoldName
            case "CTFontObliqueUsage":
                fontName = appFontItalicName
            default:
                fontName = appFontName
            }
            self.init(name: fontName, size: fontDescriptor.pointSize)!
        }
        else {
            self.init(myCoder: aDecoder)
        }
    }
    else {
        self.init(myCoder: aDecoder)
    }
}
...
}

This works perfectly for swift-3.2. But its not running with swift-4.0. Please help me. Thanks in advance.

like image 740
Litle Dev Avatar asked Jan 31 '26 05:01

Litle Dev


1 Answers

The type of the font attributes identifier has been changed from String to UIFontDescriptor.AttributeName.

The benefit is you can declare an extension

extension UIFontDescriptor.AttributeName {
    static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
}

Then you can write

if let fontAttribute = fontDescriptor.fontAttributes[.nsctFontUIUsage] as? String {

or without the extension

if let fontAttribute = fontDescriptor.fontAttributes[UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")] as? String {
like image 120
vadian Avatar answered Feb 02 '26 18:02

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!