SlideShare una empresa de Scribd logo
1 de 59
Descargar para leer sin conexión
NSCoder Swift 
An introduction to Swift 
Andreas Blick - @aquarioverde 
October 18th, 2014
Swift
Swift 
• New programming language introduced by 
Apple on June 2014 at WWDC 
• Builds on the best of C and Objective-C, without 
the constraints of C compatibility 
• Development started by Chris Lattner, who also 
started the LLVM and Clang project
Swift 
• Safe programming patterns and modern 
features 
• Seamless access to all existing Cocoa 
frameworks 
• Mix-and-match interoperability with Objective-C
Playgrounds
Playgrounds 
• Tool / Feature for 
• learning 
• code development 
• experimentation
Playgrounds 
• Strings 
• Arrays & dictionaries 
• Color 
• Views 
• Images 
• … etc
var / let
Variables & Constants 
• Defined using var or let keyword 
• No need to define type 
• Swift can mostly infer the type 
• Can contain any unicode character 
var instrument: String = “guitar” 
let nrOfSongs = 42 
var trackLength = 3.23
Strings 
• Collection of characters that can be accessed easily 
• Seamlessly bridged: NSString API available 
• Mutability defined by assignment (var or let) 
• String interpolation for literals, variables and expressions 
let instrument = “guitar" 
! 
let music = "play (instrument)" 
let noise = "play " + instrument
Numbers 
• Integers are stored as Int or UInt 
• can be written as decimal, binary, octal, hexadecimal 
• have max and min properties: Int.max 
• Floating point numbers are stored as Float and Double 
• can be written as decimal and hexadecimal 
• Can contain underscores for readability: 7_777.77 
• Bool can be true or false
Arrays 
• Stores ordered list of multiple values 
• Arrays are type specific 
• Accessed using properties, methods or subscripting 
var numbers: Array<Int> = Array<Int>() 
var numbers: [Int] = [Int]() 
! 
numbers = [1,2,3] 
numbers = [Int](count:7,repeatedValue:0]
Dictionaries 
• Containers that store multiple key-value pairs of the 
same type 
• Accessed using properties, methods or subscripting 
• Assigning nil as a value removes it 
var numbers:Dictionary<Int,String> = Dictionary<Int,String>() 
! 
numbers = [1:“One”,2:“Two”,3:”Three”]
Tuples 
• Group multiple values of any type into a single compound value 
• Values can be of any type 
• Values can be accessed by index 
• Tuples can have named values 
let instrument = ("guitar", “strings") 
println(instrument.0) 
! 
let (name, family) = instrument 
! 
let instrument = (name: "guitar", family: "strings")
Loops 
• for-in loop to iterate using range 
• for-in loops to iterate over a collection 
• while / do-while loops if unknown number of iterations 
for ix in 1…5 { . . . } 
for var ix = 0; ix < 7; ix++ { . . . } 
for (key, value) in aDictionary { . . . } 
! 
while ix < 7 { . . . } 
do { . . . } while ix < 7
Conditionals 
• if / else for simple conditions 
• switch statements for complex conditions 
if number == 5 { . . . } 
! 
switch number { 
case 5: 
println(“5”) 
default: 
println(“default”) 
}
Conditionals - Switch 
• do not fall through (no break needed) 
• must be exhaustive (use default:) 
• support ranges: case 0…7: 
• support tuples: case (1, 2): 
• value binding: case (let x, 2): 
• can use where clause to check additional conditions 
case (let x, let y) where x == y:
Control Transfer Statements 
• continue 
• break 
• return 
• fallthrough 
• loops and switches can be labeled to be used with break and continue 
counter: for i in 1...7 { 
for j in 1...7 { 
println("(i) - (j)") 
if i == 3 { continue counter} 
} 
}
?
Optionals 
• Used where a value might be missing by adding a ? sign 
• Similar to nil in Objective-C, but can be used on any type 
• non optionals can not be nil 
• Optionals can implicitly be unwrapped by adding a ! sign (forced 
unwrapping) 
let instruments = ["guitar" : 6, "bass": 4, “ukulele”: “8”] 
let nrOfStrings: Int? = instruments[“guitar"] 
! 
if nrOfStrings != nil { 
println(nrOfStrings!) 
} else { . . . }
Optionals 
• Use optional binding to find out if an optional 
contains a value 
let instruments = ["guitar" : 6, "bass": 4, “ukulele”: “8”] 
let nrOfStrings: Int? = instruments[“guitar"] 
! 
if let nrOfStrings = instruments["guitar"] { 
println(nrOfStrings) 
} else { . . . } 
• Use optional chaining when a value might be nil 
let familyName = guitar.family?.name?
func
Functions 
• Functions are blocks of code that execute a specific task 
• Functions have parameters and can return values - default to void 
• Parameters can have default values 
• They should always be placed at the end of the list 
func play(instrument: String = "guitar") -> String { 
return "play (instrument)" 
} 
! 
play(instrument: "drums")
Functions 
• Parameter names are not required when calling a function 
that has no default values 
• Functions can return multiple values using tuples 
• Use # if external and internal parameter names are the same 
func play(instrument: String) -> (String, volume: Int) { 
return ("play (instrument)", 7) 
} 
play(“guitar").volume 
! 
func play(instrument instr: String) -> String { . . . } 
func play(#instrument: String) -> String { . . . }
Functions 
• Functions can take a variable number of 
arguments using variadic parameters 
• One function can only have one variadic 
parameter 
func playInstruments(instruments: String...) -> String { 
var play = "playing " 
for instrument in instruments { 
play += instrument + " " 
} 
return play 
} 
playInstruments("guitar", "drums", "sax")
Functions 
• Parameters are constants by default and can not be changed 
• They can be defined as variables using var 
• Variables parameters can only be modified within a function 
• To persist a variable outside a function the inout parameter is needed 
func swapTwoInts(inout a: Int, inout b: Int) { 
let tmpA = a 
a = b 
b = tmpA 
} 
var x = 3, y = 7 
swapTwoInts(&x, &y)
Functions 
• Functions have a specific function type that can be assigned to 
variables 
• They can be passed as parameters and returned by other 
functions 
• Functions can be nested 
func iPlay(player:(String) ->String, song:String) ->String { 
return player(song) 
} 
func playGuitar(song: String) -> String { 
return "playing (song) on guitar" 
} 
let playing = iPlay(playGuitar, "I sat by the ocean")
Closures 
{}
Closures 
• Closures are self-contained blocks of code that 
can be passed around 
• Functions are named closures! 
• Closures can capture and store references and 
constants from their surrounding context 
• Trailing closures can be used for readability 
• Closures start using the in keyword
Closures - Example 
let playMusic = { println("make some noise”) } 
! 
! 
! 
func repeat(count:Int, song:String, player:(String)->(String)) { 
for i in 0..<count { 
println(player(song)); 
} 
} 
repeat(5, "Even Flow") { 
(song: String) -> String in 
return "playing (song)" 
}
class
Classes 
• Classes are program code templates for creating 
objects, consisting of properties and methods 
• No need for interface/header files 
• No need to inherit from any other class 
• No abstract class support 
• Compare using the identity operator ===
Classes - Properties 
• Access to properties handled automatically 
• Properties do not have a corresponding instance 
variable 
• Every property needs to have a value assigned 
• Properties without a setter are read-only 
• Can have lazy stored properties (lazy) 
• Type properties are defined using class keyword
Classes - Example 
class Instrument { 
let type: String 
var isUsed: Bool = false 
init(type: String) { 
self.type = type 
} 
var info: String { 
get { 
return isUsed ? "used (type)" : "new (type)" 
} 
} 
} 
! 
let electricGuitar = Instrument(type: "guitar")
Classes - Properties 
• Property observers can respond to changes in a 
properties’ value (willSet & didSet) 
var isUsed: Bool = false { 
willSet(willBeUsed) { 
let msg = (self.isUsed ? "was" : "was not") + 
" used and “ + 
(willBeUsed ? "is used now" : "is not used now”) 
println(msg) 
} 
}
Classes - Methods 
• Methods are functions associated with a particular type 
• Subscripts are special methods (subscript) for 
accessing members. They can contain any number of 
input parameters of any type. 
class Instrument { 
func play() { 
println("make some noise") 
} 
subscript(ix: Int) -> String { 
return "model (ix)" 
} 
}
Initialization 
• The class needs to be completely initialized before 
accessing any property or method 
• Properties that are allowed to have no value can be 
declared optional using the ? sign 
• Property observers are NOT called on initialization 
• Every class must have at least one designated initialiser 
• Every class can have multiple convenience initializers 
• Deinitializers can be used for cleaning up
Initializer Chaining 
• Designated initializers must call a designated 
initializer from their immediate superclass 
• Convenience initializers must call another 
initializer available in the same class 
• Convenience initializers must ultimately end up 
calling a designated initializer
Initialization - Example 
class Instrument { 
let type: String 
var family: String? 
init(type: String) { 
self.type = type 
} 
convenience init(type: String, family: String) { 
self.init(type: type) 
self.family = family 
} 
deinit { 
println("instrument (type) destroyed") 
} 
} 
! 
let guitar = Instrument(type: “guitar")
Initialization 
• Closures can be used for initialising complex 
properties 
class Some { 
let some: String = { 
return "some" 
}() 
}
Inheritance 
• Classes can inherit methods, properties from other 
classes 
• Initializers are not inherited by default 
• Initialize own class properties before calling super.init 
• Overridden methods need override keyword 
• Methods marked as final can not be overridden 
• An entire class can be marked as final
Inheritance - Example 
class Guitar : Instrument { 
init() { 
super.init(type: "guitar") 
family = "Strings" 
} 
! 
override func play() { 
println("make some noise") 
} 
} 
! 
let guitar = Guitar()
struct
Structures 
• Structures are value types, they are always 
copied, not referenced 
• Structures can have initializers, methods and 
properties 
• Automatically generated memberwise initializer 
• Structures do not have deinitializers 
• Array and Dictionary are structures
Structures 
• All properties of constant structures are constant as 
well 
• Methods for modifying structure properties need 
the mutating keyword 
• Structures do not support inheritance 
• No type-casting 
• Type properties are defined using static keyword
Enumerations 
• An enumeration is a complete collection of items 
• Enumeration values are fully-fledged in their own 
• Enumerations are first-class types! 
• Enumerations can have methods & initialisers 
• Enumeration can have default raw values of the 
same type
Enumerations - Example 
enum Instrument: Int { 
case Guitar = 1, Base 
case Drums, Bongo, Trumpet, Saxophone 
func description() -> String { 
switch self { 
case .Guitar, .Base: 
return "Strings" 
case .Trumpet, .Saxophone: 
return "Wind" 
default: 
return "Unknown" 
} 
} 
} 
let instrument = Instrument.Trumpet 
instrument.description() 
instrument.toRaw() 
let unknown = Instrument.fromRaw(1)?.description()
Enumerations 
• Enumerations can have associated values 
enum Instrument { 
case Guitar(nrOfStrings: Int), Base 
case Drums, Bongo 
func description() -> String { 
switch self { 
case .Guitar(let nrOfStrings): 
return ("(nrOfStrings)-string guitar") 
default: 
return "Unknown" 
} 
} 
} 
let instrument = Instrument.Guitar(nrOfStrings: 6) 
instrument.description()
++
Extensions 
• Extensions add new functionality to existing classes, 
structures, … etc. 
They are similar to Categories in Objective-C 
• They can add methods, computed properties, initialisers 
but no stored properties 
extension Instrument { 
func rock() { 
println("(type) is rocking") 
} 
}
Protocols 
• A protocol defines methods and properties a class, struct 
or enumeration can or must adopt 
• Existing types can be extended to adopt a protocol 
• A protocol can inherit from one or more other protocols 
• Protocol composition can be used to combine protocols 
• Any protocol can be used as type 
• Define as @objc for type checking and optional support
Protocols - Example 
@objc protocol Instrument { 
func play() 
} 
! 
class Guitar: Instrument { 
func play() { 
println("playing guitar") 
} 
} 
! 
let items = [Guitar(), NSString()] 
! 
for item in items { 
if let instrument = item as? Instrument { 
instrument.play() 
} 
}
Generics 
• Generic code enables writing flexible, reusable 
functions and types 
func swapTwoValues<T>(inout a: T, inout b: T) { 
let tmpA = a 
a = b 
b = a 
}
Generics 
• You can define your own generic type 
• and specify type constraints 
struct Stack<T: Instrument> { 
var items = [T]() 
mutating func push(item: T) { 
items.append(item) 
} 
mutating func pop() { 
items.removeLast() 
} 
} 
var guitarStack = Stack<Guitar>()
References 
• WWDC 2014 Videos 
• Apple Books 
• The Swift Programming Language 
• Using Swift with Cocoa & Objective-C 
• Web 
• https://developer.apple.com/swift/
+++
ARC 
• Swift handles memory management using 
automatic reference counting 
• Think about relationship between object instead 
of memory 
• Avoid strong reference cycles by using weak or 
unowned references
Assertions 
• Use assertions whenever a condition has the 
potential to be false, but must be true 
• End code execution 
let age = -3 
assert(age >= 0, "age can no be less than 0")
Thank you! 
Andreas Blick - @aquarioverde

Más contenido relacionado

La actualidad más candente

Python first day
Python first dayPython first day
Python first dayfarkhand
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)mircodotta
 
Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013rivierarb
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-CKazunobu Tasaka
 
Java core - Detailed Overview
Java  core - Detailed OverviewJava  core - Detailed Overview
Java core - Detailed OverviewBuddha Tree
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionOregon FIRST Robotics
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming PatternsVasil Remeniuk
 
(4) collections algorithms
(4) collections algorithms(4) collections algorithms
(4) collections algorithmsNico Ludwig
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scalafanf42
 
(4) collections algorithms
(4) collections algorithms(4) collections algorithms
(4) collections algorithmsNico Ludwig
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingPranavSB
 
Swift as an OOP Language
Swift as an OOP LanguageSwift as an OOP Language
Swift as an OOP LanguageAhmed Ali
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functionaldjspiewak
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)mircodotta
 

La actualidad más candente (20)

Python first day
Python first dayPython first day
Python first day
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
 
Java core - Detailed Overview
Java  core - Detailed OverviewJava  core - Detailed Overview
Java core - Detailed Overview
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introduction
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming Patterns
 
(4) collections algorithms
(4) collections algorithms(4) collections algorithms
(4) collections algorithms
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
(4) collections algorithms
(4) collections algorithms(4) collections algorithms
(4) collections algorithms
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception Handling
 
Swift as an OOP Language
Swift as an OOP LanguageSwift as an OOP Language
Swift as an OOP Language
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functional
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Intermediate JavaScript
Intermediate JavaScriptIntermediate JavaScript
Intermediate JavaScript
 
Python programming
Python programmingPython programming
Python programming
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
 
Javascript
JavascriptJavascript
Javascript
 

Destacado

An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with SwiftFatih Nayebi, Ph.D.
 
Session 1. iOS developers enthusiasts session
Session 1. iOS developers enthusiasts sessionSession 1. iOS developers enthusiasts session
Session 1. iOS developers enthusiasts sessionGAME Studios
 
Object Oriented Programming in Swift Ch0 - Encapsulation
Object Oriented Programming in Swift Ch0 - EncapsulationObject Oriented Programming in Swift Ch0 - Encapsulation
Object Oriented Programming in Swift Ch0 - EncapsulationChihyang Li
 
Amazon DynamoDB Design Patterns for Ultra-High Performance Apps (DAT304) | AW...
Amazon DynamoDB Design Patterns for Ultra-High Performance Apps (DAT304) | AW...Amazon DynamoDB Design Patterns for Ultra-High Performance Apps (DAT304) | AW...
Amazon DynamoDB Design Patterns for Ultra-High Performance Apps (DAT304) | AW...Amazon Web Services
 
Practical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingNatasha Murashev
 
Game Development Using Swift Programming Language
Game Development Using Swift Programming LanguageGame Development Using Swift Programming Language
Game Development Using Swift Programming LanguageSarah Hussein
 

Destacado (6)

An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with Swift
 
Session 1. iOS developers enthusiasts session
Session 1. iOS developers enthusiasts sessionSession 1. iOS developers enthusiasts session
Session 1. iOS developers enthusiasts session
 
Object Oriented Programming in Swift Ch0 - Encapsulation
Object Oriented Programming in Swift Ch0 - EncapsulationObject Oriented Programming in Swift Ch0 - Encapsulation
Object Oriented Programming in Swift Ch0 - Encapsulation
 
Amazon DynamoDB Design Patterns for Ultra-High Performance Apps (DAT304) | AW...
Amazon DynamoDB Design Patterns for Ultra-High Performance Apps (DAT304) | AW...Amazon DynamoDB Design Patterns for Ultra-High Performance Apps (DAT304) | AW...
Amazon DynamoDB Design Patterns for Ultra-High Performance Apps (DAT304) | AW...
 
Practical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-Programming
 
Game Development Using Swift Programming Language
Game Development Using Swift Programming LanguageGame Development Using Swift Programming Language
Game Development Using Swift Programming Language
 

Similar a NSCoder Swift - An Introduction to Swift

Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...gjcross
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
OOP-java-variables.pptx
OOP-java-variables.pptxOOP-java-variables.pptx
OOP-java-variables.pptxssuserb1a18d
 
Learning core java
Learning core javaLearning core java
Learning core javaAbhay Bharti
 
Python Programming and GIS
Python Programming and GISPython Programming and GIS
Python Programming and GISJohn Reiser
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developersMohamed Wael
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Functional programming with F#
Functional programming with F#Functional programming with F#
Functional programming with F#Remik Koczapski
 

Similar a NSCoder Swift - An Introduction to Swift (20)

kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Datatype
DatatypeDatatype
Datatype
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
 
Net framework
Net frameworkNet framework
Net framework
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
OOP-java-variables.pptx
OOP-java-variables.pptxOOP-java-variables.pptx
OOP-java-variables.pptx
 
Python by ganesh kavhar
Python by ganesh kavharPython by ganesh kavhar
Python by ganesh kavhar
 
enum_namespace.ppt
enum_namespace.pptenum_namespace.ppt
enum_namespace.ppt
 
Learning core java
Learning core javaLearning core java
Learning core java
 
Java
Java Java
Java
 
Python Programming and GIS
Python Programming and GISPython Programming and GIS
Python Programming and GIS
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
 
Python3
Python3Python3
Python3
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Lesson3
Lesson3Lesson3
Lesson3
 
Lesson3
Lesson3Lesson3
Lesson3
 
Functional programming with F#
Functional programming with F#Functional programming with F#
Functional programming with F#
 
ITFT - Java
ITFT - JavaITFT - Java
ITFT - Java
 

Último

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Último (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

NSCoder Swift - An Introduction to Swift

  • 1. NSCoder Swift An introduction to Swift Andreas Blick - @aquarioverde October 18th, 2014
  • 3. Swift • New programming language introduced by Apple on June 2014 at WWDC • Builds on the best of C and Objective-C, without the constraints of C compatibility • Development started by Chris Lattner, who also started the LLVM and Clang project
  • 4. Swift • Safe programming patterns and modern features • Seamless access to all existing Cocoa frameworks • Mix-and-match interoperability with Objective-C
  • 6. Playgrounds • Tool / Feature for • learning • code development • experimentation
  • 7. Playgrounds • Strings • Arrays & dictionaries • Color • Views • Images • … etc
  • 9. Variables & Constants • Defined using var or let keyword • No need to define type • Swift can mostly infer the type • Can contain any unicode character var instrument: String = “guitar” let nrOfSongs = 42 var trackLength = 3.23
  • 10. Strings • Collection of characters that can be accessed easily • Seamlessly bridged: NSString API available • Mutability defined by assignment (var or let) • String interpolation for literals, variables and expressions let instrument = “guitar" ! let music = "play (instrument)" let noise = "play " + instrument
  • 11. Numbers • Integers are stored as Int or UInt • can be written as decimal, binary, octal, hexadecimal • have max and min properties: Int.max • Floating point numbers are stored as Float and Double • can be written as decimal and hexadecimal • Can contain underscores for readability: 7_777.77 • Bool can be true or false
  • 12. Arrays • Stores ordered list of multiple values • Arrays are type specific • Accessed using properties, methods or subscripting var numbers: Array<Int> = Array<Int>() var numbers: [Int] = [Int]() ! numbers = [1,2,3] numbers = [Int](count:7,repeatedValue:0]
  • 13. Dictionaries • Containers that store multiple key-value pairs of the same type • Accessed using properties, methods or subscripting • Assigning nil as a value removes it var numbers:Dictionary<Int,String> = Dictionary<Int,String>() ! numbers = [1:“One”,2:“Two”,3:”Three”]
  • 14. Tuples • Group multiple values of any type into a single compound value • Values can be of any type • Values can be accessed by index • Tuples can have named values let instrument = ("guitar", “strings") println(instrument.0) ! let (name, family) = instrument ! let instrument = (name: "guitar", family: "strings")
  • 15. Loops • for-in loop to iterate using range • for-in loops to iterate over a collection • while / do-while loops if unknown number of iterations for ix in 1…5 { . . . } for var ix = 0; ix < 7; ix++ { . . . } for (key, value) in aDictionary { . . . } ! while ix < 7 { . . . } do { . . . } while ix < 7
  • 16. Conditionals • if / else for simple conditions • switch statements for complex conditions if number == 5 { . . . } ! switch number { case 5: println(“5”) default: println(“default”) }
  • 17. Conditionals - Switch • do not fall through (no break needed) • must be exhaustive (use default:) • support ranges: case 0…7: • support tuples: case (1, 2): • value binding: case (let x, 2): • can use where clause to check additional conditions case (let x, let y) where x == y:
  • 18. Control Transfer Statements • continue • break • return • fallthrough • loops and switches can be labeled to be used with break and continue counter: for i in 1...7 { for j in 1...7 { println("(i) - (j)") if i == 3 { continue counter} } }
  • 19. ?
  • 20. Optionals • Used where a value might be missing by adding a ? sign • Similar to nil in Objective-C, but can be used on any type • non optionals can not be nil • Optionals can implicitly be unwrapped by adding a ! sign (forced unwrapping) let instruments = ["guitar" : 6, "bass": 4, “ukulele”: “8”] let nrOfStrings: Int? = instruments[“guitar"] ! if nrOfStrings != nil { println(nrOfStrings!) } else { . . . }
  • 21. Optionals • Use optional binding to find out if an optional contains a value let instruments = ["guitar" : 6, "bass": 4, “ukulele”: “8”] let nrOfStrings: Int? = instruments[“guitar"] ! if let nrOfStrings = instruments["guitar"] { println(nrOfStrings) } else { . . . } • Use optional chaining when a value might be nil let familyName = guitar.family?.name?
  • 22. func
  • 23. Functions • Functions are blocks of code that execute a specific task • Functions have parameters and can return values - default to void • Parameters can have default values • They should always be placed at the end of the list func play(instrument: String = "guitar") -> String { return "play (instrument)" } ! play(instrument: "drums")
  • 24. Functions • Parameter names are not required when calling a function that has no default values • Functions can return multiple values using tuples • Use # if external and internal parameter names are the same func play(instrument: String) -> (String, volume: Int) { return ("play (instrument)", 7) } play(“guitar").volume ! func play(instrument instr: String) -> String { . . . } func play(#instrument: String) -> String { . . . }
  • 25. Functions • Functions can take a variable number of arguments using variadic parameters • One function can only have one variadic parameter func playInstruments(instruments: String...) -> String { var play = "playing " for instrument in instruments { play += instrument + " " } return play } playInstruments("guitar", "drums", "sax")
  • 26. Functions • Parameters are constants by default and can not be changed • They can be defined as variables using var • Variables parameters can only be modified within a function • To persist a variable outside a function the inout parameter is needed func swapTwoInts(inout a: Int, inout b: Int) { let tmpA = a a = b b = tmpA } var x = 3, y = 7 swapTwoInts(&x, &y)
  • 27. Functions • Functions have a specific function type that can be assigned to variables • They can be passed as parameters and returned by other functions • Functions can be nested func iPlay(player:(String) ->String, song:String) ->String { return player(song) } func playGuitar(song: String) -> String { return "playing (song) on guitar" } let playing = iPlay(playGuitar, "I sat by the ocean")
  • 29. Closures • Closures are self-contained blocks of code that can be passed around • Functions are named closures! • Closures can capture and store references and constants from their surrounding context • Trailing closures can be used for readability • Closures start using the in keyword
  • 30. Closures - Example let playMusic = { println("make some noise”) } ! ! ! func repeat(count:Int, song:String, player:(String)->(String)) { for i in 0..<count { println(player(song)); } } repeat(5, "Even Flow") { (song: String) -> String in return "playing (song)" }
  • 31. class
  • 32. Classes • Classes are program code templates for creating objects, consisting of properties and methods • No need for interface/header files • No need to inherit from any other class • No abstract class support • Compare using the identity operator ===
  • 33. Classes - Properties • Access to properties handled automatically • Properties do not have a corresponding instance variable • Every property needs to have a value assigned • Properties without a setter are read-only • Can have lazy stored properties (lazy) • Type properties are defined using class keyword
  • 34. Classes - Example class Instrument { let type: String var isUsed: Bool = false init(type: String) { self.type = type } var info: String { get { return isUsed ? "used (type)" : "new (type)" } } } ! let electricGuitar = Instrument(type: "guitar")
  • 35. Classes - Properties • Property observers can respond to changes in a properties’ value (willSet & didSet) var isUsed: Bool = false { willSet(willBeUsed) { let msg = (self.isUsed ? "was" : "was not") + " used and “ + (willBeUsed ? "is used now" : "is not used now”) println(msg) } }
  • 36. Classes - Methods • Methods are functions associated with a particular type • Subscripts are special methods (subscript) for accessing members. They can contain any number of input parameters of any type. class Instrument { func play() { println("make some noise") } subscript(ix: Int) -> String { return "model (ix)" } }
  • 37. Initialization • The class needs to be completely initialized before accessing any property or method • Properties that are allowed to have no value can be declared optional using the ? sign • Property observers are NOT called on initialization • Every class must have at least one designated initialiser • Every class can have multiple convenience initializers • Deinitializers can be used for cleaning up
  • 38. Initializer Chaining • Designated initializers must call a designated initializer from their immediate superclass • Convenience initializers must call another initializer available in the same class • Convenience initializers must ultimately end up calling a designated initializer
  • 39. Initialization - Example class Instrument { let type: String var family: String? init(type: String) { self.type = type } convenience init(type: String, family: String) { self.init(type: type) self.family = family } deinit { println("instrument (type) destroyed") } } ! let guitar = Instrument(type: “guitar")
  • 40. Initialization • Closures can be used for initialising complex properties class Some { let some: String = { return "some" }() }
  • 41. Inheritance • Classes can inherit methods, properties from other classes • Initializers are not inherited by default • Initialize own class properties before calling super.init • Overridden methods need override keyword • Methods marked as final can not be overridden • An entire class can be marked as final
  • 42. Inheritance - Example class Guitar : Instrument { init() { super.init(type: "guitar") family = "Strings" } ! override func play() { println("make some noise") } } ! let guitar = Guitar()
  • 44. Structures • Structures are value types, they are always copied, not referenced • Structures can have initializers, methods and properties • Automatically generated memberwise initializer • Structures do not have deinitializers • Array and Dictionary are structures
  • 45. Structures • All properties of constant structures are constant as well • Methods for modifying structure properties need the mutating keyword • Structures do not support inheritance • No type-casting • Type properties are defined using static keyword
  • 46. Enumerations • An enumeration is a complete collection of items • Enumeration values are fully-fledged in their own • Enumerations are first-class types! • Enumerations can have methods & initialisers • Enumeration can have default raw values of the same type
  • 47. Enumerations - Example enum Instrument: Int { case Guitar = 1, Base case Drums, Bongo, Trumpet, Saxophone func description() -> String { switch self { case .Guitar, .Base: return "Strings" case .Trumpet, .Saxophone: return "Wind" default: return "Unknown" } } } let instrument = Instrument.Trumpet instrument.description() instrument.toRaw() let unknown = Instrument.fromRaw(1)?.description()
  • 48. Enumerations • Enumerations can have associated values enum Instrument { case Guitar(nrOfStrings: Int), Base case Drums, Bongo func description() -> String { switch self { case .Guitar(let nrOfStrings): return ("(nrOfStrings)-string guitar") default: return "Unknown" } } } let instrument = Instrument.Guitar(nrOfStrings: 6) instrument.description()
  • 49. ++
  • 50. Extensions • Extensions add new functionality to existing classes, structures, … etc. They are similar to Categories in Objective-C • They can add methods, computed properties, initialisers but no stored properties extension Instrument { func rock() { println("(type) is rocking") } }
  • 51. Protocols • A protocol defines methods and properties a class, struct or enumeration can or must adopt • Existing types can be extended to adopt a protocol • A protocol can inherit from one or more other protocols • Protocol composition can be used to combine protocols • Any protocol can be used as type • Define as @objc for type checking and optional support
  • 52. Protocols - Example @objc protocol Instrument { func play() } ! class Guitar: Instrument { func play() { println("playing guitar") } } ! let items = [Guitar(), NSString()] ! for item in items { if let instrument = item as? Instrument { instrument.play() } }
  • 53. Generics • Generic code enables writing flexible, reusable functions and types func swapTwoValues<T>(inout a: T, inout b: T) { let tmpA = a a = b b = a }
  • 54. Generics • You can define your own generic type • and specify type constraints struct Stack<T: Instrument> { var items = [T]() mutating func push(item: T) { items.append(item) } mutating func pop() { items.removeLast() } } var guitarStack = Stack<Guitar>()
  • 55. References • WWDC 2014 Videos • Apple Books • The Swift Programming Language • Using Swift with Cocoa & Objective-C • Web • https://developer.apple.com/swift/
  • 56. +++
  • 57. ARC • Swift handles memory management using automatic reference counting • Think about relationship between object instead of memory • Avoid strong reference cycles by using weak or unowned references
  • 58. Assertions • Use assertions whenever a condition has the potential to be false, but must be true • End code execution let age = -3 assert(age >= 0, "age can no be less than 0")
  • 59. Thank you! Andreas Blick - @aquarioverde