swift基础语法
常量(let关键字)
只能赋值一次
它的值不要求在编译时期确定,但使用之前必须赋值一次
变量(var关键字)
可以被赋值多次
跟常量一样,在使用之前必须给他赋值,否则编译器会报错
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)
元组
var pen:(name:String, price:Int) = ("英雄", 15);
pen.name = "毕加索"
var car:(String, Int) = ("奔驰", 9999)
car.0 = "宝马"
var (theName, thePrice) = car
print(theName, thePrice)
typealias(类似之前的typedef)
typealias Price = Int
var penPrice:Price = 100
if-let
var product:Int? = 100
if let weight = product, (weight > 30) {
print("666")
}
String类基本用法
//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(类比于c中的sizeof)
//MemoryLayout(类比于c中的sizeof)
print(MemoryLayout<String>.size)
数组
//数组
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()!) //获取数组中的最小值
集合
//集合
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) //从大到小排序再遍历集合
}
字典
//字典
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"))
循环打印
//循环打印
for i in 1...7 {
print(i, terminator: " ")
}
函数
//函数
func hanshu(param:Int) -> Int {
return param + 1;
}
重载
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"))
类和继承
//类和继承(final阻止继承和重写)
var car1 = Car(tyreCount: 4)
car1.drive()
var boat1 = Boat(floor: 50)
boat1.drive()
set、get方法
//set、get方法
let teacher = Teacher1()
teacher.memberAge = -1
teacher.memberName = ""
print(teacher.description)
SnapKit第三方库用法(Masonry)
这个第三方库和Masonry的作用和用法都很相似
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)
}
其中这块我们看到和oc不同的是Int(SIZE_HEIGHT)
这块有个强制类型转化,这块原因是因为Swift是一个非常安全的语言,所以类型必须是相同的SIZE_WIDTH是一个浮点型常量,i是一个Int型变量,所以类型不同不能一起计算。
有了oc的基础,关于swift的学习比较容易,可以找一些项目练练手更好入手。
Codable(JSONModel)
这个库是官方的,不用导直接能用,用法和JSONModel类似,有一些小区别,但是感觉更好用一下:文章来源:https://www.toymoban.com/news/detail-481267.html
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)
}
}
用法和AFNetworking也基本相同,中间部分是将请求到的数据用Codable解析。文章来源地址https://www.toymoban.com/news/detail-481267.html
到了这里,关于【iOS】—— swift基础语法及一些第三方库使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!