SlideShare ist ein Scribd-Unternehmen logo
1 von 87
Downloaden Sie, um offline zu lesen
Minh Chuong Huynh/ iOS internship
chuong.huynh@rainmaker-labs.com / +84 962 332 808
SWIFT 3
111/2/2016
THE BASIC OF SWIFT
11/2/2016 2
 Swift combines the best of C and Objective-C.
 Semi-colon (;) following each statement is not required
 Multiline comments can be nested within other multiline
comments
Introduction
11/2/2016 3
 Basic types and Collection types.
 Key words: var, let
 Constants are used more often.
 Other customize types: Int8, UInt16, Int32, UInt64, 0b..., 0o....,
0x....
 1_000_000.000_000_1 = 1000000.0000001
 typealias <alias> = <ExistedType>
 Swift is a type-safe language
Constants and variables
11/2/2016 4
 Define variable and constant type to make code clear.
 Unnecessary: Swift would define the type of variables and
constants by their init values.
Type antonation
11/2/2016 5
 Values of optional variables or constants may be absent (= nil):
<type> ?
 Must be unwrapped “!” when getting the value.
 Implicitly Unwrapped Optionals: unnecessary to unwrap
Optional
11/2/2016 6
 Swift has almost basic operators in C/C++, even ternary a ? b :
c
 Modulo (%) also operate with floating-point numbers.
 Range operators: a...b, a..<b
 ‘=‘: not return value
 ‘===‘: test whether two object references both refer to the
same object instance.
Basic operators
11/2/2016 7
 A group of mixed types.
 Each element can be named and we can access elements by
these names.
 Tuples are compared by comparing each element respectively.
Tuple
11/2/2016 8
STRINGS AND CHARACTERS
11/2/2016 9
 isEmpty
 characters
 characters.count
 startIndex
 endIndex
 characters.indices
Some properties
11/2/2016 10
 var <newString> = String(<anotherString>)
 append(<character>)
 +=, +
 index(before:) and index(after:)
 index(_,offsetBy:)
 insert(_,at:)
 insert(contentsOf:, at: )
 remove(at:)
 removeSubrange(<range>)
 hasPrefix(<string>) and hasSuffix(<string>)
Some methods
11/2/2016 11
 “(<variable or constant>)....”
String interpolation
11/2/2016 12
 u{n}: where n is a 1–8 digit hexadecimal number with a value
equal to a valid Unicode code point.
Unicode
11/2/2016 13
COLLECTION TYPES
11/2/2016 14
 Elements: same type + ordered
 Define: Array<type>() or [type]()
 Array(repeating: <default value>, count: <size>)
 “+”: combine two arrays
 “[]”: to make array empty
 Access element: [<index>]
 Properties: count, isEmpty
 Methods: append(<element>), insert(at:), remove(at:),
removeLast()
Array
11/2/2016 15
 Elements: distinct values of the same type (hashable type) + no
ordered
 Define: Set<type>() or [type]()
 “[]”: to make set empty
 Properties: count, isEmpty
 Methods: insert(<element>), remove(<element>), removeAll(),
sorted(), contains(<element>),
Set
11/2/2016 16
 Fundamental Set Operators:
==
intersection(<set>),
symmetricDifference(<set>),
union(<set>),
subtracting(<set>),
isSubset(of: <set>),
isSuperset(of:<set>),
isStrictSubset(of:<set>),
isStrictSuperset(of:<set>),
isDisjoint(with:<set>)
Set
11/2/2016 17
 Like dictionary in Python
 Define: Dictionary<keyType, valueType>() or
[keyType:valueType]()
 Properties: isEmpty, keys, values
 Methods: updateValue( <new value>, forKey: <key>),
removeValue(forKey: <key>)
Dictionary
11/2/2016 18
CONTROL FLOWS
11/2/2016 19
 for <item> in <range or list>{}
(like Python)
 for var index = <init value>; <stopping condition>; <index increasement>{}
(like C/C++)
For-In
11/2/2016 20
 while: check the condition at the start of each through the loop.
 repeat – while: check the condition at the end of each pass
through the loop.
While; repeat-while
11/2/2016 21
 like if-else in C/C++ or Python
If-else
11/2/2016 22
 break: unnecessary
 Each case must contain at least one
executable statement.
 Compound case: combine several values
to a single case.
 Each case can receive range.
 Tuple: we use “_” to match any possible
