Swift-语法基础

avatar
作者
猴君
阅读量:0

 一、声明

变量声明 

以关键字 var 开头的声明引入变量,该变量在程序执行期间可以具有不同的值。

var str: String = "hello" str = "hello, world"

常量声明

以关键字 let 开头的声明引入只读常量,该常量只能被赋值一次。

let str: String = "hello"

二、类型

Int类型

Int 整数类型,又包含Int8、Int16、Int32、Int64。

let intNum: Int = 12 let maxInt16: Int16 = Int16.max let MinInt32: Int32 = Int32.min

Float类型

Float 浮点数类型。

let floatNum: Float = 3.14

Bool类型

Bool 类型由 true 和 false 两个逻辑值组成。

let success: Bool = true if success {     // do something }

String类型

String 代表字符序列,可以使用转义字符来表示字符。

let str1 = "title" let str2 = "detail" let str3 = str1 + " " + str2;  let isContain = str3.contains(str1)  let content = "content: \(str3)" print(content)  let intNum = Int("12") // 12 let floatNum = Float("3.14") // 3.14  _ = " every body ".replacingOccurrences(of: " ", with: "") // 'everybody' _ = " every body ".trimmingCharacters(in: .whitespaces) // 'every body'           let hasPrefix = "every one".hasPrefix("every") // true let hasSuffix = "every one".hasSuffix("one") // true

Array类型

Array 类型是由可赋值给数组声明中指定的元素类型的数据组成的对象。

var arr1 = Array<String>() arr1.append("red") arr1.append("blue") arr1.removeLast() let isEmpty = arr1.isEmpty // ["red"]  var arr2 = [String]() arr2.append("black") arr2.append("gray") let obj = arr2[0] // "black" let count = arr2.count  let arr3 = arr1 + arr2 // ["red", "black", "gray"] let isContain = arr3.contains("gray")   let arr4 = Array(arr3[1...]) // ["black", "gray"]  let segments = "m.baidu.com".components(separatedBy: ".") // ["m", "baidu", "com"] let host = components.joined(separator: ".") // "m.baidu.com"

Dictionary类型

Dictionary 是 HashMap 结构,存储 key-value 键值对。

var dic1 = [String: String]() dic1["hello"] = "world" dic1.removeValue(forKey: "hello") _ = dic1.isEmpty  var dic2: [Int: Int] = [1:1, 2:2, 3:3] dic2[4] = 4 print("count: \(dic2.count)")

Void类型

Void 类型用于指定函数没有返回值。

func getDeviceId() -> Void {     // do somethind }

Enum类型

enum 枚举类型用于声明一组命名的常数。

// 声明 enum Direction {     case LEFT     case RIGHT     case TOP     case BOTTOM }  // 应用 let direction = Direction.LEFT

三、语句

if语句

if condition {     // do something }

if 结合 let 的应用场景 

// 常规的非空判断 func execute(value: String?) {     if value != nil {         print("\(value!.count)")     } }  // 结合let的非空判断 func execute(value: String?) {     if let value = value {         print("\(value.count)")     } }

switch语句

switch type {     case 0:          // do something     case 1, 2:         // do something     default:         // do something }

for语句

let arr: [String] = ["a", "b", "c", "d", "e"] for i in 0..<arr.count {     let str = arr[i]     if str == 'd' {         break     }     // do something }
let arr: [String] = ["a", "b", "c", "d", "e"] for str in arr {     if str == 'b' {         continue     }     // do something }
let arr: [String] = ["a", "b", "c", "d", "e"] arr.forEach{ obj in     // do something }  arr.enumerated().forEach { (idx, obj) in     // do something }  let dic: [Int: Int] = [1:1, 2:2, 3:3] dic.forEach { (key, value) in     // do something }

while语句

while condition {     // do something }

try-catch语句

do {     try // do something } catch {     print(error) }

四、运算符

三元运算符

let str = value ? value : ""  let str1 = value ?? ""

加/减运算符

let i = 0 i += 1 // 等价与 i = i+1  let j = 10 j -= 1 // 等价与 j = j-1

可选链运算符

1)变量/属性的定义

class Article {     var title: string = "标题"     var summary: String?      init() {         self.summary = "简介"     }        func execute(hasSign: Bool) {         _ = self.title.count         _ = self.summary?.count          var sign: String? // 先声明         if hasSign {             sign = "署名" // 再赋值         }         let signLength = sign?.count ?? 0     } }

2)方法传参

func execute(_ str1: String, _ str2: String?) -> String {     return str1 + (str2 ?? "") }  execute("a", nil)

五、函数

常规的函数声明/调用。

func execute(arg1: String, arg2: String?) -> Bool {      // do something      return true }  execute(arg1: "title", arg2: nil)
func execute(_ str1: inout String, _ str2: String) {     str1 += str2 }  var str1 = "he" execute(&str1, "llo")

 带回调的函数声明/调用。

func execute(callBack: ((String) -> Void)?) {     if let callBack = callBack {         callBack("success")     } }  execute { result in     // do something }

六、类

类声明

引入一个新类型,并定义其字段、方法和构造函数。

class Car {     var name: String = ""     var style: String = ""     var price: Float?     private var identify: String?      init() { ... }      func execute() {         let detail = "\(self.name) \(self.style)"         print(detail)     } }

构造函数

1)不带参数

init() {     // do something }

2)带参数

init(name: String, style: String) {     self.name = name     self.style = style     // do something }

 3)调用时机

// 不带参数 let car1 = Car()  car1.name = "Tesla" car1.style = "Model 3"  // 带参数 let car1 = Car(name: "Tesla", style: "Model 3")

实例方法

class Car {     init() { ... }      func execute() {         // do something     }  }  Car().execute()

类方法

class Car {     class func execute() {         // do something     }  }  Car.execute()

Getter/Setter方法

class Car {     private var _name: String = ""     private var _price: Float?        var name: String {         get {             return _name         }         set {             _name = newValue         }     }      var price: Float? {         get {             return _price         }         set {             _price = newValue         }     }          func execute() {         self.name = "BYD" // set         print(self.name) // get     } }

类继承

class BydCar: Car {     var Batterylife: Int?      override init() {         super.init()         self.name = "Byd"     }      override func execute() {         super.execute()         // do something     } }

方法重写

class BydCar: Car {     override func execute() {         // 重写execute方法     } }

方法重载

class BydCar: Car {     func execute(_ argument: [String: String]) {         // 重载execute方法(修改入参)     }      func execute(_ argument: String) -> Bool {         // 重载execute方法(修改入参/出参)     } }

协议声明

protocol CarInterface {     func drive() } 

协议继承

protocol BydInterface: CarInterface {     func automaticParking() } 

协议实现

class BydCar: Car, BydInterface {     override init() {         super.init()         self.name = "Byd"     }      func drive() {         // drive      }      func automaticParking() {         // automatic parking     } } 

静态属性

// 声明 class EventConstants {     static let AVAILABLE    = true     static let LOAD_EVENT   = "onLoad"     static let UNLOAD_EVENT = "onUnload" }  // 应用 let available = EventConstants.AVAILABLE

静态方法

// 声明 class DeviceUtils {     static func getDeviceName() -> String {         return "iPhone 15"     } }  // 应用 let deviceName = DeviceUtils.getDeviceName()

本文参考于 Swift 官方文档:Swift Documentation

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!