プログラム
text_write.swift
// -------------------------------------------------------------------------
// text_create.swift
//
// Oct/29/2024
//
// -------------------------------------------------------------------------
import Foundation
// -------------------------------------------------------------------------
func textWriteProc(fileOut: String, dictAA: [String: [String: Any]]) {
do {
let fileURL = URL(fileURLWithPath: fileOut)
var strOut = ""
for (key, unit) in dictAA {
if let name = unit["name"] as? String,
let population = unit["population"] as? Int,
let dateMod = unit["date_mod"] as? String {
strOut += "\(key)\t\(name)\t\(population)\t\(dateMod)\n"
}
}
try strOut.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
fputs("*** error *** in textWriteProc ***\n", stderr)
fputs("\(error)\n", stderr)
}
}
// -------------------------------------------------------------------------
func dataPrepareProc() -> [String: [String: Any]] {
var dictAA = [String: [String: Any]]()
dictAA["t2381"] = ["name": "名古屋", "population": 32154, "date_mod": "2003-4-17"]
dictAA["t2382"] = ["name": "豊橋", "population": 19473, "date_mod": "2003-5-r"]
dictAA["t2383"] = ["name": "岡崎", "population": 98371, "date_mod": "2003-7-21"]
dictAA["t2384"] = ["name": "一宮", "population": 51673, "date_mod": "2003-1-7"]
dictAA["t2385"] = ["name": "蒲郡", "population": 36175, "date_mod": "2003-2-2"]
dictAA["t2386"] = ["name": "常滑", "population": 31249, "date_mod": "2003-10-13"]
dictAA["t2387"] = ["name": "大府", "population": 39581, "date_mod": "2003-12-24"]
dictAA["t2388"] = ["name": "瀬戸", "population": 32875, "date_mod": "2003-11-18"]
dictAA["t2389"] = ["name": "犬山", "population": 34871, "date_mod": "2003-4-15"]
return dictAA
}
// -------------------------------------------------------------------------
fputs("*** 開始 ***\n", stderr)
let arguments = CommandLine.arguments
guard arguments.count > 1 else {
fputs("Please provide output file path\n", stderr)
exit(1)
}
let fileOut = arguments[1]
print(fileOut)
let dictAA = dataPrepareProc()
textWriteProc(fileOut: fileOut, dictAA: dictAA)
fputs("*** 終了 ***\n", stderr)
// -------------------------------------------------------------------------
実行コマンド
swift text_write.swift cities.txt
確認したバージョン
$ swift --version
Swift version 6.0.1 (swift-6.0.1-RELEASE)
Target: x86_64-unknown-linux-gnu