Swift提供了一些基本的內建型別,常見的有以下幾種:
Int
:整數型別,根據平台的不同可以是32位或64位。Float
:單精度浮點數,32位。Double
:雙精度浮點數,64位。Bool
:布爾型別,值為true
或false
。String
:字符串型別,用於存儲文本。Character
:字符型別,用於存儲單個字符。let intValue: Int = 42
let anotherIntValue = 10
let sum = intValue + anotherIntValue
print("Sum: \\\\(sum)") // Sum: 52
let floatValue: Float = 3.14
let doubleValue: Double = 2.718281828
let product = floatValue * Float(doubleValue)
print("Product: \\\\(product)") // Product: 8.5397596
let isSwiftFun: Bool = true
let isLearningHard = false
if isSwiftFun {
print("Swift is fun!")
} else {
print("Swift is not fun.")
}
let greeting: String = "Hello, world!"
let name = "Alice"
let personalizedGreeting = greeting + " " + name
print(personalizedGreeting) // Hello, world! Alice
let letter: Character = "A"
let exclamationMark: Character = "!"
let message = "Hello" + String(exclamationMark)
print(message) // Hello!
選擇型用於表示一個值可能存在或不存在。使用?來標記一個變量為選擇型。
var optionalString: String? = "Hello"
print(optionalString) // Optional("Hello")
optionalString = nil
print(optionalString) // nil
// 使用可選綁定來解包選擇型
if let unwrappedString = optionalString {
print(unwrappedString)
} else {
print("optionalString is nil")
}
// 使用強制解包
print(optionalString!) // 這將在optionalString為nil時崩潰
在Swift中,可以通過顯式轉換來改變變數的型別:
let intValue: Int = 42
let doubleValue: Double = Double(intValue) // 將Int轉換為Double
let stringValue: String = "123"
if let intValueFromString = Int(stringValue) {
print("轉換成功:\\\\(intValueFromString)")
} else {
print("轉換失敗")
}
自訂型別可以通過定義類、結構和枚舉來創建:
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func greet() {
print("Hello, my name is \\\\(name) and I am \\\\(age) years old.")
}
}
let person = Person(name: "Alice", age: 30)
person.greet()
struct Point {
var x: Int
var y: Int
func description() -> String {
return "Point at (\\\\(x), \\\\(y))"
}
}
let point = Point(x: 10, y: 20)
print(point.description())
enum Direction {
case north
case south
case east
case west
}
let currentDirection = Direction.north
switch currentDirection {
case .north:
print("Heading North")
case .south:
print("Heading South")
case .east:
print("Heading East")
case .west:
print("Heading West")
}
元組是一組有序的值,可以包含不同型別:
let httpError = (404, "Not Found")
let (statusCode, statusMessage) = httpError
print("Status code is \\\\(statusCode) and status message is \\\\(statusMessage)")
let namedHttpError = (statusCode: 404, message: "Not Found")
print("Status code is \\\\(namedHttpError.statusCode) and status message is \\\\(namedHttpError.message)")
集合是一組無序且不重複的值:
var fruitSet: Set<String> = ["Apple", "Banana", "Cherry"]
fruitSet.insert("Durian")
print(fruitSet)
陣列是一組有序的值:
var numbers: [Int] = [1, 2, 3, 4, 5]
numbers.append(6)
print(numbers)
let firstNumber = numbers[0]
print("First number is \\\\(firstNumber)")
字典是一組鍵值對:
var capitals: [String: String] = ["France": "Paris", "Japan": "Tokyo"]
capitals["China"] = "Beijing"
print(capitals)
if let capital = capitals["France"] {
print("The capital of France is \\\\(capital)")
}