我为 SwiftUI Font 编写了一个扩展,它引入了一些自定义字体。
extension Font {
static let solDisplay: Font = .custom("Gilroy", size: 36)
static let solHeadline: Font = .custom("Gilroy", size: 24)
}
现在由于某种原因,在构建过程中出现了以下错误:Cannot infer contextual base in reference to member 'heavy'
.有趣的是,此错误是其他人在执行 Pull Request 时发现的 - 我在本地没有注意到这些错误中的任何一个,但它似乎只发生在一些人身上。目前,我们团队中四分之二的人有其他人没有的错误。
struct AssetsDemoPage: View {
let fonts: [(String, Font)] = [
("Display - Heavy", .solDisplay.weight(.heavy)), // Error Happening here
("Display - Light", .solDisplay), // No error here!
("Headline - Heavy", .solHeadline.weight(.heavy)), // Error Happening here
("Headline - Light", .solHeadline), // No error here!
]
var body: some View {
NavigationView {
List {
Section(header: Text("Fonts")) {
ForEach(fonts, id: \.0) { name, font in
Text(name)
.font(font)
}
}
}
.navigationBarTitle(Text("Assets"), displayMode: .inline)
}
}
}
最佳答案
正如@jnpdx 所指的 Xcode 版本一样,Swift 版本可能不一样。在 Swift 5.4 中,SE-0287被实现。
该提议允许隐式成员链。您可以阅读有关链接的提案的更多信息,但这总结得很好:
This proposal suggests the expansion of implicit member syntax to more complex expressions than just a single static member or function. Specifically, implicit member syntax would be allowed to cover chains of member references.
代码如
Color.red.opacity(0.5)
现在可以简化为 .red.opacity(0.5)
,类似于您的示例。使用 Swift 5.4 需要 Xcode 12.5,所以让团队知道升级。
关于SwiftUI:无法推断引用成员的上下文基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67494326/