プログラム
text_read.swift
// --------------------------------------------------------------------
// text_read.swift
//
// Oct/29/2024
//
// --------------------------------------------------------------------
import Foundation
// --------------------------------------------------------------------
func textReadProc(fileIn: String) -> [String:[String:Any]] {
var dict = [String: [String: Any]]()
let fpIn = try! String(contentsOfFile: fileIn, encoding: .utf8)
let lines = fpIn.components(separatedBy: .newlines)
for line in lines {
let cols = line.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: "\t")
if cols.count >= 4, cols[0].hasPrefix("t") {
if let population = Int(cols[2]) {
dict[cols[0]] = ["name": cols[1], "population": population, "date_mod": cols[3]]
} else {
print("*** error *** \(fileIn) ***")
print("*** \(line) ***")
}
}
}
return dict
}
// --------------------------------------------------------------------
func dictDisplayProc(dict: [String:[String:Any]]) {
for (key, value) in dict.sorted(by: { $0.key < $1.key }) {
let name = value["name"]!
let population = value["population"]!
let dateMod = value["date_mod"]!
print("\(key)\t\(name)\t\(population)\t\(dateMod)")
}
}
// --------------------------------------------------------------------
print("*** 開始 ***")
guard CommandLine.arguments.count > 1 else {
print("入力ファイル名を指定してください")
exit(1)
}
let fileIn = CommandLine.arguments[1]
let dict = textReadProc(fileIn: fileIn)
dictDisplayProc(dict: dict)
print("*** 終了 ***")
// --------------------------------------------------------------------
実行コマンド
swift text_read.swift cities.txt
確認したバージョン
$ swift --version
Swift version 6.0.1 (swift-6.0.1-RELEASE)
Target: x86_64-unknown-linux-gnu