2024-06-19|閱讀時間 ‧ 約 29 分鐘

Swift入門-Day4:資料型別

內建型別

Swift提供了一些基本的內建型別,常見的有以下幾種:

  • Int:整數型別,根據平台的不同可以是32位或64位。
  • Float:單精度浮點數,32位。
  • Double:雙精度浮點數,64位。
  • Bool:布爾型別,值為truefalse
  • String:字符串型別,用於存儲文本。
  • Character:字符型別,用於存儲單個字符。

整數(Int)

let intValue: Int = 42
let anotherIntValue = 10
let sum = intValue + anotherIntValue
print("Sum: \\\\(sum)") // Sum: 52

浮點數(Float 和 Double)

let floatValue: Float = 3.14
let doubleValue: Double = 2.718281828
let product = floatValue * Float(doubleValue)
print("Product: \\\\(product)") // Product: 8.5397596

布爾型別(Bool)

let isSwiftFun: Bool = true
let isLearningHard = false
if isSwiftFun {
print("Swift is fun!")
} else {
print("Swift is not fun.")
}

字符串(String)

let greeting: String = "Hello, world!"
let name = "Alice"
let personalizedGreeting = greeting + " " + name
print(personalizedGreeting) // Hello, world! Alice

字符(Character)

let letter: Character = "A"
let exclamationMark: Character = "!"
let message = "Hello" + String(exclamationMark)
print(message) // Hello!

選擇型(Optional)

選擇型用於表示一個值可能存在或不存在。使用?來標記一個變量為選擇型。

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)")
}

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.