【iOS】—— basic syntax of swift and usage of some third-party libraries

Swift Basic Grammar

constant (let keyword)

It can only be assigned once
. Its value is not required to be determined at compile time, but it must be assigned once before use.

variable (var keyword)

It can be assigned multiple times
. Like a constant, it must be assigned a value before use, otherwise the compiler will report an error

var str:String
str = "hello world";
print(str)
str += " 11";
print(str)

var a, b, c:Int
a = 1
print(a)

var bool1:Bool = true
print(bool1)

tuple

var pen:(name:String, price:Int) = ("英雄", 15);
pen.name = "毕加索"

var car:(String, Int) = ("奔驰", 9999)
car.0 = "宝马"
var (theName, thePrice) = car
print(theName, thePrice)

typealias (similar to the previous typedef)

typealias Price = Int
var penPrice:Price = 100

if-let

var product:Int? = 100
if let weight = product, (weight > 30) {
    
    
    print("666")
}

Basic usage of String class

//String
var c1 = "hello"
var c2 = "world"
var c3 = c1 + " " + c2

var d1 = "hello\(123)"
var d2 = "hello\(c2)"
var d3 = "hello\(1+2)"
var d4 = "hello\(1) \(3)"
print(d1, d2, d3, d4)

var string2 = "My name is Jaki"
string2 = string2.uppercased()   //全部转化为大写
print(string2)
string2 = string2.lowercased()   //全部转化为小写
print(string2)
print(string2.hasPrefix("my"))
print(string2.hasSuffix("jaki"))

MemoryLayout (analogous to sizeof in c)

//MemoryLayout(类比于c中的sizeof)
print(MemoryLayout<String>.size)

array

//数组
var array1:[Int]
var array2:Array<Int>

//创建有10个String类型元素的数组,并且每个元素都为字符串Hello
var array3 = [String](repeating: "hello", count: 10)
print(array3)
//同理的Int
var array4 = Array (repeating: 1, count: 10);
print(array4)
print(array4.contains(1))   //判断数组中是否包含某个元素
//数组排序
var arraySort = [1, 3, 5, 6, 7]
arraySort = arraySort.sorted(by: >)   //从大到小
arraySort = arraySort.sorted(by: <)   //从小到大
print(arraySort.max()!)   //获取数组中的最大值
print(arraySort.min()!)   //获取数组中的最小值

gather

//集合
var set1:Set<Int> = [1, 2, 3, 4]
var set2 = Set(arrayLiteral: 1, 2, 3, 4)
print(set1.isEmpty)
print(set1.contains(1))   //是否包含1
set1.insert(5)
set1.remove(1)
set1.removeFirst()
//set1.remove(at: set1.firstIndex(of: 2)!)   //移除集合中某个位置的元素
for item in set1.sorted(by: >) {
    
    
    print(item)   //从大到小排序再遍历集合
}

dictionary

//字典
var dic1:[Int: String]
var dic2:Dictionary<Int, String>
var dic3 = [1: "one"]
dic1 = [1:"1", 2:"2", 3:"3"]
dic2 = Dictionary(dictionaryLiteral: (1, "1"), (2, "2"), (3, "3"))

cycle printing

//循环打印
for i in 1...7 {
    
    
    print(i, terminator: " ")
}

function

//函数
func hanshu(param:Int) -> Int {
    
    
    return param + 1;
}

overload

func addFunc(param1:Int, param2:Int)->Int {
    
    
    return param1 + param2
}
func addFunc(param1:Double, param2:Double)->Double {
    
    
    return param1 + param2
}
func addFunc(param1:String, param2:String)->String {
    
    
    return param1 + param2
}
print(addFunc(param1: 5, param2: 10));
print(addFunc(param1: 1.52, param2: 3.61))
print(addFunc(param1: "123", param2: "abc"))

Classes and Inheritance

//类和继承(final阻止继承和重写)
var car1 = Car(tyreCount: 4)
car1.drive()
var boat1 = Boat(floor: 50)
boat1.drive()

