Easy Tutorial
❮ Swift Methods Swift Enumerations ❯

Swift Class

Swift class is a general-purpose and flexible construct used to build code.

We can define properties (constants, variables) and methods for a class.

Unlike other programming languages, Swift does not require you to create separate interface and implementation files for custom classes. All you need to do is define a class in a single file, and the system will automatically generate an external interface for other code.

Class and Structure Comparison

Classes and structures in Swift have many similarities. These include:

Compared to structures, classes have additional features:

Syntax:

class classname {
   Definition 1
   Definition 2
   ……
   Definition N
}

Class Definition

class student{
   var studname: String
   var mark: Int 
   var mark2: Int 
}

Instantiating a class:

let studrecord = student()

Example

import Cocoa

class MarksStruct {
    var mark: Int
    init(mark: Int) {
        self.mark = mark
    }
}

class studentMarks {
    var mark = 300
}
let marks = studentMarks()
print("成绩为 \(marks.mark)")

Output of the above program:

成绩为 300

Accessing Class Properties as Reference Types

Class properties can be accessed using the . notation. The format is: instanceOfClass.propertyName:

import Cocoa

class MarksStruct {
   var mark: Int
   init(mark: Int) {
      self.mark = mark
   }
}

class studentMarks {
   var mark1 = 300
   var mark2 = 400
   var mark3 = 900
}
let marks = studentMarks()
print("Mark1 is \(marks.mark1)")
print("Mark2 is \(marks.mark2)")
print("Mark3 is \(marks.mark3)")

Output of the above program:

Mark1 is 300
Mark2 is 400
Mark3 is 900

Identity Operators

Since classes are reference types, it's possible for multiple constants and variables to reference the same class instance.

To determine whether two constants or variables refer to the same class instance, Swift has two identity operators:

Identity Operators Nonidentity Operators
Operator: === Operator: !==
Returns true if both constants or variables reference the same class instance Returns true if both constants or variables reference different class instances

Example

import Cocoa

class SampleClass: Equatable {
    let myProperty: String
    init(s: String) {
        myProperty = s
    }
}
func ==(lhs: SampleClass, rhs: SampleClass) -> Bool {
    return lhs.myProperty == rhs.myProperty
}

let spClass1 = SampleClass(s: "Hello")
let spClass2 = SampleClass(s: "Hello")

if spClass1 === spClass2 {// false
    print("References the same class instance \(spClass1)")
}

if spClass1 !== spClass2 {// true
    print("References different class instances \(spClass2)")
}

Output of the above program:

References different class instances SampleClass
❮ Swift Methods Swift Enumerations ❯