iosswiftxcodeswiftuilive-preview

Font extension causes Swift live preview to crash (Xcode 12.3)


I've tried to create Font extension for my application like this:

import SwiftUI

extension Font {
    // H1
    static var largeTitle: Font {
        return Font.custom("Roboto-Bold", size: 34)
    }
    
    // H2
    static var title: Font {
        return Font.custom("Roboto-Bold", size: 24)
    }

    // Body 2 (input title)
    static var caption: Font {
        return Font.custom("Roboto-Regular", size: 14)
    }

...

The font is applying correctly in simulator. But live preview crashes with the following error in diagnostic window

ambiguous use of 'caption'

----------------------------------------

CompileDylibError: Failed to build LoginView.swift

Compiling failed: ambiguous use of 'caption'

/src/Login/LoginView.swift:31:31: error: ambiguous use of 'caption'
                        .font(Font.caption)
                              ^
/src/Font.swift:38:16: note: found this candidate
    static var caption: Font {
               ^
SwiftUI.Font:14:23: note: found this candidate
    public static var caption: Font

Am I doing something wrong? Is it possible to fix it?


Solution

  • The problem is that Font already has a static property called caption. See its documentation. You should not be able to add a property with the same name and type, that piece of code should not compile at all.

    You need to rename your property to resolve the ambiguity.

    The same applies to title and largeTitle, you shouldn't recreate properties that already exist on Font, you should rename all of them.

    Unrelated to your question, but no need to add those properties as computed properties, they can be immutable stored properties.

    extension Font {
        // H1
        static let robotoLargeTitle = Font.custom("Roboto-Bold", size: 34)
        
        // H2
        static let robotoTitle = Font.custom("Roboto-Bold", size: 24)
    
        // Body 2 (input title)
        static let robotoCaption = Font.custom("Roboto-Regular", size: 14)
    }