2024-11-13
let diceImages = [
UIImage(named: "DiceOne"),
UIImage(named: "DiceTwo"),
UIImage(named: "DiceThree"),
UIImage(named: "DiceFour"),
UIImage(named: "DiceFive"),
UIImage(named: "DiceSix")
]
注意,var
指可变的变量,let
指不变的变量,类似const
Int.random(in: 0...5)
范围:从0到5的随机整数
let diceImages = [
UIImage(named: "DiceOne")!, //!代表非空
UIImage(named: "DiceTwo")!,
UIImage(named: "DiceThree")!,
UIImage(named: "DiceFour")!,
UIImage(named: "DiceFive")!,
UIImage(named: "DiceSix")!
]
diceImageView1.image = diceImages.randomElement()
注意,因为数组元素是UIImage,系统会进行安全检查,认为这里可能是空值。即UIImage?
,加上一个Optional的条件。
加上感叹号意思是强制解包
,否则会报错。
告诉编译器, 我确定这里有值 ,这样,执行randomElement()才不会报错。
pritn(“Text \(2+3) Text”)
示例代码:
var a = 4
print("The result of 2 + 2 = \(2+2)")
print("The result of 2 + 2 = \(a)”)
格式:
func getMilk(){ //do stuff }
Key - value对
var dict = ["Brewery”: “a place where beer is made”]
var dict : [String: Int] = [“Angela”: 7712345678, “Philipp”: 7787654321]
switch hardness {
case "Soft":
print(5)
case "Medium":
print(7)
case "Hard":
print(12)
default:
print("Error")
}
func loveCalculator(){
let loveScore = Int.random(in: 0...1);
print(loveScore)
if(loveScore==1){
print("You love each other like Kanye loves Kanye")
} else{
print("You'll be forever alone.")
}
}
loveCalculator()
Int.random(in: 0...100)
Int.random(in: 0..<100)
let numbers = [1, 2, 3, 4, 5]
let slice = numbers[...3] // 包含索引 0 到 3 的元素 [1, 2, 3, 4]
Optional是用来处理不知道是否有值
存在的情况,防止程序因为空值崩溃。
//var playerUsername: String = nil //不能直接赋值nil
var playerUsername: String? = nil
playerUsername = "Jack"
var unwrappedP1Username = playerUsername!
print(playerUsername) //optional("Jack")
print(playerUsername!) //Jack
print(unwrappedP1Username) //Jack
playerUsername = nil
//print(playerUsername!) //报错,因为强制解包nil值
//怎么办?
/* 方法一:条件检查*/
if playerUsername != nil {
print(playerUsername!)
}
Optional
解决的是值为空时,会抛出错误中断程序的问题。
代表Optional类型,即可能有值,可能是nil:
var name: String? // name 可以是 String 或 nil
var petName: String? = "Buddy"
print(petName?.uppercased()) // 如果 petName 有值,输出大写;否则输出 nil
代表一定有值。但是若值为空时则抛出错误。
var name: String? = "孝中"
print(name!) // 输出:孝中
若值为nil时,程序崩溃。
var nickname: String? = nil
print(nickname!) // 运行时崩溃
//1.import
import UIKit
import AVFoundation
class ViewController: UIViewController {
//2.声明变量
var player: AVAudioPlayer!
var totalTime = 0
var secondsPassed = 0
var timer = Timer()
let eggTimes = [
"Soft": 3,
"Medium": 4,
"Hard": 7
]
//3.IB操作:IBOutlet和IBAction
@IBOutlet weak var doneLabel: UILabel!
@IBOutlet weak var progressBar: UIProgressView!
@IBAction func hardnessSelector(_ sender: UIButton) {
let hardness = sender.currentTitle!
timer.invalidate() //取消timer每次点击都会触发,现在仅触发1次
progressBar.progress = 0.0
secondsPassed = 0
doneLabel.text = hardness
totalTime = eggTimes[hardness]!
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
//4.function定义
@objc func updateTimer(){
if secondsPassed < totalTime {
secondsPassed += 1
progressBar.progress = Float(secondsPassed) / Float(totalTime)
print(Float(secondsPassed) / Float(totalTime))
} else {
timer.invalidate() // 停止定时器
doneLabel.text = "Done." // 更新标签文字
playSound()
}
}
// 播放声音
func playSound() {
let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
}