Skip to content

Instantly share code, notes, and snippets.

View PeterPanSwift's full-sized avatar

潘世穎 PeterPanSwift

View GitHub Profile
@PeterPanSwift
PeterPanSwift / ContentView.swift
Created May 24, 2025 15:56
SwiftUI Dice Rolling App - ContentView with three dice and sum calculation
//
// ContentView.swift
// Demo
//
// Created by SHIH-YING PAN on 2025/5/24.
//
import SwiftUI
struct ContentView: View {

當然可以!我們可以用《小王子》B612 星球的故事,來幫助初學者理解 Swift 的 Optional 概念——這個在 Swift 中很重要,但剛開始學時常讓人困惑的語法。


🪐 B612 星球與 Optional 的故事

你是否記得《小王子》中,小王子住在一個小小的星球——B612?在他的星球上,什麼都有可能存在:有時只有一朵玫瑰花,有時卻什麼也沒有。有一天,小王子想知道自己的星球上有沒有玫瑰花。

在 Swift 語言裡,Optional 就像這個問題:

import SwiftUI
struct ContentView: View {
@State private var guessNumberText = ""
@State private var showResult = false
@State private var result = ""
@State private var guessWrongCount = 0
@State private var answer = Int.random(in: 1...100)
@State private var upperBound = 100
@State private var lowerBound = 1
import SwiftUI
struct ContentView: View {
@State private var guessNumberText = ""
@State private var showResult = false
@State private var result = ""
@State private var guessWrongCount = 0
@State private var answer = Int.random(in: 1...100)
@State private var upperBound = 100
import SwiftUI
struct ContentView: View {
@State private var questions = [
Question(text: "吸血鬼最害怕什麼物品?", answer: "大蒜和十字架"),
Question(text: "德古拉伯爵是哪個國家的吸血鬼?", answer: "羅馬尼亞"),
Question(text: "吸血鬼在傳說中無法在什麼物品中看到自己?", answer: "鏡子"),
]
@State private var currentQuestionIndex = 0
@State private var showAnswer = false
import SwiftUI
struct ContentView: View {
@State private var questions = [
Question(text: "吸血鬼最害怕什麼物品?", answer: "大蒜和十字架"),
Question(text: "德古拉伯爵是哪個國家的吸血鬼?", answer: "羅馬尼亞"),
Question(text: "吸血鬼在傳說中無法在什麼物品中看到自己?", answer: "鏡子"),
]
@State private var currentQuestionIndex = 0
import SwiftUI
struct ContentView: View {
@State private var questions = [
Question(text: "吸血鬼最害怕什麼物品?", answer: "大蒜和十字架"),
Question(text: "德古拉伯爵是哪個國家的吸血鬼?", answer: "羅馬尼亞"),
Question(text: "吸血鬼在傳說中無法在什麼物品中看到自己?", answer: "鏡子"),
]
@State private var currentQuestionIndex = 0
@State private var showAnswer = false
import SwiftUI
struct ContentView: View {
let questions = [
Question(text: "吸血鬼最害怕什麼物品?", answer: "大蒜和十字架"),
Question(text: "德古拉伯爵是哪個國家的吸血鬼?", answer: "羅馬尼亞"),
Question(text: "吸血鬼在傳說中無法在什麼物品中看到自己?", answer: "鏡子"),
]
@State private var currentQuestionIndex = 0
@State private var showAnswer = false
import SwiftUI
struct ContentView: View {
let questions = [
Question(text: "吸血鬼最害怕什麼物品?", answer: "大蒜和十字架"),
Question(text: "德古拉伯爵是哪個國家的吸血鬼?", answer: "羅馬尼亞"),
Question(text: "吸血鬼在傳說中無法在什麼物品中看到自己?", answer: "鏡子"),
]
@State private var currentQuestionIndex = 0
//
// ContentView.swift
// Demo
//
// Created by SHIH-YING PAN on 2025/4/26.
//
import SwiftUI
// 問題結構