我正在嘗試創建一個函式,它將回傳一個帶有我的 plist 路徑的字串并處理一些錯誤,例如 fileDoesntExist、notPlistFile、invalidConfiguration。plist 在啟動時被稱為引數
--configuration "${PROJECT_DIR}/configuration.plist"
我創建了一個帶有錯誤的列舉:
enum PathError: Error {
case fileDoesntExist, notPlistFile, invalidConfiguration
}
到目前為止,我的功能是這樣的:
func getConfigurationFilePath() throws -> String {
CommandLine.arguments
if let indexPath = CommandLine.arguments.firstIndex(where: {$0 == "--configuration"}) {
let url = URL(fileURLWithPath: CommandLine.arguments[indexPath 1])
let data = try! Data(contentsOf: url)
let pListObject = try PropertyListSerialization.propertyList(from: data, options:PropertyListSerialization.ReadOptions(), format:nil)
let pListDict = pListObject as? Dictionary<String, AnyObject>
}
我的清單:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>OutputFile</key>
<string>/tmp/assessment_output.txt</string>
<key>ErrorFile</key>
<string>/tmp/assessment_error.txt</string>
<key>RunConfiguration</key>
<dict>
<key>RunInterval</key>
<integer>30</integer>
<key>Iterations</key>
<string>3</string>
</dict>
</dict>
</plist>
現在我很難弄清楚如何將這些錯誤插入到函式中。任何提示/建議?
uj5u.com熱心網友回復:
如果你想拋出自定義錯誤而不是真正的錯誤,你必須對guard所有可能失敗的行
enum PathError: Error {
case invalidParameter, fileDoesntExist, notPlistFile, invalidConfiguration
}
func getConfigurationFilePath() throws -> String {
let args = CommandLine.arguments
guard let indexPath = args.firstIndex(where: {$0 == "--configuration"}),
indexPath 1 < args.count else {
throw PathError.invalidParameter
}
let url = URL(fileURLWithPath: args[indexPath 1])
guard let data = try? Data(contentsOf: url) else {
throw PathError.fileDoesntExist
}
guard let pListObject = try? PropertyListSerialization.propertyList(from: data, format: nil) else {
throw PathError.notPlistFile
}
guard let _ = pListObject as? Dictionary<String, Any> else {
throw PathError.invalidConfiguration
}
return url.path
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/434669.html
