總是斷斷續(xù)續(xù)的學(xué)習(xí)一些swift知識(shí)琐鲁,在實(shí)際開(kāi)發(fā)中也未使用過(guò)swift來(lái)開(kāi)發(fā)一款app卫旱。故將平時(shí)的學(xué)習(xí)筆記留在這里,勉勵(lì)自己围段。在以后的發(fā)展中顾翼,swift必將成為翹楚。
- 以下筆記是基于Swift4版本:
- 關(guān)于swift三方庫(kù)的介紹請(qǐng)看OC&Swift三方庫(kù)
-
懶加載:
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上加載數(shù)據(jù)奈泪,用到了Kingfisher
var teacherModel: ContentModel! {
//didSet可以來(lái)復(fù)制适贸,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
}
}
-
協(xié)議與代理
//聲明協(xié)議涝桅,
protocol ResourceButtonResponseDelegate {
optional func responseButton(button:UIButton)
}
//聲明代理屬性
var delegate:ResourceButtonResponseDelegate?
//傳值
if let dele = self.delegate {
dele.responseButton(button: button)
}
//成為代理
header.delegate = self
//代理方遵守協(xié)議并完成協(xié)議
extension ViewController: ResourceButtonResponseDelegate {
func responseButton(button: UIButton) {
print(button.tag)
}
}
-
block(閉包)拜姿,typealias別名
//聲明屬性:名稱(chēng)(參數(shù):參數(shù)類(lèi)型,...) ->返回類(lèi)型
var responseBlock:((_ index:Int) ->Void)?
//需要的時(shí)候傳值
if let block = self.responseBlock {
block(index)
}
//接收傳值
header.responseBlock = { index in
print(index)
}
//閉包別名
typealias ResponseBlock = (_ index:Int)->Void
-
swift排序??苹支,再也不用寫(xiě)冒泡啦
var numbers = [20, 19, 7, 12, 3, 4, 28, 17]
let sortNum = numbers.sorted { $0 > $1 }
-
selector方法
//添加方法:#selector(類(lèi)名:方法名)
btn.addTarget(self, action: #selector(HomeHeaderView.clickResourceButton(button:)), for: .touchUpInside)
//方法
@objc func clickResourceButton(button: UIButton) {
//do something
}
-
UIImage:可以直接引入圖片名稱(chēng)來(lái)顯示圖片砾隅。直接敲圖片名稱(chēng):只能為英文名稱(chēng)
-
網(wǎng)絡(luò)請(qǐng)求:需用到Alamofire:發(fā)起請(qǐng)求、SwiftyJSON:解析json很容易很安全债蜜、ObjectMapper:json轉(zhuǎn)模型
import Alamofire
import SwiftyJSON
//encoding:JSONEncoding.default,headers:headers這樣才是接收json數(shù)據(jù)。
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里轉(zhuǎn)模型稍微復(fù)雜一點(diǎn)究反,手動(dòng)映射寻定。
建立模型
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"]
}
}
轉(zhuǎn)模型:網(wǎng)絡(luò)求得的JSON數(shù)據(jù)。
Network.teacherRecommendRequest({ (result) in
print("data:\(result)")
//轉(zhuǎn)模型
let res = ResultModel(JSONString: result.rawString()!)
if let data = res?.data {
print(data)
let json = JSON(data)
//將data再轉(zhuǎn)模型
print((DataModel(JSONString: json.rawString()!))!.content[0].info ?? "")
}
}) { (error) in
print("error:\(error)")
}