1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swift: Text から Dictionary に変換

Posted at

プログラム

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
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?