1. 变量和常量的定义
在Swift中,变量和常量的定义非常简单。变量用var
关键字声明,而常量用let
关键字声明。
var myVariable = 42
let myConstant = "Hello, Swift!"
2. 数据类型转换
Swift中的数据类型转换可以通过类型构造来实现。
let intToDouble = 42 as Double
let stringToInt = "100" as Int
3. 控制流
使用if
和switch
语句来控制程序的流程。
if myVariable > 10 {
print("变量大于10")
}
switch myVariable {
case 1:
print("变量等于1")
default:
print("变量不等于1")
}
4. 循环
Swift支持for
和while
循环。
for i in 1...5 {
print(i)
}
var j = 0
while j < 5 {
print(j)
j += 1
}
5. 函数
函数允许你将代码封装成可重用的块。
func sayHello(name: String) {
print("Hello, \(name)!")
}
sayHello(name: "Swift")
6. 闭包
闭包是匿名函数,可以在代码块中使用。
let closure = { (name: String) in
print("Hello, \(name)!")
}
closure("Swift")
7. 面向对象编程
Swift支持面向对象编程,类和结构体可以用来定义数据和行为。
class MyClass {
var property: String
init(property: String) {
self.property = property
}
func method() {
print("MyClass method")
}
}
let myClass = MyClass(property: "Swift")
myClass.method()
8. 属性观察器
属性观察器允许你在属性值改变时执行代码。
class MyClass {
var property: String {
didSet {
print("Property changed to \(property)")
}
}
init(property: String) {
self.property = property
}
}
let myClass = MyClass(property: "Swift")
myClass.property = "Swift 5"
9. 类型别名
类型别名可以让你给现有类型起一个新名字。
typealias MyInt = Int
var myInt: MyInt = 42
10. 数组和字典
Swift中的数组和字典是常用的数据结构。
let myArray = [1, 2, 3]
let myDictionary = ["key1": "value1", "key2": "value2"]
通过以上10个实用的小案例,你可以快速上手Swift编程。随着你不断学习和实践,你将能够开发出更多复杂和有趣的应用程序。