与 Configuration 类似,但您不认为 JSON 或 Plist 风格的 XML 是编写人性化配置文件的良好标记语言? 我也同意。 让我们改用 INI 文件。
与 JSON 不同,INI 文件支持注释,并且比 XML 和 JSON 都具有更低的“噪声”级别。
让我们编写一个像这样的 INI 文件。
; Configuration file for my great Swift app
; Lines that start with the ; character are comments
; Site name
site-name = My Great Site
; Site root URL
site-url = https://example.com/mygreatsite
; Database credentials and configuration
[database]
username = hello
password = world
现在在您的 Swift 项目中,使用 SPM 添加 Configuration-INIDeserializer。 完成后,您可以这样在您的代码中使用它。
import Configuration
import Configuration_INIDeserializer // <= Note the underscore
let config = Configuration()
// Tell Configuration how to read INI files. Don't forget this line!
config.use(INIDeserializer())
// Now you can load an INI file
config.load(file: "/path/to/my-config.conf")
// For top-level values, cast from the top level of the configuration "array"
let siteName = config["site-name"] as? String ?? "Default Site Name"
// For values in sections, try casting the section as a [String: String]
guard let databaseCredentials = config["database"] as? [String: String] else {
print("Can't find database credentials")
exit(1)
}
let databaseUsername = databaseCredentials["username"]
接受反馈、错误报告和 Patreon 赞助 并感谢您的支持!