Randy Scovil
Cuesta College/Cal Poly
Yes We Do Apps, Inc.
Right Up Front
 I am not here to advocate for Swift.
 I am not here to advocate against Swift.
 I use both Objective-C and Swift.
 I teach both Objective-C and Swift.
@randyscovil / SV-iOS 21/18/2016
Understood Up Front
 This is a brief introduction to Swift, with
an eye to the key differences from
Objective-C.
 You are pretty familiar with Objective-C,
and haven’t had the time/inclination to
investigate Swift.
 We may not agree on everything.
@randyscovil / SV-iOS 31/18/2016
Brief History of Teaching iOS
 Jan. 2010: First iOS Course
 Jan. 2013: First iOS II Course
 (1st such course in CA)
 Jan. 2015: Swift taught in iOS II
 Objective-C in iOS I
 Aug. 2015: Swift taught in iOS I
 Jan. 2016: Objective-C will be taught in
iOS II, as well as more advanced Swift
@randyscovil / SV-iOS 41/18/2016
Observations of iOS Courses
 Wide range of backgrounds
 Sizeable contingent has 0 coding
background
 Some with O-O background
 Most get the core ideas/syntax of
Objective-C within a semester
 The easy parts of Swift are easier to
learn than Objective-C
 The harder parts of Swift are harder
@randyscovil / SV-iOS 51/18/2016
Data Types
 Most things are value types
 Classes and closures are reference types
 Value types include:
 Strings
 Arrays
 Enums
 Tuples
@randyscovil / SV-iOS 61/18/2016
Implicit All-Seeing Superclass
 In Swift, there isn’t one
 Must explicitly subclass NSObject if needed
 Need to opt in to key protocols
 CustomStringConvertible
○ description
 Equatable
○ ==
 Hashable
○ hashValue
 Comparable
○ comparison operators
@randyscovil / SV-iOS 71/18/2016
Declarations
 No explicitly (im)mutable types
 Declare with let for constant, var for
variable (must use var, not implicit)
 Can explicitly set type with a type
annotation, or set via type inference
based on initial value
// Type annotation
let theString : String
// Inferred as String
var someString = “Hey now”
@randyscovil / SV-iOS 81/18/2016
Optionals
 One of the bigger adjustments to make
 Any type (value or reference) can be
declared as an optional type
 Means it may have nil, or a value
 Declare with a ? after the type (e.g. Int?)
 To get value need to unwrap the optional
 Frees you from initialization obligations
 Actually syntactic sugar for the Optional
generic type
@randyscovil / SV-iOS 91/18/2016
Optional Binding
 Execute only if optional is not nil
// instead of this
if possibleNil != nil {
doSomethingWith(possibleNil)
}
// you tend to do this
// localValue is assigned value
if let localValue = possibleNil {
doSomethingWith(localValue)
}
@randyscovil / SV-iOS 101/18/2016
Implicitly Unwrapped Optionals
 If an optional is assumed to always have
a value, can bypass binding and unwrap
it using the ! operator
 Unwrapping a nil is a runtime error
 Often show up as parameters in
framework methods
let unwrapMe : String!
let implicit : String = unwrapMe
@randyscovil / SV-iOS 111/18/2016
Range Operators
 Half-open range (..<) – doesn’t include
second value:
for i in 0..<array.count {
doFunStuff(array[i])
}
 Closed range (…) includes both points
for i in 1…howManyTimes {
doStuff()
}
@randyscovil / SV-iOS 121/18/2016
Strings
 Pretty straightforward
 Immutable/mutable based on let/var
 Get contents of value as String with ()
around variable
 Type must conform to
CustomStringConvertible protocol
let bob = 23
someLabel.text = “Value: (Bob)”
@randyscovil / SV-iOS 131/18/2016
Control Flow
 No () around conditions
 Usual conditional/loop structures
 switch is a different animal
 Checks to see if exhaustive
 Implicit break, explicit fallthrough
 Range and Tuple matching
 where clause – allows you to match with a
