我正在创建一个保存帐户的程序。我正在用用户信息逐行写入文件(第 1 行 = 用户名,第 2 行 = 密码,第 3 行 = 显示名称)。我很擅长阅读文本文件,但是如何将每一行解码为不同的变量?所以 line1 = usernameVariable, line2 = passwordVariable, line3 = displaynameVariable。
这是我读取数据的方式
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
outText = text2
} catch {/* error handling here */}
}
这就是 print(outText) 得到的:
n1
u1
p1
x
n2
u2
p2
n = 昵称,u = 用户名,p = 密码。
我只是想将 u1 读取的任何内容分配给用户名变量等。
为此,您不应该使用文本文件。有许多更合适的方法来存储和检索您的数据。文本文件在最佳选项列表中非常低。
首先,声明一个struct
来保存每个条目:
struct UserData {
let username: String
let password: String
let displayName: String
}
由于您希望保留此数据,请创建 struct Codable
:
struct UserData: Codable {
现在您可以使用JSONEncoder
对用户数据列表进行编码Data
,然后将数据写入文件。并用于JSONDecoder
回读用户数据列表。
// You array of users
let users = [ UserData(username: "Bob", password: "pass", displayName: "Hello") ]
// Get the path
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let url = dir.appendingPathComponent("userdata")
// Code to save the array of data
do {
let data = try JSONEncoder().encode(users)
try data.write(to: url)
} catch {
print("error: \(error)")
}
// Code to read the list of user data
do {
let data = try Data(contentsOf: url)
let newUsers = try JSONDecoder().decode([UserData].self, from: data)
print(newUsers)
} catch {
print("error: \(error)")
}
现在您不需要自己进行任何字符串解析。这恰好使用 JSON 来持久化数据,但该细节并不重要。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句