- Swift 教程
- Swift - 首页
- Swift - 概述
- Swift - 环境
- Swift - 基本语法
- Swift - 变量
- Swift - 常量
- Swift - 字面量
- Swift - 注释
- Swift 运算符
- Swift - 运算符
- Swift - 算术运算符
- Swift - 比较运算符
- Swift - 逻辑运算符
- Swift - 赋值运算符
- Swift - 位运算符
- Swift - 其他运算符
- Swift 高级运算符
- Swift - 运算符重载
- Swift - 算术溢出运算符
- Swift - 恒等运算符
- Swift - 范围运算符
- Swift 数据类型
- Swift - 数据类型
- Swift - 整数
- Swift - 浮点数
- Swift - Double
- Swift - 布尔值
- Swift - 字符串
- Swift - 字符
- Swift - 类型别名
- Swift - 可选值
- Swift - 元组
- Swift - 断言和前提条件
- Swift 控制流
- Swift - 决策
- Swift - if 语句
- Swift - if...else if...else 语句
- Swift - if-else 语句
- Swift - 嵌套 if 语句
- Swift - switch 语句
- Swift - 循环
- Swift - for in 循环
- Swift - while 循环
- Swift - repeat...while 循环
- Swift - continue 语句
- Swift - break 语句
- Swift - 穿透语句
- Swift 集合
- Swift - 数组
- Swift - 集合
- Swift - 字典
- Swift 函数
- Swift - 函数
- Swift - 嵌套函数
- Swift - 函数重载
- Swift - 递归
- Swift - 高阶函数
- Swift 闭包
- Swift - 闭包
- Swift-逃逸和非逃逸闭包
- Swift - 自动闭包
- Swift 面向对象编程
- Swift - 枚举
- Swift - 结构体
- Swift - 类
- Swift - 属性
- Swift - 方法
- Swift - 下标
- Swift - 继承
- Swift-重写
- Swift - 初始化
- Swift - 析构
- Swift 高级特性
- Swift - ARC 概述
- Swift - 可选链
- Swift - 错误处理
- Swift - 并发
- Swift - 类型转换
- Swift - 嵌套类型
- Swift - 扩展
- Swift - 协议
- Swift - 泛型
- Swift - 访问控制
- Swift - 函数与方法
- Swift - SwiftyJSON
- Swift - 单例类
- Swift 随机数
- Swift 不透明类型和装箱类型
- Swift 有用资源
- Swift - 在线编译
- Swift - 快速指南
- Swift - 有用资源
- Swift - 讨论
Swift - 结构体
结构体是Swift中最常用的用户自定义数据类型。它允许我们将相关数据和操作组合到单个块中。它对于将数据和功能封装到单个单元中非常有用,并提供更组织化和可读的代码。在结构体中,我们可以借助方法和属性添加功能。
在Swift中,结构体不需要任何额外的文件或接口来实现,我们可以在单个文件中定义结构体,外部接口会自动访问此代码。结构体是值类型。
Swift中的结构体
就像其他编程语言一样,在Swift中,结构体使用struct关键字以及名称和花括号({})定义。这里名称必须以大写字母开头,例如School,而不是school。花括号包含所有属性和方法。
属性 - 与结构体关联的常量和变量称为结构体的属性。它们通常用于存储和检索结构体实例中的值。一个结构体可以有多个属性。
方法 - 与结构体关联的函数称为结构体的方法。它们通常用于定义与结构体相关的行为。方法可以具有参数和返回值。一个结构体可以有多个方法。在Swift中,使用方法不允许我们更改属性。但是,如果我们想在方法内部更改属性,则必须使用mutating关键字标记该方法。
语法
以下是结构体的语法:
struct nameStruct {
// Properties
Property 1 : Type
Property 2 : Type
// Methods
func functionName(){
// Statement
}
// Mutating method
mutating func functionName(){
// Statement
}
}
示例
在下面的Swift示例中,我们需要访问包含三门科目分数的学生记录,并计算这三门科目的总分。因此,我们创建一个名为markStruct的结构体,其中包含三个名为'Int'的数据类型的分数。
struct MarkStruct{
var mark1: Int
var mark2: Int
var mark3: Int
}
Swift结构体实例
结构体实例是从结构体的定义创建的对象,并代表属性的一些值集。单个结构体可以有多个实例,它们彼此独立,这意味着如果我们修改一个实例,不会影响其他实例。
我们可以通过调用结构体初始化器来创建一个结构体实例。结构体可能包含也可能不包含初始化器。因此,如果结构体不包含任何初始化器,则Swift将自动接收一个逐成员初始化器来创建结构体对象。使用此初始化器,我们可以通过在逐成员初始化器中传递初始值以及名称来初始化每个属性。
语法
以下是结构体实例的语法:
var objectName = StructName(propertyName1: value, propertyName2: value)
示例
在下面的Swift示例中,我们将创建MarkStruct的实例。
struct MarkStruct{
var mark1: Int
var mark2: Int
var mark3: Int
}
// Creating instance using memberwise initializer
var myObj = MarkStruct(mark1: 10, mark2: 20, mark3: 30)
如果结构体包含默认初始化器,我们也可以在不提供参数或初始值的情况下创建结构体的实例。
struct MarkStruct{
var mark1: Int
var mark2: Int
var mark3: Int
// Default initialzer
init(){
Mark1 = 1
Marks2 = 2
Mark3 = 3
}
}
// Creating instance using default initializer
var myInstance = MarkStruct()
在Swift中访问结构体的属性
要访问结构体的属性,我们可以使用结构体实例后跟一个点(.)和属性名称。使用此表示法,我们还可以修改属性的值。借助此表示法,我们还可以访问和修改结构体的子属性。
语法
以下是访问结构体属性的语法:
structInstanceName.PropertyName
以下是修改结构体属性的语法:
structInstanceName.PropertyName = value
以下是访问结构体子属性的语法:
structInstanceName.PropertyName.subPropertyName
以下是修改结构体子属性的语法:
structInstanceName.PropertyName.subPropertyName = value
示例
Swift程序,用于访问和修改结构体的属性。
// Defining a structure
struct Employee {
var name: String
var age: Int
var department: String
var salary: Int
}
// Creating an instance of the Employee structure
// with initial values of the properties
var emp = Employee(name: "Mona", age: 22, department: "HR", salary: 32000)
// Accessing the values of the properties using dot notation
print("Employee Details:")
print("Name: \(emp.name)")
print("Age: \(emp.age)")
print("Department: \(emp.department)")
print("Salary: \(emp.salary)")
// Modifying the values of the properties using dot notation
emp.age = 23
emp.salary = 33000
// Displaying the updated values
print("\nUpdated Values:")
print("Age: \(emp.age)")
print("Salary: \(emp.salary)")
输出
它将产生以下输出:
Employee Details: Name: Mona Age: 22 Department: HR Salary: 32000 Updated Values: Age: 23 Salary: 33000
示例
Swift程序,用于访问和修改结构体的子属性。
// Defining a structure with sub-properties
struct Address {
var buildingName: String
var city: String
var pincode: String
}
// Defining a structure
struct Student {
var name: String
var age: Int
var address: Address
}
// Creating an instance of the Student structure
// with initial values of the properties
var stud = Student(name: "Sumit", age: 22, address: Address(buildingName: "Anad Vihar", city: "Delhi", pincode: "333333"))
// Accessing the values of the properties and sub-properties using dot notation
print("Student Details:")
print("Name: \(stud.name)")
print("Age: \(stud.age)")
print("Building Name: \(stud.address.buildingName)")
print("City: \(stud.address.city)")
print("Pincode: \(stud.address.pincode)")
// Modifying the values of the sub-properties using dot notation
stud.address.buildingName = "Mohita Vihar"
stud.address.pincode = "333000"
// Displaying the updated values
print("\nUpdated Values:")
print("Building Name: \(stud.address.buildingName)")
print("Pincode: \(stud.address.pincode)")
输出
它将产生以下输出:
Student Details: Name: Sumit Age: 22 Building Name: Anad Vihar City: Delhi Pincode: 333333 Updated Values: Building Name: Mohita Vihar Pincode: 333000
在Swift中访问结构体的方法
借助点表示法,我们还可以访问结构体的方法。在这里,我们也可以使用结构体实例后跟一个点(.)和方法名称来访问方法。
语法
以下是访问结构体方法的语法:
structInstanceName.methodName
示例
Swift程序,用于访问结构体的方法。
// Defining a structure
struct Parallelogram {
var base: Double
var height: Double
// Method to calculate the area of the Parallelogram
func calculateParallelogramArea() -> Double {
return base * height
}
// Mutating method to resize the base and height of the Parallelogram
mutating func resizeParallelogram(by value: Double) {
base += value
height += value
}
}
// Create an instance of the Parallelogram structure
var myObj = Parallelogram(base: 10.0, height: 9.0)
// Calling the calculateParallelogramArea() method
let area = myObj.calculateParallelogramArea()
print("Area of the Parallelogram: \(area)")
// Calling the mutating method i.e., resizeParallelogram()
myObj.resizeParallelogram(by: 3)
// Displaying the updated base and height of the Parallelogram
print("\nUpdated values: ")
print("Base: \(myObj.base)")
print("Height: \(myObj.height)")
输出
它将产生以下输出:
Area of the Parallelogram: 90.0 Updated values: Base: 13.0 Height: 12.0
Swift中结构体作为值类型
在Swift中,结构体是值类型,这意味着当我们将结构体赋值给变量或常量或将其作为参数传递给函数时,会创建一个结构体的副本。这些副本与原始实例独立,这意味着如果我们修改一个实例的副本,不会影响结构体实例的其他副本。
示例
Swift程序,用于演示结构体作为值类型。
// Defining a structure
struct Student {
var name: String
var age: Int
}
// Creating an instance of the Student structure
var stud = Student(name: "Sumit", age: 22)
// Creating a copy of the stud instance
var details = stud
// Modifying the values of the properties
details.name = "Mohina"
details.age = 34
print("student 1: name-\(stud.name) and age-\(stud.age)")
print("student 2: name-\(details.name) and age-\(details.age)")
输出
它将产生以下输出:
student 1: name-Sumit and age-22 student 2: name-Mohina and age-34
Swift中带有self关键字的结构体
在结构体中,self关键字用于区分属性名称和方法的参数。self关键字通常与方法或初始化器内部的属性一起使用,以便编译器可以轻松区分哪个是参数,哪个是属性(如果它们的名称相同)。或者self关键字用于引用结构体的当前实例。
语法
以下是self关键字的语法:
self.PropertyName
示例
Swift程序,用于演示如何在结构体中使用self关键字。
// Defining a structure
struct markStruct{
var mark1: Int
var mark2: Int
var mark3: Int
// Initializer with same property and parameter name
init(mark1: Int, mark2: Int, mark3: Int){
// Using self keyword to distinguish between
// the property and parameter name
// Here self.mark1 is the property name
self.mark1 = mark1
self.mark2 = mark2
self.mark3 = mark3
}
}
// Creating an instance of the structure
var marks = markStruct(mark1: 98, mark2: 96, mark3:100)
// Displaying the values of the properties
print(marks.mark1)
print(marks.mark2)
print(marks.mark3)
输出
它将产生以下输出:
98 96 100
在Swift中将结构体传递给函数
在Swift中,允许我们将结构体作为参数传递给函数,方法是将结构体指定为参数的类型。结构体始终按值传递,这意味着结构体的副本将作为参数传递,修改不会影响原始结构体。在函数中,如果我们不想修改结构体,则可以将其作为常规参数传递;如果我们想修改结构体,则必须将其作为inout参数传递。
示例
Swift程序,用于演示如何将结构体传递给函数。
// Defining a structure
struct Rectangle {
var length: Double
var width: Double
}
// Passing a structure to a function as a regular parameter
func areaOfRectangle(value:Rectangle){
print("Area of the Rectangle is \(value.length * value.width)")
}
// Passing a structure to a function as an inout parameter
// Because we will modify the structure
func newAreaOfRectangle(data:inout Rectangle, byL newLength : Double, byW newWidth : Double){
data.length *= newLength
data.width *= newWidth
print("New Area of the Rectangle is \(data.length * data.width)")
}
// Create an instance of the rectangle structure
var myObj = Rectangle(length: 10.0, width: 9.0)
// Calling the function
areaOfRectangle(value:myObj)
// Calling the another function
newAreaOfRectangle(data: &myObj, byL : 2, byW : 3)
输出
它将产生以下输出:
Area of the Rectangle is 90.0 New Area of the Rectangle is 540.0