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.