这个计算属性为什么返回`.white`和`.black`?

huangapple go评论66阅读模式
英文:

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 .whitereturn .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.blackColor.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.

huangapple
  • 本文由 发表于 2023年6月18日 23:09:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定