Telechargé par TAMO De TAMO JULES ABDIEL

IOS CLASSESS & OBJECTS IN SWIFT

publicité
CLASSESS & OBJECTS IN
SWIFT
What is a class?
In object-oriented programming, a class is an extensible
program-code-template for creating objects, providing initial
values for state (member variables) and implementations of
behavior (member functions or methods).
We can define a class in Swift using the class keyword. We instantiate
a new instance of a class using the class name followed by (). Classes
can have properties and functions associated with them.
A property is a value that is associated with an instance of a class
and a method is a function that is associated with a class. A class is
a way of grouping related data along with the methods that
operate on them.
We can define a class in Swift using the class keyword. We instantiate
a new instance of a class using the class name followed by (). Classes
can have properties and functions associated with them.
A property is a value that is associated with an instance of a class
and a method is a function that is associated with a class. A class is
a way of grouping related data along with the methods that
operate on them.
In Swift, You define a class like this:
class Dog {}
A class can also be a subclass of another class:
class Animal {}
class Dog: Animal {}
Classes can define properties that instances of the class can use. In this
example, Dog has two properties: name and
dogAge:
class Dog {
var name = ""
var dogAge = 0
}
You can access the properties with dot syntax:
let dog = Dog()
print(dog.name)
print(dog.dogAge)
Classes can also define methods that can be called on the instances, they are
declared similar to normal functions,
just inside the class:
class Dog {
func bark() {
print("Ruff!")
}
}
Calling methods also uses dot syntax:
dog.bark()
Classes are reference types, meaning that multiple variables can refer to the same
instance.
class Dog {
var name = ""
}
let firstDog = Dog()
firstDog.name = "Fido"
let otherDog = firstDog // otherDog points to same Dog instance
otherDog.name = "Rover" // modifying otherDog also modifies firstDog
print(firstDog.name) //prints "Rover"
Because classes are reference types, even if the class is a constant, its variable
properties can still be modified.
OBJECTS
An Object is an instance of a Class. For Example we have a Class Animal and a Dog is
an Object which is an instance of the Class Animal.
class Animal {
var name : string
Var height : int
}
var dog = Animal() // the dog object is an instance of the Animal Class
dog.name = “Ralf"
dog.height=30
THANK YOU
Téléchargement