value in switch-case
 Switch case can bind the value or values it matches to
temporary constants or variables.
 where :to check for additional conditions.
Switch
11/2/2016 23
 continue, break
 fallthrough
 Labeled Statement
 guard
Control transfer statements
11/2/2016 24
Checking API availability
11/2/2016 25
FUNCTIONS
11/2/2016 26
 func <function name> (<argument label> <parameter name>: <type>,…..) -> <return
type>{}
Defining and calling
11/2/2016 27
 Default argument labels and “_” labels
 Default value for parameter
 Variadic parameter: same-type parameters
 inout and &
Argument labels and parameter names
11/2/2016 28
 (<type of parameter 1>, <type of parameter 2>,…) -> <return type>
Ex: ()-> Void
 Can be used as parameter type or return type
Function types
11/2/2016 29
 Define functions inside the bodies of other functions
Nested functions
11/2/2016 30
BLOCKS IN C/C++
CLOSURES
11/2/2016 31
 Shorter version of function:
{ (parameters) -> return type in
statements
}
 Single-expression closure:
{ <parameter>,… in <return value> }
 Shorthand argument names: $0, $1, $2...
Ex: sorted(by: { $0 > $1 }) // ~ { s1, s2 in s1 > s2}
Closure expressions
11/2/2016 32
 When assigning a function or a closure to a constant or a variable, that
constant or variable is a reference to the function or closure.
Reference types
11/2/2016 33
 When the closure is passed as an argument to the function, but
is called after the function returns.
 Adding @escaping before argument name
Escaping closures
11/2/2016 34
 Adding @autoclosure before closure parameter
 The codes inside the closures (as parameters of function) will not be really
executed until it's called again in the body of the function
Autoclosures
11/2/2016 35
ENUMERATIONS
11/2/2016 36
enum <name of enumeration>{
case <definition 1> // or case <def 1>, <def 2>
case <definition 2>
…
}
 Different with C/C++
Syntax
11/2/2016 37
 In switch statement
 Associated values:
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
 Raw values:
enum <name of enumeration>: <type>{
case <definition 1> = <value>
case <definition 2> = <value>
…
}
Others
11/2/2016 38
 Implicitly assigned raw values
 <name of enum> (rawValue: <value>): check enumeration
the value
 Recursive enumerations:
Others
11/2/2016 39
CLASSES & STRUCTURES
11/2/2016 40
 Structure have an automatically-generated memberwise
initializer.
 Struct is value ype
 Class is reference type
 To compare the references: === or !==
 Structure types in Swift: String, Array, Dictionary
 Classes types in Swift: NSString, NSArray, NSDictionary
Compare with C/C++
11/2/2016 41
PROPERTIES
11/2/2016 42
 The property whose initial value is not calculated until the first
time it is used.
 Global constants and variables are always computed lazily.
 Keyword: lazy
Lazy stored properties
11/2/2016 43
Computed
properties
11/2/2016 44
 Remove set
Read-only computed properties
11/2/2016 45
 willSet: is called just before the value is stored, with newValue
(a default parameter)
 didSet: is called imediately after the new value is stored, with
oldValue (a default parameter)
Property observers
11/2/2016 46
 Keyword: static, class
Static properties
11/2/2016 47
METHODS
11/2/2016 48
 self: ~ this(C++) or self(Python)
 mutating: To change value of properties in structure or
enumeration by methods
11/2/2016 49
SUBSCRIPTS
11/2/2016 50
Syntax
11/2/2016 51
Can use more than one parameter
INHERITANCE
11/2/2016 52
 like C++’s inheritance
 override methods and properties (get and set)
 super: excute superclass’s methods or properties
 final: preventing a method, property or subscript from being
overriden
11/2/2016 53
Construction in C++
INITIALIZATION
11/2/2016 54
 Init is a mutating function.
 Swift also provides a default initializer.
 Write required before the definition of a class initializer to
indicate that every subclass of the class must implement that
initializer.
11/2/2016 55
Designated and convenience
11/2/2016 56
 1: If your subclass doesn’t define any designated initializers, it
automatically inherits all of its superclass designated initializers.
 2: If your subclass provides an implementation of all of its
