swift tutorial part 2. the complete guide for swift programming language

43
By: Hossam Ghareeb [email protected] Part 2 The Complete Guide For Programming Language

Upload: hossam-ghareeb

Post on 04-Jul-2015

1.201 views

Category:

Software


3 download

DESCRIPTION

Part 2 of The complete guide for Swift programming language. In this part we introduced: Classes Inheritance Computed Properties Type Level Lazy Property Observers Structures Equality Vs Identity Type Casting Any Vs AnyObject Protocols Delegation Extensions Generics Operator Functions

TRANSCRIPT

Page 1: Swift Tutorial Part 2. The complete guide for Swift programming language

By: Hossam [email protected]

Part 2

The Complete Guide For

Programming Language

Page 2: Swift Tutorial Part 2. The complete guide for Swift programming language

Contents

● Classes

● Inheritance

● Computed Properties

● Type Level

● Lazy

● Property Observers

● Structures

● Equality Vs Identity

● Type Casting

● Any Vs AnyObject

● Protocols

● Delegation

● Extensions

● Generics

● Operator Functions

Page 3: Swift Tutorial Part 2. The complete guide for Swift programming language

Classes

● Swift is Object oriented language and you can create your own custom classes .

● In Swift, you don't have to write interface and implementation files like Obj-C. Just one file and Swift will care about everything.

● You can create classes with the keyword "class" and then you can list all your attributes and methods.

● In creating new instances of your class, you don't need for keywords like new, alloc, init . Just the class name and empty parentheses ().

● Class instances are passed by reference.

Page 4: Swift Tutorial Part 2. The complete guide for Swift programming language

Classes

● Student class example

Page 5: Swift Tutorial Part 2. The complete guide for Swift programming language

Classes● As in previous example, you can list easily your attributes. In Swift

class, attributes should have one of 3 conditions :○ Defined with initial value like firstName.○ Defined with Optional value like middleName.○ Initialized inside the default initializer lastName.

● init() function is used to make a default initializer for the class.

● You can create multiple initializers that accept parameters.

● Methods are created easily like functions syntax.

● Deinitializer using deinit() can be use to free up any resources that this instance holds them.

Page 6: Swift Tutorial Part 2. The complete guide for Swift programming language

Classes

Page 7: Swift Tutorial Part 2. The complete guide for Swift programming language

Inheritance

● In Swift, a class can inherit from another class using ":"

● Unlike Objective-C, a Swift class doesn't inherit from base class or anything by default.

● Calling super is required when overriding any initializer from super class.

● Use the keyword override when you want to override a function from your super class.

● Use the keyword final before a class name to prevent it from being inherited. Also you can use it before a function name to prevent it from being overridden.

Page 8: Swift Tutorial Part 2. The complete guide for Swift programming language

Inheritance

Page 9: Swift Tutorial Part 2. The complete guide for Swift programming language

Computed Properties

● All previous properties are called "stored properties", because we store values on them. In Swift, we have other type called "Computed properties" as these properties don't store anything but they compute the value from other properties.

● Open curly braces { } after property to write the code of computing. You can do this if you wanna getter only.

● If you want to override setter , you will type code inside set{ } and getter inside get { }

● If you didn't provide setter set { } the property will be considered as readOnly

● A value called newValue will be available in setter to be used.

Page 10: Swift Tutorial Part 2. The complete guide for Swift programming language

Computed Properties

Page 11: Swift Tutorial Part 2. The complete guide for Swift programming language

Type Level

● TypeLevel in Swift is a way to define properties and methods called by Type itself, not by instance (like class methods)

● Write the keyword class before attribute or function to make it as type level.

Page 12: Swift Tutorial Part 2. The complete guide for Swift programming language

Lazy

● Lazy keyword is used before var attributes (var only not let) to mark it as lazy initialized. It means that, initialize it only when it will be used. So when you try to access this attribute it will be initialized to be used, otherwise it will remain nil.

Page 13: Swift Tutorial Part 2. The complete guide for Swift programming language

Property Observers● Suppose you want to keep track about every change in a property

in a class. Swift gives you an awesome way to track it before and after change using willSet { } and didSet { }

