Episode 108— 單字App

Shien
彼得潘的 Swift iOS / Flutter App 開發教室
10 min readSep 15, 2022

下載單字

https://www.dropbox.com/s/ah8of5mgtvo0lbi/alphabet.zip?dl=0

以上網址有提供字母單字表,下載整份資料夾後,直接拖曳資料夾進 Xcode Bundle 資料夾裡

從剛剛的資料夾裡可以看到每個字母所對應的單字資料

取得單字資料

取得所有單字

class VocabularyList {
var allVoc = [String]()
let letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "Y", "Z"]
func fetchAllVoc(with letter: String) {
let path = Bundle.main.url(forResource: letter, withExtension: "txt")

let content = try? String(data: Data(contentsOf: path!), encoding: .utf16)
if let content = content {
allVoc = content.components(separatedBy: "\n")
} else {
print("no voc content")
}
}
}

新增一個 Vocabulary List 類別來管理單字的處理。

var allVoc = [String]()

用 [String] 儲存所有單字的資料

let path = Bundle.main.url(forResource: letter, withExtension: "txt")

因為資料是存在 Bundle 資料夾裡,所以要從 Bundle.main 取得資料來源。使用參數 letter 來取得該字母的單字,副檔名為 txt。

let letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "Y", "Z"]

屆時使用這 26 字母取得權

let content = try? String(data: Data(contentsOf: path!), encoding: .utf16)

將數據轉換為字串

可以看到目前的資料是以一行一行為一個單位,這邊想要取得每一行單字資料為一個單位

allVoc = content.components(separatedBy: "\n")

使用 components(separatedBy: ) 將字串以某種形式分開來。這邊的資料是以換行為單位,所以使用 “/n” 來做區分。

取得單字資料的細節

class VocabularyList {
var vocDetails = [String]()
var english = [String]()
var chinese = [String]()
var enSentences = [String]()
var chSenteces = [String]()

func storeDetails(use allVocs: [String]) {
english.removeAll()
chinese.removeAll()
enSentences.removeAll()
chSenteces.removeAll()
vocDetails.removeAll()

if !allVocs.isEmpty {
for voc in allVocs {
vocDetails += voc.components(separatedBy: "\t")
}
var num = 0
for (i,string) in vocDetails.enumerated() {
num = (i+1)%4
switch num {
case 1:
english.append(string)
case 2:
chinese.append(string)
case 3:
enSentences.append(string)
case 0:
chSenteces.append(string)
default:
print("something wrong with details")
}
}
}
}
}

一樣在剛剛的類別中新增細項的屬性,要將剛剛 allVoc 裡面的資料拆的更細。

每一筆單字分為 — 英文、中文、英文句子、中文句子。他們分別使用 tab 分開。

if !allVocs.isEmpty {
for voc in allVocs {
vocDetails += voc.components(separatedBy: "\t")
}
}

檢視每一個單字,使用 components(separatedBy: ) 方法,使用 “\t” 代表以 tab 為單位區分。

var num = 0
for (i,string) in vocDetails.enumerated() {
num = (i+1)%4
switch num {
case 1:
english.append(string)
case 2:
chinese.append(string)
case 3:
enSentences.append(string)
case 0:
chSenteces.append(string)
default:
print("something wrong with details")
}
}

按照剛剛的分法每個單字都會有四個部分,利用輪到的數字分別儲存四個不同內容。

單字表及單字卡

每個字母會顯示對應的單字列表,每個單字的 cell 可以發出聲音。可以使用 Search Bar 尋找裡面的單字。

單字卡顯示該字母的全部單字,有翻轉功能及中英文發音功能。

單字列表程式碼

單字卡程式碼

單字收藏

在單字收藏這個功能中使用到了 CRUD 的 CRD 。由於單字是固定的所以沒有 Update 的功能。

在按下星星的時候就會在收藏列表新增 (Create) 一個單字。

按下該單字會發出聲音 (Read)

往右滑可以刪除單字 (Delete)

程式碼

自我測驗

使用 Struct 的方式生成題目,選擇題比拼字題多了選項的的屬性,拼字提比選擇題多了字數的屬性。兩邊Struct都有對答案的方法,拼字比選擇題多了顯示底線的方法。

測驗都可以調整秒數及題數,拼字練習可額外調整是否顯示底線及答案。

程式碼

--

--