superclass designated initializers—either by inheriting them as
per rule 1, or by providing a custom implementation as part of
its definition—then it automatically inherits all of the superclass
convenience initializers.
Automatic initializer inheritance
11/2/2016 57
 init? which can return nil if the init is unsuccessful.
 This can be override in subclass (and also can be override to a subclass
nonfailable initializer).
Failable initializers
11/2/2016 58
Destruction in C++
“deinit”
DEINITIALIZATION
11/2/2016 59
AUTOMATIC REFERENCE
COUTING (ARC)
11/2/2016 60
 ARC automatically frees up the memory used by class instances
when those instances are no longer needed
 Create a new instance --> allocate a chunk of memory to store
information.
 Destruct instance --> frees up the memory used by that instance to
used for other purposes.
 ARC will not deallocate an instance as long as at least one active
reference to that instance still exists.
Concept
11/2/2016 61
Strong reference cycles between class
instances
11/2/2016 62
=> MEMORY LEAK
Strong reference cycles between class
instances (Solving)
11/2/2016 63
WEAK REFERENCE
Strong reference cycles between class
instances (Solving)
11/2/2016 64
UNOWNED REFERENCE
 The closures capture self, which means that it holds a strong
reference
Strong reference cycles for closures
11/2/2016 65
Strong reference cycles for closures
(Solving)
11/2/2016 66
 defines the rules to use when capturing one or more reference
types within the closure’s body.
OPTIONAL CHAINING
11/2/2016 67
11/2/2016 68
ERROR HANDLING
11/2/2016 69
11/2/2016 70
Coverting errors to optional values
11/2/2016 71
 Disabling error propagation: using try!
 defer: execute a set of statements just before code execution
leaves the current block of code.
11/2/2016 72
TYPE CASTING
11/2/2016 73
 is: check whether an instance is of a certain subclass type
 as? and as! : used to downcast to the subclass. Using as?
When you not sure if the downcast will succeed and as! only
when you are sure that the downcast will always succeed.
 Any:an instance of any type at all, including function types.
 AnyObject: an instance of any class type.
11/2/2016 74
Add new functionality (even init) to an existing class, structure, enumeration,
or protocol type
EXTENSIONS
11/2/2016 75
11/2/2016 76
interface
PROTOCOL
11/2/2016 77
 list of methods and properties to define an interface
11/2/2016 78
 associatedtype: a placeholder name to a type that is used as
part of the protocol.
 To make the connection between 2 classes.
Ex: when the profile view controller need to update after we edit
some details.
 Create a delegate protocol that defines the responsibilities of
the delegate.
 Add a delegate property in the delegating class to keep track
of the delegate.
 Adopt and implement the delegate methods in the delegate
class.
 Call the delegate from the delegating object.
Delegate pattern design
11/2/2016 79
11/2/2016 80
Typedef in C/C++
GENERICS
11/2/2016 81
11/2/2016 82
ACCESS CONTROL
11/2/2016 83
11/2/2016 84
ADVANCE OPERATORS
11/2/2016 85
11/2/2016 86
11/2/2016 87
THE END

Weitere ähnliche Inhalte

Was ist angesagt?

Swift internals
Swift internalsSwift internals
Swift internalsJung Kim
 
JavaScript 101 - Class 1
JavaScript 101 - Class 1JavaScript 101 - Class 1
JavaScript 101 - Class 1Robert Pearce
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Hardened JavaScript
Hardened JavaScriptHardened JavaScript
Hardened JavaScriptKrisKowal2
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about LambdasRyan Knight
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developersjessitron
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 
Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran Khoa
 
PLSQL CURSOR
PLSQL CURSORPLSQL CURSOR
PLSQL CURSORArun Sial
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 

Was ist angesagt? (20)

Swift internals
Swift internalsSwift internals
Swift internals
 
JavaScript 101 - Class 1
JavaScript 101 - Class 1JavaScript 101 - Class 1
JavaScript 101 - Class 1
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Hardened JavaScript
Hardened JavaScriptHardened JavaScript
Hardened JavaScript
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about Lambdas
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developers
 
A Taste of Dotty
A Taste of DottyA Taste of Dotty
A Taste of Dotty
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
PLSQL CURSOR
PLSQL CURSORPLSQL CURSOR
PLSQL CURSOR
 
Kotlin
KotlinKotlin
Kotlin
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 

Andere mochten auch

Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Korhan Bircan
 
ios_summit_2016_korhan
ios_summit_2016_korhanios_summit_2016_korhan
ios_summit_2016_korhanKorhan Bircan
 
