英文:
Why does this computed property returns .white and .black?
问题
我完全是Swift和SwiftUI的新手,我正在按照官方的苹果教程进行学习(我现在正在这个部分:https://developer.apple.com/tutorials/app-dev-training/creating-a-card-view)。但是,我不理解这个语法:
import SwiftUI
enum Theme: String {
case bubblegum
case buttercup
case indigo
case lavender
case magenta
case navy
case orange
case oxblood
case periwinkle
case poppy
case purple
case seafoam
case sky
case tan
case teal
case yellow
var accentColor: Color {
switch self {
case .bubblegum, .buttercup, .lavender, .orange, .periwinkle, .poppy, .seafoam, .sky, .tan, .teal, .yellow: return .black
case .indigo, .magenta, .navy, .oxblood, .purple: return .white
}
}
var mainColor: Color {
Color(rawValue)
}
}
具体是return .white
和return .black
代码。为什么我们返回.white
和.black
?
它们看起来像枚举案例之类的东西,但var accentColor
说它将返回一个Color
类型,那么为什么我们不返回Color()
?而是只是.white
和.black
?这是SwiftUI特定的语法还是什么?
英文:
I'm completely new to Swift and SwiftUI and I'm following the official apple tutorial (I'm specifically in this section right now: https://developer.apple.com/tutorials/app-dev-training/creating-a-card-view). But, I do not understand this syntax:
import SwiftUI
enum Theme: String {
case bubblegum
case buttercup
case indigo
case lavender
case magenta
case navy
case orange
case oxblood
case periwinkle
case poppy
case purple
case seafoam
case sky
case tan
case teal
case yellow
var accentColor: Color {
switch self {
case .bubblegum, .buttercup, .lavender, .orange, .periwinkle, .poppy, .seafoam, .sky, .tan, .teal, .yellow: return .black
case .indigo, .magenta, .navy, .oxblood, .purple: return .white
}
}
var mainColor: Color {
Color(rawValue)
}
}
Specifically the return .white
and return .black
code. Why are we returning .white
and .black
?
They look like enum cases or something but the var accentColor
says it will return a Color
type, so why are we not returning Color()
? instead of just .white
and .black
? is this a SwiftUI specific syntax or something?
答案1
得分: 1
你实际上返回了静态属性 Color.black
和 Color.white
,但因为可以从返回类型推断出 Color
,所以只需要返回静态属性,而不是整个 Class.staticProperty
。
这是Swift中非常常见的模式,特别是在SwiftUI中。
英文:
[Copied from comments for completeness]
You are actually returning the static properties Color.black
and Color.white
but because the Color
can be inferred from the return type you only need to return the static property and not the whole Class.staticProperty
.
This is a very common pattern in Swift & especially SwiftUI.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论