condition:
case let (x, y) where x == y :
@randyscovil / SV-iOS 141/18/2016
guard Statements
 New for Swift 2
 Concise way to send code packing if a
condition is not met
 Also can be used to throw errors
/* assign value of key “name” from
dict person fail if key not present */
guard let name = person[“name”] else {
return
}
@randyscovil / SV-iOS 151/18/2016
Functions
 Do not have to belong to anything – can
be global
 Functions (methods) can be members of
enums and structs
 Functions can be variables, parameters
and return values
 Can be nested inside other functions
 Overridden versions require an explicit
override keyword
@randyscovil / SV-iOS 161/18/2016
Function Headers
 All functions start with the func keyword
 Return value is last after -> operator
 If no ->, implicitly void
func timesTwo(a : Int) - > Int {
return a * 2
}
func noReturn(a : Int) {
print(a)
}
@randyscovil / SV-iOS 171/18/2016
Parameter Passing
 Value types passed by value, reference
types passed by…reference
 Can pass a value type by prepending &
on the argument and listing parameter
as inout to allow mutating beyond
scope of function
 Parameters must be explicitly annotated
to mutate them locally
 Declare them as var parameters
@randyscovil / SV-iOS 181/18/2016
Closures
 Think blocks
 Use {} and in
 sort() and sortInPlace() take a
closure argument with two parameters
of array type, returning Bool
reversed = names.sort( {
(s1: String, s2: String) -> Bool in
return s1 > s2
})
@randyscovil / SV-iOS 191/18/2016
Trailing Closures
 If a closure is the last argument, you can
pass it outside the closing paren of the
method call
reversed = names.sort()
{
(s1: String, s2: String) -> Bool in
return s1 > s2
}
 This can be reduced down to:
{ $0 > $1 }
@randyscovil / SV-iOS 201/18/2016
Classes, Structs, Enums
 Classes are reference types
 Structs are value types and can have
defined initializers (in addition to a
compiler-generated memberwise
initializer)
 Structs are pretty close to classes in
Swift…
@randyscovil / SV-iOS 211/18/2016
How are Classes Distinct?
 Allow inheritance
 Can check runtime type via type casting
 Have deinitializers
 Use reference counting
@randyscovil / SV-iOS 221/18/2016
When To Use Structs?
 Type is a few relatively simple values
 Want to pass a copy rather than a
reference
 Properties are value types
 Doesn’t need to inherit from another
type
@randyscovil / SV-iOS 231/18/2016
Enumerations
 Can have methods
 Once type is established (through local
declaration, parameter, or expected
argument type) can be referenced
without the actual type but just with .
and the enum value
let addButton = UIBarButtonItem
(barButtonSystemItem: .Add,
target: self,
action:"addPressed")
@randyscovil / SV-iOS 241/18/2016
Properties
 Declared as variables outside methods
 lazy properties
 Not initialized until used
 Computed properties
 Declared as properties that can define get/set
operations to compute on demand
 Property Observers
 Can define willSet and didSet code to be
triggered pre/post-assignment
 New and old values are available
@randyscovil / SV-iOS 251/18/2016
Inheritance
 Define superclass and protocols
conformed to with commas after :
following class name:
class Student : Person, Hashable
 Overridden methods must be prefaced
with the override keyword
override func viewDidLoad() {
super.viewDidLoad()
}
@randyscovil / SV-iOS 261/18/2016
Initialization
 All initializers are named init()
 Every property must do one of:
 Have a default value
 Be initialized in all init()s
 Be declared as an optional
 Very specific rules on implementing
initializers when subclassing
 Designated and convenience initializers
 Spend some time with this chapter in The
Swift Programming Language book
@randyscovil / SV-iOS 271/18/2016
Optional Chaining
 When you need to access a property of
an optional
 In lieu of forced unwrapping
 ? After optional to access
// address is optional property
// true if address non-nil
if let zip = joe.address?.zip {
}
@randyscovil / SV-iOS 281/18/2016
Error Handling
 Can define throws in header
 Do not have to specify error type thrown
 Method call preceded by try inside a do