Improving apps with iOS 10 notifications (do iOS 2016)
Improving apps with iOS 10 notifications (do iOS 2016)Improving apps with iOS 10 notifications (do iOS 2016)
Improving apps with iOS 10 notifications (do iOS 2016)Donny Wals
 
WWDC 2016
WWDC 2016WWDC 2016
WWDC 2016PiXeL16
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0Korhan Bircan
 
WWDC 2016 Personal Recollection
WWDC 2016 Personal RecollectionWWDC 2016 Personal Recollection
WWDC 2016 Personal RecollectionMasayuki Iwai
 
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdkI os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdk政斌 楊
 
iOS 10 - What you need to know
iOS 10 - What you need to knowiOS 10 - What you need to know
iOS 10 - What you need to knowThe App Business
 
Swift 3 を書くときに知っておきたい API デザインガイドライン #love_swift #akibaswift
Swift 3 を書くときに知っておきたい API デザインガイドライン #love_swift #akibaswiftSwift 3 を書くときに知っておきたい API デザインガイドライン #love_swift #akibaswift
Swift 3 を書くときに知っておきたい API デザインガイドライン #love_swift #akibaswiftTomohiro Kumagai
 

Andere mochten auch (12)

Korhan bircan
Korhan bircanKorhan bircan
Korhan bircan
 
Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)
 
ios_summit_2016_korhan
ios_summit_2016_korhanios_summit_2016_korhan
ios_summit_2016_korhan
 
Improving apps with iOS 10 notifications (do iOS 2016)
Improving apps with iOS 10 notifications (do iOS 2016)Improving apps with iOS 10 notifications (do iOS 2016)
Improving apps with iOS 10 notifications (do iOS 2016)
 
WWDC 2016
WWDC 2016WWDC 2016
WWDC 2016
 
Swift 3
Swift   3Swift   3
Swift 3
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
iOS 10
iOS 10iOS 10
iOS 10
 
WWDC 2016 Personal Recollection
WWDC 2016 Personal RecollectionWWDC 2016 Personal Recollection
WWDC 2016 Personal Recollection
 
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdkI os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
 
iOS 10 - What you need to know
iOS 10 - What you need to knowiOS 10 - What you need to know
iOS 10 - What you need to know
 
Swift 3 を書くときに知っておきたい API デザインガイドライン #love_swift #akibaswift
Swift 3 を書くときに知っておきたい API デザインガイドライン #love_swift #akibaswiftSwift 3 を書くときに知っておきたい API デザインガイドライン #love_swift #akibaswift
Swift 3 を書くときに知っておきたい API デザインガイドライン #love_swift #akibaswift
 

Ähnlich wie SWIFT 3

Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerApache Traffic Server
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Getting started with c++.pptx
Getting started with c++.pptxGetting started with c++.pptx
Getting started with c++.pptxAkash Baruah
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat SheetLaura Hughes
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptxMrMudassir
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash courseHolden Karau
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
[Apostila] programação arduíno brian w. evans
[Apostila] programação arduíno   brian w. evans[Apostila] programação arduíno   brian w. evans
[Apostila] programação arduíno brian w. evansWeb-Desegner
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
 
Stata cheatsheet programming
Stata cheatsheet programmingStata cheatsheet programming
Stata cheatsheet programmingTim Essam
 
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its ModuleMuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its ModuleJitendra Bafna
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
Java And Jav Rename To Bpplustree Class Assumptions
Java And Jav Rename To Bpplustree Class AssumptionsJava And Jav Rename To Bpplustree Class Assumptions
Java And Jav Rename To Bpplustree Class AssumptionsSheena Crouch
 

Ähnlich wie SWIFT 3 (20)

Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
Day 2
Day 2Day 2
Day 2
 
Python basics - for bigginers
Python basics - for bigginersPython basics - for bigginers
Python basics - for bigginers
 
Getting started with c++.pptx
Getting started with c++.pptxGetting started with c++.pptx
Getting started with c++.pptx
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat Sheet
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptx
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
[Apostila] programação arduíno brian w. evans
[Apostila] programação arduíno   brian w. evans[Apostila] programação arduíno   brian w. evans
[Apostila] programação arduíno brian w. evans
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
Stata cheatsheet programming
Stata cheatsheet programmingStata cheatsheet programming
Stata cheatsheet programming
 
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its ModuleMuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its Module
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Java And Jav Rename To Bpplustree Class Assumptions
Java And Jav Rename To Bpplustree Class AssumptionsJava And Jav Rename To Bpplustree Class Assumptions
Java And Jav Rename To Bpplustree Class Assumptions
 
