Swift 提供了丰富的数据类型,可以满足各种编程需求。以下是 Swift 中一些常用的数据类型:

1. 基本数据类型

  •  Integers(整数):

  - Int: 根据平台,可以是 32 位或 64 位。
  - Int8, Int16, Int32, Int64: 有符号整数,分别表示 8、16、32 和 64 位。
  - UInt: 无符号整数,根据平台,可以是 32 位或 64 位。
  - UInt8, UInt16, UInt32, UInt64: 无符号整数,分别表示 8、16、32 和 64 位。
  let integerNumber: Int = 42

  •  Floating-Point Numbers(浮点数):

  - Double: 64 位浮点数。
  - Float: 32 位浮点数。
  let pi: Double = 3.14159

  •  Booleans(布尔值):

  - Bool: 布尔类型,只有 true 或 false。
  let isSwiftAwesome: Bool = true

  •  Characters(字符):

  - Character: 表示单个字符。
  let firstLetter: Character = "S"

  •  Strings(字符串):

  - String: 表示一串文本。
  let greeting: String = "Hello, Swift!"

2. 集合类型

  •  Arrays(数组):

  - Array: 有序的数据集合。
  var numbers: [Int] = [1, 2, 3, 4, 5]

  •  Dictionaries(字典):

  - Dictionary: 无序的键值对集合。
  var person: [String: Any] = ["name": "John", "age": 25, "isStudent": true]

  •  Sets(集合):

  - Set: 无序且唯一元素的集合。
  var uniqueNumbers: Set<Int> = [1, 2, 3, 4, 5]

3. 元组(Tuples)

  •  Tuple: 有序的数据集合,可以包含多个不同类型的元素。

let coordinates: (Double, Double) = (40.7128, -74.0060)

4. 可选类型(Optionals)

  •  Optional: 表示一个值可能存在,也可能不存在的情况。

var optionalNumber: Int? = 42

5. 其他数据类型

  •  函数类型(Function Types):

  - Function: 表示函数的类型。
  func add(_ a: Int, _ b: Int) -> Int {
      return a + b
  }

  •  闭包类型(Closure Types):

  - Closure: 表示闭包的类型。
  let multiply: (Int, Int) -> Int = { (a, b) in
      return a * b
  }

这只是 Swift 中一些常见的数据类型,Swift 还支持结构体(Structures)、类(Classes)、枚举(Enumerations)等更高级的数据类型。


转载请注明出处:http://www.pingtaimeng.com/article/detail/14412/Swift