● In next example, we wanna keep track on player score. Also we have a limit 1000 points in score, so if the score is set to value more than 1000, it will remain 1000.

● newValue is given in willSet { } and oldValue is given in didSet { }

● If you want to change the names of newValue and oldValue do the following =>

Page 14: Swift Tutorial Part 2. The complete guide for Swift programming language

Property Observers

Page 15: Swift Tutorial Part 2. The complete guide for Swift programming language

Structures● Structures and classes are very similar in Swift. Structures can

define properties, methods, define initializers, computed properties and conform to protocols.

● Structures don't have Inheritance, Type Casting or Deinitializers

● String, Array and Dictionary are implemented as Structures!

● Structures are value types, so they are passed by value . When you assigned it to another value, the struct value is copied.

● Structures have an automatically memberwise initializers to initialize your properties

Page 16: Swift Tutorial Part 2. The complete guide for Swift programming language

StructuresCheck example:

Page 17: Swift Tutorial Part 2. The complete guide for Swift programming language

Equality Vs Identity

● We always used to use "==" for checking in equality. In Swift there is another thing called Identity "===" and "!==". Its used only with Objects to check if they point to the same object.

● Identity is used only with objects. You cannot use it with structures.

● Two objects can be equal but not identical. Because they may have the same values but they are different objects

Page 18: Swift Tutorial Part 2. The complete guide for Swift programming language

Equality Vs Identity

Page 19: Swift Tutorial Part 2. The complete guide for Swift programming language

Type Casting

● TypeCasting is a way for type checking and downcasting objects.

check this:

we created array of controls. As we know that Array should be typed, Swift compiler found that they are different in type, so it had to look for their common superclass which is UIView so this array is of type UIView.

● We will use is keyword to check the type of object, check example:

Page 20: Swift Tutorial Part 2. The complete guide for Swift programming language

Type Casting

● If I wanted to use component, you can't because its UIView type. To use it we can cast it to UILabel using as keyword. Use as if you really sure that the downcast will work because it will give runtime error if not.

● Use as? if you are not sure, it will return nil if downcast fails

Page 21: Swift Tutorial Part 2. The complete guide for Swift programming language

Type CastingIn this example you will see how to use as?

Page 22: Swift Tutorial Part 2. The complete guide for Swift programming language

Any Vs AnyObject● In Swift you can set the type of object to AnyObject, its equivalent

to id in Objective-C.

● You can use it with arrays or dictionaries or anything. AnyObject holds only Objects (class type references).

● Any can be anything like objects, tuples, closures,.....

● Use is, as and as? to downcast and check the type of Any or AnyObject

Check examples:

Page 23: Swift Tutorial Part 2. The complete guide for Swift programming language

Any Vs AnyObject

objects array has String, Label and Date !! so the compiler will try to get their common super class of them, it will ended by "AnyObject". But someone can say, "55 & true are not objects ???". In fact, they are because in runtime Swift bridged them to Foundation classes. So String will be bridged to NSString, Int & Bools will be bridged to NSNumber. The common superclass for them now will be NSObject which is equivalent to AnyObject in Swift

● AnyObject is like id, you can send any message to them (call any function), but in runtime will give error is doesn't respond to this message. check example:

Page 24: Swift Tutorial Part 2. The complete guide for Swift programming language

Any Vs AnyObject

Here in runtime we got this error, because obj became of type Number which doesn't respond to this method. So to avoid this you have to use is as or as? to help check the type before using the object.

Page 25: Swift Tutorial Part 2. The complete guide for Swift programming language

Protocols● Protocols can easily be created using keyword protocol.

● Methods and properties can be listed between { } to be implemented by class which conforms to this protocol

● Protocol properties can be readonly by adding {get} OR settable and gettable by adding {get set} .

● Classes can conform to multiple protocols.

● Structures and enumerations can conform to protocols.

● You can use protocols as types in variables, properties, function return type and so on.

● Protocols can inherit one or more protocols.

Page 26: Swift Tutorial Part 2. The complete guide for Swift programming language

Protocols example:

Page 27: Swift Tutorial Part 2. The complete guide for Swift programming language

Protocols

