Swift基本语法-简例

Swift基本语法简例

  • 安全类型 ?与! 区别
  • 变量与常量
  • 字符串拼接
  • 多行字符串
  • 数组操作
  • 字典操作
  • 数组遍历控制
  • 条件判断
  • switch语句
  • 循环遍历
  • 函数
  • 闭包
  • 对象
  • 枚举
  • 结构体
  • 协议
  • 扩展
  • 泛型
  • get,set属性
  • 属性观察
  • 懒加载,重写方法
  • 回调及保护

安全类型 ?与! 区别

?表示:返回值是一个可选类型,需要解包处理,如果有值就是相应类型的,如果没有值,就是“nil”,适用于不确定值的情形
!表示:不需要解包处理(第一次赋值时编译器已自动解包),必须保证有值,否则会报错

两者都可以通过if语句强制解析和if let可选绑定来进行使用

变量与常量

var mutableVal = 11
mutableVal = 30
let val = 20
let valDouble:Double = 50

字符串拼接

let value1 = "swift is"
let value2 = 666
let total = value1 + String(value2)
let value3 = "I think \(value1) best."

多行字符串

let value = "is sure."
let moreValue = """
when I see "swift is best."
And I see "I Love you \(value)."
"""

数组操作

var value1List = ["apple", "banana","卡特琳娜","德玛西亚"]
value1List[1] = "赵信"//数组第二个元素替换
value1List.append("韩信")//数组拼接
value1List = []
let value2List = ["999", "333"]
value1List = value1List + value2List//数组拼接,(同元素类型,区别于python)

字典操作

var valueDic = ["name1":"卡特琳娜", "name2":"德玛西亚"]
valueDic["name2"] = "凯南"
valueDic = [:]

数组遍历控制

let intValueList = [46,64,76,87,11,99]
var temp = 0
for item in intValueList {
    if item > 60 {
        temp += 4
    } else {
        temp += 1
    }
}
print(temp)

条件判断

var valueString:String? = "swift"
print(valueString == nil)
var valueName:String? = "is best."
if let name = valueName, let string = valueString {
    valueString = "\(string) \(name)"
}

switch语句

let value = "赵信"
switch value {
case "李信":
    print("李信")
case "韩信", "韩非":
    print("more switch")
case let x where x.hasSuffix("信") :
    print("it is a spicy \(x)?")
default:
    print("default")
}

循环遍历

//循环遍历找出最大值
let intValueList = ["firstList":[1,3,4,22,23,31, 9],
                    "secList":[2,7,12,13,21,25, 11],
                    "thirdList":[3,9,11,12,23,33, 12]]
var maxValue = 0
for (_, numbers) in intValueList {
    for number in numbers {
        if number > maxValue {
            maxValue = number
        }
    }
}
print(maxValue)

函数

//返回string类型的函数 (入参str1,str2)
func value(str1:String, str2:String) -> String {
    return "\(str1)\(str2)"
}
//函数(入参int类型的数组)
func showMaxValue(scores:[Int]) -> (min:Int, max:Int, sum:Int){
    
}

闭包

func request(list:[Int], condition:(Int) -> Bool) ->Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}

//回调
func requestBlock(param:Dictionary<String, Any>, SuccessData:@escaping (Dictionary<String, Any>?) -> Void) {
    let valueDic = ["name1":"卡特琳娜", "name2":"德玛西亚"]
    SuccessData(valueDic)
}

对象

class colorModel {
    var color = "red"
    func colorDes() -> String {
        return "swift is best with \(color)."
    }
    
}

枚举

enum colorString {
    case red, green, blue, gray
    func colorDes() -> String {
        switch self {
        case .red:
            return "red"
        case .blue:
            return "blue"
        case .green:
            return "green"
        default:
            return "gray"
        }
    }
}
let colorStr = colorString.red
let colorDes = colorStr.colorDes()

结构体

struct colorModel {
    var color = "red"
    func colorDes() -> String {
        return "swift is best with \(color)."
    }
    
}

协议

protocol exampleProtocol {
    var simpleDes:String{ get }
    mutating func adjust()
    
}

class simpleClass: exampleProtocol {
    var simpleDes:String = "simple class Des"
    var anotherProperty:Int = 88999
    func adjust() {
        simpleDes += " adjusted"
    }
}

var a = simpleClass()
a.adjust()
let aDes = a.simpleDes

struct simpleStruct:exampleProtocol {
    var simpleDes: String = "simple Struct Des"
    mutating func adjust() {
        simpleDes += " adjusted"
    }
}

var b = simpleStruct()
b.adjust()
let bDes = b.simpleDes

扩展

extension UIApplication {
    var isDebug:Bool {
        #if DEBUG
        return true
        #else
        return false
        #endif
    }
}

泛型

func changeArray<Item>(repeating item:Item, numberOfTimes:Int) ->[Item] {
    var result:[Item] = []
    for _ in 0..<numberOfTimes {
        result.append(item)
    }
    return result
}
changeArray(repeating: "hhh", numberOfTimes: 2)

get,set属性

//point
var center:Point {
    get{
        Point(x: origin.x + (size.width/2),
              y: origin.y + (size.height / 2))
    }
    set{
        origin.x = newValue.x - (size.width / 2)
        origin.y = newValue.y - (size.height / 2)
    }
}
//string
var _str : String
var tempStr : String {
    get {
        return _str
    }
    set {
        _str = newValue
    }
}

属性观察

var totalSteps:Int = 0 {
    willSet(newTotalSteps){
        print("\(newTotalSteps)")
    }
    didSet {
        if totalSteps > oldValue {
            print("when totalSteps > oldValue : \(totalSteps - oldValue)")
        }
    }
}

懒加载,重写方法

class SwiftUIView: UIView {
    //重写init方法
    override init(frame: CGRect){
        super.init(frame: frame)
        
    }
    
    //懒加载
    lazy var arrowImgView: UIImageView = {
        let arrowImgV = UIImageView()
        arrowImgV.isUserInteractionEnabled = true
        arrowImgV.backgroundColor = .clear
        arrowImgV.clipsToBounds = true
        arrowImgV.snp.makeConstraints { (make) in
            make.size.centerX.equalToSuperview().offset(-10)
            make.size.centerY.equalToSuperview().offset(8)
        }
        return arrowImgV
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder) has not been implemented")
    }
}

回调及保护

    var requestComplete:((_ success: Bool) -> Void)?

//回调
self.viewModel.requestComplete = { [weak self] success in
    guard let self = self else { return }
    self.hiddenLoadingHUD()
}

你可能感兴趣的:(移动互联网-iOS笔记,python,正则表达式,爬虫)