Blog about iOS development. Code snippets, best practice, discussions, stories, jokes and tutorials - everything that I can't post on Stackoverflow.
Showing posts with label Error. Show all posts
Showing posts with label Error. Show all posts
Wednesday, August 22, 2018
Errors in WWDC 2018
Some errors in the translation example. WWDC 2018, Session 404: New Localization Workflows in Xcode 10, slide 34. Looks like additional words were added just to make EN->RU translation look more complicated :)
Saturday, January 27, 2018
Catching nil as Error
Github gist.
I've posted this as an answer on stackoverflow before, and the information was highly appreciated by some people. The question was like: “How to catch any error, specially unexpectedly found nil in Swift?" Though the author was asking about catching system errors, I decided to post my super-handy Unwrap Snippet there.
The idea of this approach is to replace multiple
Those who make apps with web backend will definitely like.
I've posted this as an answer on stackoverflow before, and the information was highly appreciated by some people. The question was like: “How to catch any error, specially unexpectedly found nil in Swift?" Though the author was asking about catching system errors, I decided to post my super-handy Unwrap Snippet there.
struct UnwrapError: Error, CustomStringConvertible {
let optional: T?
public var description: String {
return "Found nil while unwrapping \(String(describing: optional))!"
}
}
public func unwrap(_ optional: T?) throws -> T {
if let real = optional {
return real
} else {
throw UnwrapError(optional: optional)
}
}
The idea of this approach is to replace multiple
if let
and guard let
statements with a single do-try-catch
block. You can:
do {
// Parse JSON and assign variables which were defined somewhere above
let dictionary = try unwrap(JSONSerialization.jsonObject(
with: data,
options: .allowFragments) as? [String: Any])
isAdsEnabled = try unwrap(dictionary["isAdsEnabled"] as? Bool)
// While calling function which require a non-optional parameter in one line of code
imageView.image = try UIImage(data: unwrap(receivedData))
// And also you can simplify the building of multipart data
var data = Data()
data += try unwrap(dispositionString.data(using: .utf8))
data += someContent
data += try unwrap("\r\n".data(using: .utf8))
} catch error {
// Handle error
// ...
// and exit
return nil
}
Those who make apps with web backend will definitely like.
Subscribe to:
Posts (Atom)