SWIFTWRITING SAFER CODE WITH
WRITING SAFER CODE WITH SWIFT
OVERVIEW▸ What Is Swift?▸ Basic Syntax▸ Why Do We Need Safety?▸ How Can Swift Help?
WHAT IS SWIFT?
WHAT IS SWIFT?
▸ General-purpose, multi-paradigm, programming language▸ Object oriented programming▸ Functional programming▸ Imperative programming
▸ Open source as of December 2015▸ Designed by Apple
A PROGRAMMING LANGUAGE
WHAT IS SWIFT?
NOT JUST APPLE DEVICES▸ Web development
▸ Kitura▸ Official linux binaries▸ Swift For Windows
WHAT IS SWIFT?
BASIC SYNTAXlet hello = "Hello, World!"
WHAT IS SWIFT?
BASIC SYNTAXstruct Hello {
let name: String func message() -> String { return "Hello, \(self.name)!” }}
let helloSFDevs = Hello(name: "SF Devs")
helloSFDevs.message()
WHAT IS SWIFT?
BASIC SYNTAXlet temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 { print("It's very cold. Consider wearing a scarf.") } else { print("It's not that cold. Wear a t-shirt.") }
WHAT IS SWIFT?
BASIC SYNTAXfor index in 1...5 { print("\(index) times 5 is \(index * 5)") }
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names { print("Hello, \(name)!") }
WHAT IS SWIFT?
OTHER BASIC STUFF▸ switch, guard▸ while, repeat-while▸ guard▸ enum, var▸ exception throwing/catching▸ closures (AKA lambdas, anonymous functions)
WHY DO WE NEED SAFETY?
WHY DO WE NEED SAFETY?
TO PROTECT YOURSELF…▸ Spec changes
▸ Brittle code
▸ Bugs
▸ Runtime errors
▸ Null Reference Exceptions
▸ Parsing errors
▸ We want to minimize these these things
WHY DO WE NEED SAFETY?
…FROM YOURSELF
HOW CAN SWIFT HELP?
HOW CAN SWIFT HELP?
▸ let vs. var▸ higher order functions▸ ? operator▸ if let▸ guard
HOW CAN SWIFT HELP?
LET VS. VAR
HOW CAN SWIFT HELP?
HIGHER ORDER FUNCTIONS
HOW CAN SWIFT HELP?
? OPERATOR
OTHER COOL STUFF
PRODUCTION JSON PARSINGguard
let id = json["Id"] as? Int, let lotId = json["LotId"] as? Int, let customerJson = json["Customer"] as? NSDictionary, let vehiclesJson = json["Vehicles"] as? [NSDictionary], let createdBy = json["CreatedBy"] as? String, let createdOnStr = json["CreatedOn"] as? String, let modifiedOnStr = json["ModifiedOn"] as? String else { return Result.Failure("Could not parse purchase json: \(json)")} guard let createdOn = toNSDate(.ISO8601, dateString: createdOnStr) else { return Result.Failure("Could not parse createdOn date: \(createdOnStr)")} guard let modifiedOn = toNSDate(.ISO8601, dateString: modifiedOnStr) else { return Result.Failure("Could not parse modifiedOn date: \(modifiedOnStr)")}
WRITING SAFER CODE WITH SWIFT
LEARN MORE▸ Official Documentation
▸ https://developer.apple.com/library/ios/documentation/Swift
▸ https://www.raywenderlich.com/▸ https://realm.io/news/swift-summit/
WRITING SAFER CODE WITH SWIFT
ANY QUESTIONS?