set, get method

//set、get方法
let teacher = Teacher1()
teacher.memberAge = -1
teacher.memberName = ""
print(teacher.description)

SnapKit third-party library usage (Masonry)

The role and usage of this third-party library and Masonry are very similar

            leftLabel.snp.makeConstraints {
    
     make in
                make.left.equalTo(self).offset(30)
                make.top.equalTo(self).offset(Int(SIZE_HEIGHT) / 5 + i * (Int(SIZE_WIDTH) / 6) + Int(SIZE_WIDTH) / 10)
                make.width.equalTo(SIZE_WIDTH / 10)
                make.height.equalTo(SIZE_WIDTH / 10)
            }

Among them, we see that the difference from oc is that Int(SIZE_HEIGHT)this block has mandatory type conversion. The reason for this is that Swift is a very safe language, so the types must be the same. SIZE_WIDTH is a floating-point constant, and i is an Int. Type variables, so different types cannot be calculated together.

With the foundation of oc, it is easier to learn about swift, and you can find some projects to practice your hands to get started.

Codable(JSONModel)

This library is official and can be used directly without a guide. The usage is similar to JSONModel, with some small differences, but it feels better to use:

    struct DailyNews: Codable {
    
    
        let date: String
        let stories: [Story]
        let topStories: [TopStory]

        enum CodingKeys: String, CodingKey {
    
    
            case date, stories
            case topStories = "top_stories"
        }
    }

    struct Story: Codable {
    
    
        let imageHue: String
        let title: String
        let url: String
        let hint: String
        let gaPrefix: String
        let images: [String]
        let type: Int
        let id: Int

        enum CodingKeys: String, CodingKey {
    
    
            case imageHue = "image_hue"
            case title, url, hint
            case gaPrefix = "ga_prefix"
            case images, type, id
        }
    }

    struct TopStory: Codable {
    
    
        let imageHue: String
        let hint: String
        let url: String
        let image: String
        let title: String
        let gaPrefix: String
        let type: Int
        let id: Int

        enum CodingKeys: String, CodingKey {
    
    
           case imageHue = "image_hue"
           case hint, url, image, title
           case gaPrefix = "ga_prefix"
           case type, id
       }
    }
    func netWorkWithData2(){
    
    
        if let urlString = URL(string: "https://news-at.zhihu.com/api/4/news/latest") {
    
    
            let request = URLRequest(url: urlString)
            URLSession.shared.dataTask(with: request) {
    
     data, response, error in
                        
                guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
    
    
                    print("Invalid response")
                    return
                }
                            
                do {
    
    
                    let decoder = JSONDecoder()
                    //decoder.keyDecodingStrategy = .convertFromSnakeCase // 有需要则配置这个属性
                    let newsVersion = try decoder.decode(DailyNews.self, from: data!)
                    print(newsVersion.stories[0].title)
                } catch {
    
    
                    print(error.localizedDescription)
                }
                
            }.resume()
        }
    }

Alamofire (AFNetworking)

Alamofire.request("https://news-at.zhihu.com/api/4/news/latest").responseJSON {
    
     response in
            switch response.result {
    
    
                case .success(let value):
                    do {
    
    
                        let jsonData = try JSONSerialization.data(withJSONObject: value, options: [])
                        let decoder = JSONDecoder()
                        //decoder.keyDecodingStrategy = .convertFromSnakeCase
                        let latestNews = try decoder.decode(DailyNews.self, from: jsonData)
                        print(latestNews.stories[0].title)
                        // 解析成功,可以使用 latestNews 对象进行后续操作
                    } catch {
    
    
                        print(error)
                        // 解析错误,处理异常情况
                    }
                case .failure(let error):
                    // 请求失败
                    print(error)
                }
        }

The usage is basically the same as AFNetworking, and the middle part is to parse the requested data with Codable.

Guess you like

Origin blog.csdn.net/m0_62386635/article/details/131114669