do {
try iAmErrorProne(“Guh”)
}
catch {
}
@randyscovil / SV-iOS 291/18/2016
Type Casting – Runtime Types
 Check for runtime type with is
/* Movie & Song are subclasses
of MediaItem */
let library = [MediaItem]()
for item in library {
if item is Movie {
} else if item is Song {
}
}
@randyscovil / SV-iOS 301/18/2016
Downcasting – as?, as!
 Conditional type cast – only do
conditional block if cast succeeds
if let movie = item as? Movie {
} else if let song = item as? Song {
}
 Forced cast – when type is assured
let destVC
segue.destinationViewController
as! EditItemViewController
@randyscovil / SV-iOS 311/18/2016
Extensions
 Think Categories
 Define as extension, then type being
extended:
extension SomeType {
 May include adding conformance to a
protocol:
extension SomeType: SomeProtocol {
@randyscovil / SV-iOS 321/18/2016
Protocols
 Structs can adopt
 Can require properties
 Can require specific initializers
 Optional requirements must be explicitly
labeled optional
@randyscovil / SV-iOS 331/18/2016
Generics
 Very similar to what you may have
encountered in Java
 Parameterized type in <>
func swapTwoValues<T>
(inout a: T, inout _ b: T) {
let tempA = a
a = b
b = tempA
}
@randyscovil / SV-iOS 341/18/2016
Swift Resources
 The Swift Programming Language
 Available at Apple Developer site and via
iBooks
 Pretty good read, not set up for TL;DR
 Swift Playgrounds in Xcode
 Great for testing out ideas in code
 Interactively displays results
 Support graphics
 Can embed Markdown
 Not an app component
@randyscovil / SV-iOS 351/18/2016
We’re Hiring!
 Full-Time, Tenure-Track CIS Opening at
Cuesta College
 Starts mid-August
 More info: jobs.cuesta.edu
 Contact me anytime:
 rscovil@cuesta.edu
 randy@yeswedoapps.com
 @randyscovil
@randyscovil / SV-iOS 361/18/2016
Thanks!
1/18/2016 @randyscovil / SV-iOS 37

SV-ios-objc-to-swift

