Swift 程式:建立類和物件


本教程將討論如何編寫 Swift 程式來建立類和物件。

Swift 語言也是一種面向物件的語言。因此,它完全支援類和物件。

類是物件的藍圖。為了向類新增功能,我們可以定義屬性和方法。這裡,類中存在的常量和變數稱為類屬性,而類中的函式稱為方法。與其他程式語言一樣,Swift 類也支援繼承、型別轉換、解構函式、引用等。

語法

以下是建立類的語法:

Class MyClassName{
   // Definition of the class
}

示例

以下程式演示瞭如何建立一個類。

class Course{
   var name = “Swift”
   var chapters = 40
   func Price(){
      print(“Price of swift package is 5000”)
   }
}

這裡,Course 是類名,name 和 chapters 是類的屬性,Price 是類的方法。我們可以透過點語法訪問類的屬性和方法。這裡,屬性名稱用點 (.) 與例項名稱分隔,例如 obj.name。

物件

在 Swift 中,類物件稱為類的例項。我們可以建立多個相同類的物件。例如,book 是一個類,author1、author2 和 author3 是該類的物件。

語法

以下是建立物件的語法:

var MyObjectName = MyClassName()

示例

以下程式演示瞭如何建立一個物件:

// Creating class
class Course{
   var name = “Swift”
   var chapters = 40
   func Price(){
      print(“Price of swift package is 5000”)
   }
}

// Creating object
var lang1 = Course()

示例

類和物件

以下程式演示瞭如何建立一個類及其物件。

import Foundation
import Glibc

// Creating class
class Author{
   // Properties
   var language = "Swift"
   var chapters = 50
   var programs = 60
   // Methods
   func price(){
      print("Cost of one package is 6000")
   }
}
// Creating object 
var lang1 = Author()
// Accessing the properties of the class
print("Language name: ", lang1.language)
print("Total number of chapters:", lang1.chapters)
// Accessing the methods of the class
lang1.price()

輸出

Language name:  Swift
Total number of chapters: 50
Cost of one package is 6000

示例

建立類的多個物件

以下程式演示瞭如何建立類的多個物件。

import Foundation
import Glibc

// Creating class
class Product{

    // Properties
    var productID = 0
    var ProductName = "Mango"
}

// Creating multiple objects
var obj1 = Product()
var obj2 = Product()

// Accessing the properties of the class
obj1.productID = 3456
print("Id of the product:", obj1.productID)

obj2.productID = 876
print("Id of the product:", obj2.productID)

輸出

Id of the product: 3456
Id of the product: 876

更新於:2022年12月13日

1K+ 次檢視

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.