C#ppt
C#pptC#ppt
C#ppt
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 

SWIFT 3

  • 1. Minh Chuong Huynh/ iOS internship chuong.huynh@rainmaker-labs.com / +84 962 332 808 SWIFT 3 111/2/2016
  • 2. THE BASIC OF SWIFT 11/2/2016 2
  • 3.  Swift combines the best of C and Objective-C.  Semi-colon (;) following each statement is not required  Multiline comments can be nested within other multiline comments Introduction 11/2/2016 3
  • 4.  Basic types and Collection types.  Key words: var, let  Constants are used more often.  Other customize types: Int8, UInt16, Int32, UInt64, 0b..., 0o...., 0x....  1_000_000.000_000_1 = 1000000.0000001  typealias <alias> = <ExistedType>  Swift is a type-safe language Constants and variables 11/2/2016 4
  • 5.  Define variable and constant type to make code clear.  Unnecessary: Swift would define the type of variables and constants by their init values. Type antonation 11/2/2016 5
  • 6.  Values of optional variables or constants may be absent (= nil): <type> ?  Must be unwrapped “!” when getting the value.  Implicitly Unwrapped Optionals: unnecessary to unwrap Optional 11/2/2016 6
  • 7.  Swift has almost basic operators in C/C++, even ternary a ? b : c  Modulo (%) also operate with floating-point numbers.  Range operators: a...b, a..<b  ‘=‘: not return value  ‘===‘: test whether two object references both refer to the same object instance. Basic operators 11/2/2016 7
  • 8.  A group of mixed types.  Each element can be named and we can access elements by these names.  Tuples are compared by comparing each element respectively. Tuple 11/2/2016 8
  • 10.  isEmpty  characters  characters.count  startIndex  endIndex  characters.indices Some properties 11/2/2016 10
  • 11.  var <newString> = String(<anotherString>)  append(<character>)  +=, +  index(before:) and index(after:)  index(_,offsetBy:)  insert(_,at:)  insert(contentsOf:, at: )  remove(at:)  removeSubrange(<range>)  hasPrefix(<string>) and hasSuffix(<string>) Some methods 11/2/2016 11
  • 12.  “(<variable or constant>)....” String interpolation 11/2/2016 12
  • 13.  u{n}: where n is a 1–8 digit hexadecimal number with a value equal to a valid Unicode code point. Unicode 11/2/2016 13
  • 15.  Elements: same type + ordered  Define: Array<type>() or [type]()  Array(repeating: <default value>, count: <size>)  “+”: combine two arrays  “[]”: to make array empty  Access element: [<index>]  Properties: count, isEmpty  Methods: append(<element>), insert(at:), remove(at:), removeLast() Array 11/2/2016 15
  • 16.  Elements: distinct values of the same type (hashable type) + no ordered  Define: Set<type>() or [type]()  “[]”: to make set empty  Properties: count, isEmpty  Methods: insert(<element>), remove(<element>), removeAll(), sorted(), contains(<element>), Set 11/2/2016 16
  • 17.  Fundamental Set Operators: == intersection(<set>), symmetricDifference(<set>), union(<set>), subtracting(<set>), isSubset(of: <set>), isSuperset(of:<set>), isStrictSubset(of:<set>), isStrictSuperset(of:<set>), isDisjoint(with:<set>) Set 11/2/2016 17
  • 18.  Like dictionary in Python  Define: Dictionary<keyType, valueType>() or [keyType:valueType]()  Properties: isEmpty, keys, values  Methods: updateValue( <new value>, forKey: <key>), removeValue(forKey: <key>) Dictionary 11/2/2016 18
  • 20.  for <item> in <range or list>{} (like Python)  for var index = <init value>; <stopping condition>; <index increasement>{} (like C/C++) For-In 11/2/2016 20
  • 21.  while: check the condition at the start of each through the loop.  repeat – while: check the condition at the end of each pass through the loop. While; repeat-while 11/2/2016 21
  • 22.  like if-else in C/C++ or Python If-else 11/2/2016 22
  • 23.  break: unnecessary  Each case must contain at least one executable statement.  Compound case: combine several values to a single case.  Each case can receive range.  Tuple: we use “_” to match any possible value in switch-case  Switch case can bind the value or values it matches to temporary constants or variables.  where :to check for additional conditions. Switch 11/2/2016 23
  • 24.  continue, break  fallthrough  Labeled Statement  guard Control transfer statements 11/2/2016 24
  • 27.  func <function name> (<argument label> <parameter name>: <type>,…..) -> <return type>{} Defining and calling 11/2/2016 27
  • 28.  Default argument labels and “_” labels  Default value for parameter  Variadic parameter: same-type parameters  inout and & Argument labels and parameter names 11/2/2016 28
  • 29.  (<type of parameter 1>, <type of parameter 2>,…) -> <return type> Ex: ()-> Void  Can be used as parameter type or return type Function types 11/2/2016 29
  • 30.  Define functions inside the bodies of other functions Nested functions 11/2/2016 30
  • 32.  Shorter version of function: { (parameters) -> return type in statements }  Single-expression closure: { <parameter>,… in <return value> }  Shorthand argument names: $0, $1, $2... Ex: sorted(by: { $0 > $1 }) // ~ { s1, s2 in s1 > s2} Closure expressions 11/2/2016 32
  • 33.  When assigning a function or a closure to a constant or a variable, that constant or variable is a reference to the function or closure. Reference types 11/2/2016 33
  • 34.  When the closure is passed as an argument to the function, but is called after the function returns.  Adding @escaping before argument name Escaping closures 11/2/2016 34
  • 35.  Adding @autoclosure before closure parameter  The codes inside the closures (as parameters of function) will not be really executed until it's called again in the body of the function Autoclosures 11/2/2016 35
  • 37. enum <name of enumeration>{ case <definition 1> // or case <def 1>, <def 2> case <definition 2> … }  Different with C/C++ Syntax 11/2/2016 37
  • 38.  In switch statement  Associated values: enum Barcode { case upc(Int, Int, Int, Int) case qrCode(String) }  Raw values: enum <name of enumeration>: <type>{ case <definition 1> = <value> case <definition 2> = <value> … } Others 11/2/2016 38
  • 39.  Implicitly assigned raw values  <name of enum> (rawValue: <value>): check enumeration the value  Recursive enumerations: Others 11/2/2016 39
  • 41.  Structure have an automatically-generated memberwise initializer.  Struct is value ype  Class is reference type  To compare the references: === or !==  Structure types in Swift: String, Array, Dictionary  Classes types in Swift: NSString, NSArray, NSDictionary Compare with C/C++ 11/2/2016 41
  • 43.  The property whose initial value is not calculated until the first time it is used.  Global constants and variables are always computed lazily.  Keyword: lazy Lazy stored properties 11/2/2016 43
  • 45.  Remove set Read-only computed properties 11/2/2016 45
  • 46.  willSet: is called just before the value is stored, with newValue (a default parameter)  didSet: is called imediately after the new value is stored, with oldValue (a default parameter) Property observers 11/2/2016 46
  • 47.  Keyword: static, class Static properties 11/2/2016 47
  • 49.  self: ~ this(C++) or self(Python)  mutating: To change value of properties in structure or enumeration by methods 11/2/2016 49
  • 51. Syntax 11/2/2016 51 Can use more than one parameter
  • 53.  like C++’s inheritance  override methods and properties (get and set)  super: excute superclass’s methods or properties  final: preventing a method, property or subscript from being overriden 11/2/2016 53
  • 55.  Init is a mutating function.  Swift also provides a default initializer.  Write required before the definition of a class initializer to indicate that every subclass of the class must implement that initializer. 11/2/2016 55
  • 57.  1: If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.  2: If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers. Automatic initializer inheritance 11/2/2016 57
  • 58.  init? which can return nil if the init is unsuccessful.  This can be override in subclass (and also can be override to a subclass nonfailable initializer). Failable initializers 11/2/2016 58
  • 61.  ARC automatically frees up the memory used by class instances when those instances are no longer needed  Create a new instance --> allocate a chunk of memory to store information.  Destruct instance --> frees up the memory used by that instance to used for other purposes.  ARC will not deallocate an instance as long as at least one active reference to that instance still exists. Concept 11/2/2016 61
  • 62. Strong reference cycles between class instances 11/2/2016 62 => MEMORY LEAK
  • 63. Strong reference cycles between class instances (Solving) 11/2/2016 63 WEAK REFERENCE
  • 64. Strong reference cycles between class instances (Solving) 11/2/2016 64 UNOWNED REFERENCE
  • 65.  The closures capture self, which means that it holds a strong reference Strong reference cycles for closures 11/2/2016 65
  • 66. Strong reference cycles for closures (Solving) 11/2/2016 66  defines the rules to use when capturing one or more reference types within the closure’s body.
  • 71. Coverting errors to optional values 11/2/2016 71
  • 72.  Disabling error propagation: using try!  defer: execute a set of statements just before code execution leaves the current block of code. 11/2/2016 72
  • 74.  is: check whether an instance is of a certain subclass type  as? and as! : used to downcast to the subclass. Using as? When you not sure if the downcast will succeed and as! only when you are sure that the downcast will always succeed.  Any:an instance of any type at all, including function types.  AnyObject: an instance of any class type. 11/2/2016 74
  • 75. Add new functionality (even init) to an existing class, structure, enumeration, or protocol type EXTENSIONS 11/2/2016 75
  • 78.  list of methods and properties to define an interface 11/2/2016 78  associatedtype: a placeholder name to a type that is used as part of the protocol.
  • 79.  To make the connection between 2 classes. Ex: when the profile view controller need to update after we edit some details.  Create a delegate protocol that defines the responsibilities of the delegate.  Add a delegate property in the delegating class to keep track of the delegate.  Adopt and implement the delegate methods in the delegate class.  Call the delegate from the delegating object. Delegate pattern design 11/2/2016 79

Hinweis der Redaktion

  1. nil cannot be used with non-optional constants and variables.
  2. isEmpty: test the string whether or not is empty. characters: get a collection of characters in the string. characters.count: get the number of characters in string. startIndex: get the starting index. endIndex: get the ending index. characters.indices: get a collection of indexes of individual characters in a string.
  3. var <newString> = String(<anotherString>): declare and copy a value of an existed string to a new string. append(<character>): add a character to the end of string. +=, +: are used to multate a string. index(before:) and index(after:): access the indices before and after a given index. index(_,offsetBy:): access an index farther away from the given index. insert(_,at:): insert a single character into a string at a specified index. insert(contentsOf:, at: ): insert the contents of another string at a specified index. remove(at:): remove a single character from a string at a specified index. removeSubrange(<range>): remove a substring at a specified range. hasPrefix(<string>) and hasSuffix(<string>): check whether a string has a particular string prefix or suffix. They return a Boolean value.
  4. Double Float, Float80 Int, Int8, Int16, Int32, Int64 UInt, UInt8, UInt16, UInt32, UInt64 String
  5. Use the intersection(_:) method to create a new set with only the values common to both sets. Use the symmetricDifference(_:) method to create a new set with values in either set, but not both. Use the union(_:) method to create a new set with all of the values in both sets. Use the subtracting(_:) method to create a new set with values not in the specified set. Use the “is equal” operator (==) to determine whether two sets contain all of the same values. Use the isSubset(of:) method to determine whether all of the values of a set are contained in the specified set. Use the isSuperset(of:) method to determine whether a set contains all of the values in a specified set. Use the isStrictSubset(of:) or isStrictSuperset(of:) methods to determine whether a set is a subset or superset, but not equal to, a specified set. Use the isDisjoint(with:) method to determine whether two sets have any values in common.
  6. Fallthrough: jump to the statement in the next case in switch-case, noting that the condition of the next case is not checked. Labeled Statement: is used to name a statement and called after continue or break to continue or end the execution of the labeled statement. Guard: The combination of assert and if statement: checking for the condition you want. If the condition is not met, guard's else statement is run: checking for bad cases early, making your function more readable and easier to maintain.
  7. ERROR TYPE: In Swift, errors are represented by values of types that conform to the Error protocol, Swift enumerations are particularly well suited to modeling a group of related error conditions, with associated values allowing for additional information about the nature of an error to be communicated THROWING AN ERROR: Throwing an error lets you indicate that something unexpected happened and the normal flow of execution can’t continue. You use a throw statement to throw an error. THROWING FUNCTIONS: To indicate that a function, method, or initializer can throw an error, you write the throws keyword in the function’s declaration after its parameters. HANDLING ERRORS: