Home > Software design >  Swift Reading plist and handle errors
Swift Reading plist and handle errors

Time:03-01

I'm trying to make a function that will return a string with the path of my plist and handle some errors, such as fileDoesntExist, notPlistFile, invalidConfiguration. The plist is being called as an argument at launch with

--configuration "${PROJECT_DIR}/configuration.plist"

I created an enum with the errors:

enum PathError: Error {
    case fileDoesntExist, notPlistFile, invalidConfiguration
}

My function so far is like this:

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>
    }

My plist:

<?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>

Now i'm having a hard time figuring out how to insert these errors into the function. Any tips/suggestions?

CodePudding user response:

If you want to throw custom errors rather than the real errors you have to guard all lines which can fail

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
}
  • Related