I was learning Swift UI and I faced an issue regarding colors. If I use background(.red) then my output of the button looks like this (Line number 39).

But the weird part is that if I use background(Color.red) then my output of the button looks like this (Line number 39).
Now my questions are
- Why two different outputs?
- What’s the actual difference between
Color.redand.red? - When to use
Color.redand.red?
Full code is given below
Using .red code
//
// ContentView.swift
// Dicey-SwiftUI
//
// Created by Moh. Absar Rahman on 26/11/21.
//
import SwiftUI
struct ContentView: View {
@State var leftDiceNumber = 1
@State var rightDiceNumber = 1
var body: some View {
ZStack {
Image("background")
.resizable()
.edgesIgnoringSafeArea(.all)
VStack {
Image("diceeLogo")
Spacer()
HStack {
DiceView(n: leftDiceNumber)
DiceView(n: rightDiceNumber)
}
.padding(.horizontal)
Spacer()
Button(action: {
leftDiceNumber = 2
rightDiceNumber = 2
}) {
Text("Roll")
.font(.system(size: 50))
.fontWeight(.heavy)
.foregroundColor(.white)
.padding(.horizontal)
}
.background(.red)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct DiceView: View {
let n: Int
var body: some View {
Image("dice\(n)")
.resizable()
.aspectRatio(1, contentMode: .fit)
.padding()
}
}
Using Color.red code
//
// ContentView.swift
// Dicey-SwiftUI
//
// Created by Moh. Absar Rahman on 26/11/21.
//
import SwiftUI
struct ContentView: View {
@State var leftDiceNumber = 1
@State var rightDiceNumber = 1
var body: some View {
ZStack {
Image("background")
.resizable()
.edgesIgnoringSafeArea(.all)
VStack {
Image("diceeLogo")
Spacer()
HStack {
DiceView(n: leftDiceNumber)
DiceView(n: rightDiceNumber)
}
.padding(.horizontal)
Spacer()
Button(action: {
leftDiceNumber = 2
rightDiceNumber = 2
}) {
Text("Roll")
.font(.system(size: 50))
.fontWeight(.heavy)
.foregroundColor(.white)
.padding(.horizontal)
}
.background(Color.red)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct DiceView: View {
let n: Int
var body: some View {
Image("dice\(n)")
.resizable()
.aspectRatio(1, contentMode: .fit)
.padding()
}
}
Note: Please do not laugh at me. I am still a beginner who is trying his best to learn SwiftUI
>Solution :
This is called implicit member expression. in situations where the type can be inferred from other information, like return types, the actual type name can be omitted.
in
.background(Color.red)
it cannot be omitted, as the parameter isnt typed Color, but some View. it wouldn’t know where to look for red if type was missing.
The difference that you see in the preview are not explainable by the code, there-for I suggest you execute it on the device, as it might be some unwanted artefact. I see a lot of those in the current Xcode version.
