#13 威力彩選號模擬器

Kai.W
彼得潘的 Swift iOS App 開發教室
3 min readMar 2, 2023

--

威力彩已連槓12期,彩金上看10億!!!

第一區設置 6 個 ImageView & Label,並將其各別拉 Outlet Collection
第二區設置 1 個 ImageView & Label
宣告一個空 arrary 用來放第一區六個隨機號碼

    var nums = [Int]()

@IBOutlet var ballImageViews: [UIImageView]!

@IBOutlet weak var specialBallImageView: UIImageView!

@IBOutlet weak var specialNumberLabel: UILabel!

@IBOutlet var numberLabels: [UILabel]!

第一區須在 1 至 38 間隨機取六組不重複號碼,透過 while 及 if 的判斷,可達到不重複隨機亂數的目的。
第二區僅取一個數字,可用最簡易的 Int.random 隨機亂數。

        //第二區號碼1到8間隨機亂數
specialNumberLabel.text = String(Int.random(in: 1...8))

//第一區號碼1到38間不重複隨機取六組
if nums.isEmpty == true { //透過 isEmpty 判斷 arrary 是否為空
while nums.count < 6 {
let randomNum = Int.random(in: 1...38)
if !nums.contains(randomNum) {
nums.insert(randomNum, at: 0)
}
}
} else if nums.isEmpty == false {
nums.removeAll() //因已達六組 while 循環停止,所以須將 arrary 所有資料移除後才可重新抓取六組新號碼
while nums.count < 6 {
let randomNum = Int.random(in: 1...38)
if !nums.contains(randomNum) {
nums.insert(randomNum, at: 0)
}
print(nums)
}
}

第一區隨機亂數後,透過 for in 迴圈,使 nums 的 6 筆資料各別顯示在 6 組Label 上。

//第一區號碼顯示數字
for i in numberLabels.indices {
numberLabels[i].text = String(nums[i])
}

--

--