字体扩展导致 Swift 实时预览崩溃Xcode 12.3

问题描述

我尝试为我的应用程序创建字体扩展,如下所示:

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)
    }

...

字体在模拟器中正确应用。但实时预览崩溃并在诊断窗口中出现以下错误

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

我做错了吗?可以修复吗?

解决方法

问题是 Font 已经有一个名为 caption 的静态属性。见its documentation。您不应该添加具有相同名称和类型的属性,那段代码根本不应该编译。

您需要重命名您的属性以解决歧义。

这同样适用于 titlelargeTitle,您不应该重新创建 Font 上已经存在的属性,您应该重命名它们。

与您的问题无关,但无需将这些属性添加为计算属性,它们可以是不可变的存储属性。

extension Font {
    // H1
    static var robotoLargeTitle = Font.custom("Roboto-Bold",size: 34)
    
    // H2
    static var robotoTitle = Font.custom("Roboto-Bold",size: 24)

    // Body 2 (input title)
    static let robotoCaption = Font.custom("Roboto-Regular",size: 14)
}