Swift4.0学习笔记

总是断断续续的学习一些swift知识,在实际开发中也未使用过swift来开发一款app。故将平时的学习笔记留在这里,勉励自己。在以后的发展中,swift必将成为翘楚。

  • 以下笔记是基于Swift4版本:
  • 关于swift三方库的介绍请看OC&Swift三方库

  • 懒加载:

    lazy var tableView: UITableView = {
        let tab = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.plain)
        tab.delegate = self
        tab.dataSource = self
        tab.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "123")
        return tab
    }()
  • set和get方法

    //cell上加载数据,用到了Kingfisher
    var teacherModel: ContentModel! {
        //didSet可以来复制,willSet,
        didSet {
            let url = URL.init(string: teacherModel.headUrl)
            self.iconImageView.kf.setImage(with: url)
            self.nameLabel.text = teacherModel.nickname
        }
    }
    var sideLength: Double
    var perimeter: Double {
        get {
            return 3.0 * sideLength
        }
        set {
            sideLength = newValue / 3.0
        }
    }
var traingle: Square {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
  • 协议与代理

    //声明协议,
    protocol ResourceButtonResponseDelegate {
        optional func responseButton(button:UIButton)
    }
    //声明代理属性
    var delegate:ResourceButtonResponseDelegate?
    //传值
    if let dele = self.delegate {
        dele.responseButton(button: button)
    }
    //成为代理
     header.delegate = self
    //代理方遵守协议并完成协议
       extension ViewController: ResourceButtonResponseDelegate {
        func responseButton(button: UIButton) {
            print(button.tag)
        }
    }
  • block(闭包),typealias别名

        //声明属性:名称(参数:参数类型,...) ->返回类型
        var responseBlock:((_ index:Int) ->Void)?
        //需要的时候传值
        if let block = self.responseBlock {
            block(index)
        }
        //接收传值
        header.responseBlock = { index in
            print(index)
        }
        //闭包别名
        typealias ResponseBlock = (_ index:Int)->Void
  • swift排序,再也不用写冒泡啦
var numbers = [20, 19, 7, 12, 3, 4, 28, 17]
let sortNum = numbers.sorted { $0 > $1 }
  • selector方法

    //添加方法:#selector(类名:方法名)
    btn.addTarget(self, action: #selector(HomeHeaderView.clickResourceButton(button:)), for: .touchUpInside)
    //方法
    @objc func clickResourceButton(button: UIButton) {
        //do something
    }
  • UIImage:可以直接引入图片名称来显示图片。直接敲图片名称:只能为英文名称

banner.png
  • 网络请求:需用到Alamofire:发起请求、SwiftyJSON:解析json很容易很安全、ObjectMapper:json转模型

import Alamofire
import SwiftyJSON

//encoding:JSONEncoding.default,headers:headers这样才是接收json数据。
let headers: HTTPHeaders = ["Accept": "application/json"]

typealias SuccessBlock = (_ data: JSON)->Void
typealias FailureBlock = (_ error: String)->Void

class Network: NSObject {
    
    class func request(url: String,
                       method: HTTPMethod,
                       parameters: Parameters,
                       success: @escaping SuccessBlock,
                       failure: @escaping FailureBlock) {
        Alamofire.request(url,
                          method: method,
                          parameters: parameters,
                          encoding: JSONEncoding.default,
                          headers: headers).responseJSON { (response) in
             //SwiftyJSON               
            switch response.result {
                case .success(let value):
                    let json = JSON(value)
                    print(json)
                    success(json)
                case .failure(let error):
                    print(error)
                    failure(error.localizedDescription)
            }
        }
    }
    class func teacherRecommendRequest(_ success: @escaping SuccessBlock, _ failure: @escaping FailureBlock) {
        let para: Parameters = ["page":0,"pageSize":5]
        
        self.request(url: baseUrl+teacherRecommend,
                     method: HTTPMethod.post,
                     parameters: para,
                     success: success,
                     failure: failure);
    }
}

ObjectMapper:Swift里转模型稍微复杂一点,手动映射。
建立模型

import UIKit
import ObjectMapper

class ResultModel: Mappable {
    
    var code: Int?
    var msg: String?
    var data: Any!
    
    required init?(map: Map) {
        
    }

    // Mappable
    func mapping(map: Map) {
        code    <- map["code"]
        msg     <- map["msg"]
        data    <- map["data"]
    }
}
import UIKit
import ObjectMapper

class DataModel: Mappable {
    
    var number: Int = -1
    var numberOfElements: Int = 0
    var sort: Any?
    var totalPages: Int = 0
    var size: Int = 0
    var last: Bool = false
    var totalElements: Int = 0
    var first: Bool = false
    var content: [ContentModel]!
    
    required init?(map: Map) {
        
    }
    
    func mapping(map: Map) {
        number           <- map["number"]
        content          <- map["content"]
        numberOfElements <- map["numberOfElements"]
        sort             <- map["sort"]
        totalPages       <- map["totalPages"]
        size             <- map["size"]
        last             <- map["last"]
        totalElements    <- map["totalElements"]
        first            <- map["first"]
    }
}

转模型:网络求得的JSON数据。

Network.teacherRecommendRequest({ (result) in
    print("data:\(result)")
    //转模型
    let res = ResultModel(JSONString: result.rawString()!)
    if let data = res?.data {
         print(data)
         let json = JSON(data)
         //将data再转模型
         print((DataModel(JSONString: json.rawString()!))!.content[0].info ?? "")
    }
            
    }) { (error) in
       print("error:\(error)")
}

你可能感兴趣的:(Swift4.0学习笔记)