变量和常量
// 变量(可变)
var myVariable = 42
myVariable = 50
// 常量(不可变)
let myConstant = 42
数据类型
// 显式声明数据类型
var explicitDouble: Double = 70
// 隐式类型推断
var implicitDouble = 70.0
字符串和字符
let myString = "Hello, Swift!"
// 拼接字符串
let name = "World"
let greeting = "Hello, \(name)!"
// 多行字符串
let multilineString = """
This is a
multiline
string.
"""
数组和字典
// 数组
var myArray = [1, 2, 3]
myArray.append(4)
// 字典
var myDictionary = ["key1": "value1", "key2": "value2"]
myDictionary["key3"] = "value3"
控制流
// 条件语句
let temperature = 25
if temperature > 30 {
print("It's hot!")
} else if temperature > 20 {
print("It's warm.")
} else {
print("It's cold.")
}
// 循环语句
for i in 1...5 {
print(i)
}
// Switch 语句
let day = "Wednesday"
switch day {
case "Monday", "Tuesday":
print("Workdays")
case "Saturday", "Sunday":
print("Weekends")
default:
print("Other days")
}
函数
func greet(name: String) -> String {
return "Hello, \(name)!"
}
let greetingMessage = greet(name: "Swift")
print(greetingMessage)
可选型(Optionals)
var maybeString: String? = "Hello"
// 强制解包
if let unwrappedString = maybeString {
print(unwrappedString)
}
// 隐式解包
let unwrappedString = maybeString!
print(unwrappedString)
类和结构体
// 类
class Dog {
var name: String
init(name: String) {
self.name = name
}
func bark() {
print("Woof!")
}
}
let myDog = Dog(name: "Buddy")
myDog.bark()
// 结构体
struct Point {
var x: Int
var y: Int
}
var point = Point(x: 10, y: 20)
point.x = 15
这是一个简单的 Swift 基本语法示例。Swift 还包括很多其他特性,如协议、扩展、闭包、枚举等。
转载请注明出处:http://www.zyzy.cn/article/detail/14411/Swift