● Add the keyword class in inheritance list after ':' to limit protocol adoption to classes only (No structures or enumerations)

● When using protocols with structures and enumerations, add the keyword mutating before func to indicate that this method is allowed to modify the instance it belongs or any properties in it.

Page 28: Swift Tutorial Part 2. The complete guide for Swift programming language

Protocols Composition● If you want a type to conform to multiple protocols use the form

protocol<SomeProtocol, AnotherProtocol>

Page 29: Swift Tutorial Part 2. The complete guide for Swift programming language

Checking For Protocol Conformance

● Use is, as or as? to check for protocol conformance.

● You must mark your protocol with @objc attribute to check for protocol conformance.

● @objc protocols can be adopted only by classes.

● @objc attribute tells compiler that this protocol should be exposed to Objective-C code.

Page 30: Swift Tutorial Part 2. The complete guide for Swift programming language

Optional Requirements In Protocols

● Attributes and methods can be optional by prefixing them with the keyword optional. It means that they don't have to be implemented.

● You check for an implementation of an optional requirement by writing ? after the requirement. Thats because the optional property or method that return value will return Optional value so you can check it easily

● Optional protocol requirements can only be specified if your protocol is marked with the @objc attribute

Page 31: Swift Tutorial Part 2. The complete guide for Swift programming language

Delegation

● Delegation is the a best friend for any iOS developer and I think there is no developer didn't use it before.

● Defining delegate property as optional is useful for not required delegates OR to use its initial value nil, so when you use it as nil you will not get errors ( Remember you can send msgs to nil)

Check example:

Page 32: Swift Tutorial Part 2. The complete guide for Swift programming language

DelegationDelegation example

Page 33: Swift Tutorial Part 2. The complete guide for Swift programming language

Extensions● Extensions are like Categories in Objective-C

● You can use it with classes, structures and enumerations.

● They are not names like categories in Objective-C

● You can add properties, instance and class methods, new initializers, nested types, subscripts and make it conform to a protocol.

● Extensions can be created by this form:

Page 34: Swift Tutorial Part 2. The complete guide for Swift programming language

Extension ExamplesUsing computed properties:

Here we have Double value to represent meters, we need it in Km and Cm, we add an extension for Double

Page 35: Swift Tutorial Part 2. The complete guide for Swift programming language

Extension ExamplesDefine new initializers:

We will add a new initializer for CGRect , to accept center point, width and height.

Page 36: Swift Tutorial Part 2. The complete guide for Swift programming language

Extension ExamplesDefine new methods:

In this example we will add new method in Int, it will take a closure to run it with int value times.

Page 37: Swift Tutorial Part 2. The complete guide for Swift programming language

Extension ExamplesDefine mutating methods:

Add methods that modify in the instance itself (mutate it):

Page 38: Swift Tutorial Part 2. The complete guide for Swift programming language

Extension ExamplesProtocol adoption with Extension:

Page 39: Swift Tutorial Part 2. The complete guide for Swift programming language

Generics● Generics is used to write reusable functions that can apply for any

type.

● Example for generics: Arrays and Dictionaries. You can create Array with any type and once declared, it works with this kind.

● Suppose you need a function that takes array as parameter and returns the first and last elements. In Swift you have to tell the function the type of array and type of return values. So this will not work for any kind of array. If you used AnyObject, the returned values will be of kind AnyObject and you have to cast them!

● To solve this we will use generics, check exmaple:

Page 40: Swift Tutorial Part 2. The complete guide for Swift programming language

GenericsWe will build a stack data structure with generic type. It can be stack of Strings, Ints, ….. or even custom objects.

Page 41: Swift Tutorial Part 2. The complete guide for Swift programming language

Operator Functions

● Classes and structures can provide their own implementation of operators (Operator overloading).

● You can add your custom operators and override them.

Check example, we will add some operators functions for CGVector

Page 42: Swift Tutorial Part 2. The complete guide for Swift programming language

Operators Functions

Page 43: Swift Tutorial Part 2. The complete guide for Swift programming language

Thanks!

If you liked the tutorial, please share and tweet with your friends.

If you have any comments or questions, don't hesitate to email ME