Swift5.0笔记 - 1. 基础语法

2020-10-21  本文已影响0人  南城同學

1. 书写格式

  1. 一句代码尾部可以省略“;”,多句代码写到同一行时必须用“;”分开。
print("Hello,World");print("test")
  1. var定义变量,let定义常量;编译器可以自动推断出变量、常量的类型。
var a = 10
a = 20
let b = 30

print(a)
print(b)
print("Hello world \(a)")
  1. 自动判断类型的前提:定义的时候就已经赋值了;
let age = 10 
  1. 否则在定义的时候要指定类型.
let age: Int
age = 10

2. 常量

var num = 10
num += 20
num += 30
let age = num
print(age)

3. 标示符

func 🐂🍺() {
    print("666")
}
🐂🍺()

let 🌹 = "花"

4. 常见的数据类型

只有两种类型:值类型(value type) 和 引用类型(reference type)

let letFloat: Float = 30.0
let letDouble = 30.0

5. 字面量

1). 布尔

let bool01 = true //取反是false

2). 字符串

let string01 = "字符串"

3). 字符(可存储ASCII字符、Unicode字符)

let chaacter01: Character = "a"

4). 整数

let intDecimal = 17 //十进制
let intBinary = 0b10001 //二进制
let intOctal = 0o21 //八进制
let intHexadecimal = 0x11 //十六进制

5). 数组

let array = [1,3,5,7,9]

6). 字典

let dictionary = ["age": 18, "height": 185, "height": 70]

6. 类型转换

let int1: UInt16 = 2_000
let int2: UInt8 = 1
let int3 = int1 + UInt16(int2)

let int01 = 3
let double01 = 0.1415
let pi = Double(int01) + double01
let intPi = Int(pi)
let result = 3 + 0.1315

7. 元组(tuple)

let http404Error = (404, "Not Found")
print("The status code is \(http404Error.0)")

//取
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")

//只取需要的
let (justTheStatusCode, _) = http404Error

//组合类型
let http200Status = (statusCode: 200, description: "ok")
print("The status code is \(http200Status.statusCode)")

上一篇 下一篇

猜你喜欢

热点阅读