I use to write early return / golden path code in Objective-C. I tried this approach in Swift and noticed that the early return is due to the use of the force expansion operator ( ! ) When additional options are involved.
Take a method that calculates the size of a directory. First, the golden way version:
private func calculateSize_GoldenPath(directory:String) -> UInt64 { let fileManager = NSFileManager.defaultManager() var error : NSError? var contents = fileManager.contentsOfDirectoryAtPath(directory, error: &error) as [String]? if contents == nil { NSLog("Failed to list directory with error \(error)") return 0 } var size : UInt64 = 0 for pathComponent in contents! { let path = directory.stringByAppendingPathComponent(pathComponent) let attributes : NSDictionary? = fileManager.attributesOfItemAtPath(path, error: &error) if (attributes == nil) { NSLog("Failed to read file size of \(path) with error \(error)") continue } size += attributes!.fileSize() } return size; }
Notice how I use the operator ! for both the contents and attributes variables.
I assume the use of the operator ! it strikes the purpose of the options and the type of security they bring. This is how I feel that the above method should be encoded in Swift to avoid forcible deployment:
private func calculateSize_IfLet(directory:String) -> UInt64 { let fileManager = NSFileManager.defaultManager() var error : NSError? if let contents = fileManager.contentsOfDirectoryAtPath(directory, error: &error) as? [String] { var size : UInt64 = 0 for pathComponent in contents { let path = directory.stringByAppendingPathComponent(pathComponent) if let attributes : NSDictionary = fileManager.attributesOfItemAtPath(path, error: &error) { size += attributes.fileSize() } else { NSLog("Failed to read file size of \(path) with error \(error)") } } return size } else { NSLog("Failed to list directory with error \(error)") return 0 } }
However, using if let , I can no longer make an early return. If some methods do not use early return, and some of them, then I get a project with a mixed coding style.
My question is, is there a way to encode the golden path style without resorting to forced deployment when additional options are involved?
source share