  • 1.
    Randy Scovil Cuesta College/CalPoly Yes We Do Apps, Inc.
  • 2.
    Right Up Front I am not here to advocate for Swift.  I am not here to advocate against Swift.  I use both Objective-C and Swift.  I teach both Objective-C and Swift. @randyscovil / SV-iOS 21/18/2016
  • 3.
    Understood Up Front This is a brief introduction to Swift, with an eye to the key differences from Objective-C.  You are pretty familiar with Objective-C, and haven’t had the time/inclination to investigate Swift.  We may not agree on everything. @randyscovil / SV-iOS 31/18/2016
  • 4.
    Brief History ofTeaching iOS  Jan. 2010: First iOS Course  Jan. 2013: First iOS II Course  (1st such course in CA)  Jan. 2015: Swift taught in iOS II  Objective-C in iOS I  Aug. 2015: Swift taught in iOS I  Jan. 2016: Objective-C will be taught in iOS II, as well as more advanced Swift @randyscovil / SV-iOS 41/18/2016
  • 5.
    Observations of iOSCourses  Wide range of backgrounds  Sizeable contingent has 0 coding background  Some with O-O background  Most get the core ideas/syntax of Objective-C within a semester  The easy parts of Swift are easier to learn than Objective-C  The harder parts of Swift are harder @randyscovil / SV-iOS 51/18/2016
  • 6.
    Data Types  Mostthings are value types  Classes and closures are reference types  Value types include:  Strings  Arrays  Enums  Tuples @randyscovil / SV-iOS 61/18/2016
  • 7.
    Implicit All-Seeing Superclass In Swift, there isn’t one  Must explicitly subclass NSObject if needed  Need to opt in to key protocols  CustomStringConvertible ○ description  Equatable ○ ==  Hashable ○ hashValue  Comparable ○ comparison operators @randyscovil / SV-iOS 71/18/2016
  • 8.
    Declarations  No explicitly(im)mutable types  Declare with let for constant, var for variable (must use var, not implicit)  Can explicitly set type with a type annotation, or set via type inference based on initial value // Type annotation let theString : String // Inferred as String var someString = “Hey now” @randyscovil / SV-iOS 81/18/2016
  • 9.
    Optionals  One ofthe bigger adjustments to make  Any type (value or reference) can be declared as an optional type  Means it may have nil, or a value  Declare with a ? after the type (e.g. Int?)  To get value need to unwrap the optional  Frees you from initialization obligations  Actually syntactic sugar for the Optional generic type @randyscovil / SV-iOS 91/18/2016
  • 10.
    Optional Binding  Executeonly if optional is not nil // instead of this if possibleNil != nil { doSomethingWith(possibleNil) } // you tend to do this // localValue is assigned value if let localValue = possibleNil { doSomethingWith(localValue) } @randyscovil / SV-iOS 101/18/2016
  • 11.
    Implicitly Unwrapped Optionals If an optional is assumed to always have a value, can bypass binding and unwrap it using the ! operator  Unwrapping a nil is a runtime error  Often show up as parameters in framework methods let unwrapMe : String! let implicit : String = unwrapMe @randyscovil / SV-iOS 111/18/2016
  • 12.
    Range Operators  Half-openrange (..<) – doesn’t include second value: for i in 0..<array.count { doFunStuff(array[i]) }  Closed range (…) includes both points for i in 1…howManyTimes { doStuff() } @randyscovil / SV-iOS 121/18/2016
  • 13.
    Strings  Pretty straightforward Immutable/mutable based on let/var  Get contents of value as String with () around variable  Type must conform to CustomStringConvertible protocol let bob = 23 someLabel.text = “Value: (Bob)” @randyscovil / SV-iOS 131/18/2016
  • 14.
    Control Flow  No() around conditions  Usual conditional/loop structures  switch is a different animal  Checks to see if exhaustive  Implicit break, explicit fallthrough  Range and Tuple matching  where clause – allows you to match with a condition: case let (x, y) where x == y : @randyscovil / SV-iOS 141/18/2016
  • 15.
    guard Statements  Newfor Swift 2  Concise way to send code packing if a condition is not met  Also can be used to throw errors /* assign value of key “name” from dict person fail if key not present */ guard let name = person[“name”] else { return } @randyscovil / SV-iOS 151/18/2016
  • 16.
    Functions  Do nothave to belong to anything – can be global  Functions (methods) can be members of enums and structs  Functions can be variables, parameters and return values  Can be nested inside other functions  Overridden versions require an explicit override keyword @randyscovil / SV-iOS 161/18/2016
  • 17.
    Function Headers  Allfunctions start with the func keyword  Return value is last after -> operator  If no ->, implicitly void func timesTwo(a : Int) - > Int { return a * 2 } func noReturn(a : Int) { print(a) } @randyscovil / SV-iOS 171/18/2016
  • 18.
    Parameter Passing  Valuetypes passed by value, reference types passed by…reference  Can pass a value type by prepending & on the argument and listing parameter as inout to allow mutating beyond scope of function  Parameters must be explicitly annotated to mutate them locally  Declare them as var parameters @randyscovil / SV-iOS 181/18/2016
  • 19.
    Closures  Think blocks Use {} and in  sort() and sortInPlace() take a closure argument with two parameters of array type, returning Bool reversed = names.sort( { (s1: String, s2: String) -> Bool in return s1 > s2 }) @randyscovil / SV-iOS 191/18/2016
  • 20.
    Trailing Closures  Ifa closure is the last argument, you can pass it outside the closing paren of the method call reversed = names.sort() { (s1: String, s2: String) -> Bool in return s1 > s2 }  This can be reduced down to: { $0 > $1 } @randyscovil / SV-iOS 201/18/2016
  • 21.
    Classes, Structs, Enums Classes are reference types  Structs are value types and can have defined initializers (in addition to a compiler-generated memberwise initializer)  Structs are pretty close to classes in Swift… @randyscovil / SV-iOS 211/18/2016
  • 22.
    How are ClassesDistinct?  Allow inheritance  Can check runtime type via type casting  Have deinitializers  Use reference counting @randyscovil / SV-iOS 221/18/2016
  • 23.
    When To UseStructs?  Type is a few relatively simple values  Want to pass a copy rather than a reference  Properties are value types  Doesn’t need to inherit from another type @randyscovil / SV-iOS 231/18/2016
  • 24.
    Enumerations  Can havemethods  Once type is established (through local declaration, parameter, or expected argument type) can be referenced without the actual type but just with . and the enum value let addButton = UIBarButtonItem (barButtonSystemItem: .Add, target: self, action:"addPressed") @randyscovil / SV-iOS 241/18/2016
  • 25.
    Properties  Declared asvariables outside methods  lazy properties  Not initialized until used  Computed properties  Declared as properties that can define get/set operations to compute on demand  Property Observers  Can define willSet and didSet code to be triggered pre/post-assignment  New and old values are available @randyscovil / SV-iOS 251/18/2016
  • 26.
    Inheritance  Define superclassand protocols conformed to with commas after : following class name: class Student : Person, Hashable  Overridden methods must be prefaced with the override keyword override func viewDidLoad() { super.viewDidLoad() } @randyscovil / SV-iOS 261/18/2016
  • 27.
    Initialization  All initializersare named init()  Every property must do one of:  Have a default value  Be initialized in all init()s  Be declared as an optional  Very specific rules on implementing initializers when subclassing  Designated and convenience initializers  Spend some time with this chapter in The Swift Programming Language book @randyscovil / SV-iOS 271/18/2016
  • 28.
    Optional Chaining  Whenyou need to access a property of an optional  In lieu of forced unwrapping  ? After optional to access // address is optional property // true if address non-nil if let zip = joe.address?.zip { } @randyscovil / SV-iOS 281/18/2016
  • 29.
    Error Handling  Candefine throws in header  Do not have to specify error type thrown  Method call preceded by try inside a do do { try iAmErrorProne(“Guh”) } catch { } @randyscovil / SV-iOS 291/18/2016
  • 30.
    Type Casting –Runtime Types  Check for runtime type with is /* Movie & Song are subclasses of MediaItem */ let library = [MediaItem]() for item in library { if item is Movie { } else if item is Song { } } @randyscovil / SV-iOS 301/18/2016
  • 31.
    Downcasting – as?,as!  Conditional type cast – only do conditional block if cast succeeds if let movie = item as? Movie { } else if let song = item as? Song { }  Forced cast – when type is assured let destVC segue.destinationViewController as! EditItemViewController @randyscovil / SV-iOS 311/18/2016
  • 32.
    Extensions  Think Categories Define as extension, then type being extended: extension SomeType {  May include adding conformance to a protocol: extension SomeType: SomeProtocol { @randyscovil / SV-iOS 321/18/2016
  • 33.
    Protocols  Structs canadopt  Can require properties  Can require specific initializers  Optional requirements must be explicitly labeled optional @randyscovil / SV-iOS 331/18/2016
  • 34.
    Generics  Very similarto what you may have encountered in Java  Parameterized type in <> func swapTwoValues<T> (inout a: T, inout _ b: T) { let tempA = a a = b b = tempA } @randyscovil / SV-iOS 341/18/2016
  • 35.
    Swift Resources  TheSwift Programming Language  Available at Apple Developer site and via iBooks  Pretty good read, not set up for TL;DR  Swift Playgrounds in Xcode  Great for testing out ideas in code  Interactively displays results  Support graphics  Can embed Markdown  Not an app component @randyscovil / SV-iOS 351/18/2016
  • 36.
    We’re Hiring!  Full-Time,Tenure-Track CIS Opening at Cuesta College  Starts mid-August  More info: jobs.cuesta.edu  Contact me anytime:  rscovil@cuesta.edu  randy@yeswedoapps.com  @randyscovil @randyscovil / SV-iOS 361/18/2016
  • 37.