参考链接
1、extension UIView
extension UIView {
func addSubviews(_ subviews: UIView...) {
subviews.forEach(addSubview)
}
}
lazy var view1: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 200))
view.backgroundColor = .red
return view
}()
lazy var view2: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 300, width: 100, height: 200))
view.backgroundColor = .green
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubviews(view1,view2)
}
forEach与forin的区别
let array = ["one", "two", "three", "four"]
array.forEach { (element) in
if element == "two" {
return
}
print("foreach:" + element)
}
result:
foreach:one
foreach:three
foreach:four
let array = ["one", "two", "three", "four"]
for element in array {
if element == "two" {
return
}
print("forin:" + element)
}
result:
forin:one
在ForIn 循环中使用return的话,会立即跳出当前的循环体。然而在forEach中,还会继续遍历剩余元素。
2、extension UILabel
extension UILabel {
static func initForTitle() -> UILabel {
let label = UILabel()
label.font = .boldSystemFont(ofSize: 27)
label.textColor = .darkGray
label.numberOfLines = 1
//根据label的宽度自动更改文字的大小
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.2
//文本基线的行为
// label.baselineAdjustment = .alignBaselines
label.textAlignment = .center
label.backgroundColor = .red
return label
}
}
func test() {
let label = UILabel.initForTitle()
label.frame = CGRect(x: 0, y: 600, width: 400, height: 80)
label.text = "中华人民共和国"
view.addSubview(label)
}
3、extension UIColor
extension UIColor {
// UIColor(r: 95, g: 199, b: 220)
convenience init(r: Int, g: Int, b: Int) {
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1.0)
}
// UIColor(hex: 0x5fc7dc)
convenience init(hex:Int) {
self.init(r:(hex >> 16) & 0xff, g:(hex >> 8) & 0xff, b:hex & 0xff)
}
}
label.textColor = UIColor(hex: 0x5fc7dc)
4、滑动关闭键盘
// Dismiss your keyboard when you are
// scrolling your tableView down interactively.
tableView.keyboardDismissMode = .interactive
5、自动填充
// To enable security code autofill on a UITextField we need to set the textContentType property to .oneTimeCode.
otpTextField.textContentType = .oneTimeCode
6、数组筛选
let array = [1, 4, 6, 7, 8]
let sort = array.filter {$0 % 2 == 0}
print(sort)//[4, 6, 8]
let array2 = ["a", "12", "csd", "4567", "88888"]
let sort2 = array2.filter {$0.count > 3}
print(sort2)//["4567", "88888"]
7、guard 校验
/*
What makes the “guard” statement truly stand out,
however, is that unwrapped optional values remain
available in the rest of the code block.
*/
private func fetchContents() {
webService.fetchCategories { [weak self] (response) in
// Optional Binding for self
guard let self = self else { return }
self.createloadMoreRequest(content: response)
}
}
private func createloadMoreRequest(content: Content?) {
// Optional Binding for content
guard let content = content else { return }
let categoryId = content.categoryId
self.loadMore(id: categoryId)
}
8.array的操作
// Use .first(where: (Int) throws -> Bool)
// to retrieve first elemen in an array which contains
// the same conditional objects.
let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let firstNegative = numbers.first(where: { $0 < 0 }) {
print("The first negative number is \(firstNegative).")
}
// Prints "The first negative number is -2."
9.array判断条件
// The following code uses this method to test whether all
// the names in an array have at least five characters:
let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 })
// allHaveAtLeastFive == true
//是否都小于10
let digits = 0...9
let areAllSmallerThanTen = digits.allSatisfy { $0 < 10 }
print(allHaveAtLeastFive,areAllSmallerThanTen)
10.defer延迟执行
override func viewDidLoad() {
super.viewDidLoad()
print("start")
test()
print("end")
}
func test() {
defer { print("End of the function") }
print("Main body of the simleDefer function")
}
//start
//Main body of the simleDefer function
//End of the function
//end
11.inout的使用
func test() {
var n1 = 10, n2 = 20
swapNumber(num1: &n1, num2: &n2)
print(n1,n2)
}
func swapNumber( num1: inout Int, num2: inout Int) {
let temp = num1
num1 = num2
num2 = temp
}
12.准换大小写
let cast = ["Name", "NAME", "namE"]
let lowerCast = cast.map { $0.lowercased() }
print(lowerCast)//["name", "name", "name"]
let count = cast.map { $0.count }
print(count)//[4, 4, 4]
13.筛选
let array = ["1", "3", "three", "4///", "5", "let"]
let numberArray: [Int?] = array.map { Int($0) }
let number2Array:[Int] = array.compactMap { Int($0) }
print(numberArray)//[Optional(1), Optional(3), nil, nil, Optional(5), nil]
print(number2Array)//[1, 3, 5]
14.排序
let array = [11, 3, 25, 17]
let sorted = array.sorted(by: >)
print(sorted)//[25, 17, 11, 3]
15.自定义运算符
- inflx 中
infix operator ∈
func ∈ (lhs: T, rhs: [T]) -> Bool {
return rhs.contains(lhs)
}
let month = "September"
if month ∈ ["April", "June", "September", "November"] {
print("\(month) has 30 days.")
}
//September has 30 days.
- prefix
// 前置:返回2的n次方
prefix operator ^
prefix func ^ (vector: Double) -> Double {
return pow(2, vector)
}
print(^5) // 32.0
- postfix
postfix operator ^
postfix func ^ (vector: Int) -> Int {
return vector * vector
}
print(5^) // 25
16.获取枚举中有多少个case(swift4.2新特性)
enum CompassDirection: CaseIterable {
case east, west, south, north
}
override func viewDidLoad() {
super.viewDidLoad()
print("there are \(CompassDirection.allCases.count) directions")
for direction in CompassDirection.allCases {
print("i want to go \(direction)")
}
}
there are 4 directions
i want to go east
i want to go west
i want to go south
i want to go north
17.对数组进行乱序操作
var array = ["name", 1, true, "age", 6, "liuxingxing"] as [Any]
let shuffledArray = array.shuffled()
print(shuffledArray)
array.shuffle()
print(array)
[6, "age", "name", true, 1, "liuxingxing"]
[6, "liuxingxing", true, "name", "age", 1]
18.计算属性
class Person {
var name: String?
var surname: String?
var fullname: String? {
guard let name = name, let surname = surname else {
return nil
}
return "\(name)\(surname)"
}
}
let person = Person()
person.name = "xingxing"
person.surname = "liu"
print(person.fullname)
19.静态属性
struct Constant {
static let baseUrl = "https://xxxxxxx"
static let backgroundColor = UIColor.red
}
override func viewDidLoad() {
super.viewDidLoad()
let myUrl = URL(string: Constant.baseUrl)
view.backgroundColor = Constant.backgroundColor
}
20.类方法与静态方法(类方法子类可以重写,静态方法没法重写)
error: Cannot override static method
class Service {
class func fetchData() {
print("this is Service")
}
static func sendData() {
print("this is static method")
}
}
class MovieService: Service {
override class func fetchData() {
print("this is movieService")
}
//error: Cannot override static method
// override static func sendData() {
// print("this is movieService")
// }
}
21.懒加载
class DataImporter {
//假使这个类需要初始化需要很长时间
var filename = "data.text"
}
class DataManager {
lazy var importer = DataImporter()
var data = [String]()
}
override func viewDidLoad() {
super.viewDidLoad()
let manager = DataManager()
manager.data.append("a data")
manager.data.append("more data")
//此时DataImporter的实例还没有被初始化
}
22.当函数有返回值时,却没有接收这个返回值,会发生警告Result of call to 'add()' is unused
,可以通过@discardableResult
来抑制该警告
var number = 10
override func viewDidLoad() {
super.viewDidLoad()
//Result of call to 'add()' is unused
add()
print(number)
}
@discardableResult
func add() -> Int {
number += 1
return number
}
23.使用元组作为返回值
override func viewDidLoad() {
super.viewDidLoad()
let statistics = calculate(scores: [1, 2, 3, 4, 5])
print(statistics.max)//5
print(statistics.min)//1
print(statistics.sum)//15
print(statistics.2)//15
}
func calculate(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
guard let min = scores.min(), let max = scores.max() else {
fatalError("scores is nil")
}
//map,reduce,filter
//public func reduce(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
//0 是为 initialResultw赋值的,为初始化值
let sum = scores.reduce(0){ $0 + $1 }//如果将0更改为5,那么sum将由15更改为20
// let numberSum = numbers.reduce(0, { x, y in
// x + y
// })
return (min, max, sum)
}
24.属性观察者
struct MyClass {
var name: String {
willSet {
print("value is \(name)")
print("value will be \(newValue)")
}
didSet {
print("value is \(name)")
print("value was \(oldValue)")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
var test = MyClass(name: "LXX")//此时并未调用willset和didSet,数据"再次赋值"的时候才会调用,即使和原来的值一样也会再次调用
test.name = "DLL"
}
value is LXX
value will be DLL
value is DLL
value was LXX
25.属性只读public private(set)
struct MyClass {
public private(set) var name: String
}
override func viewDidLoad() {
super.viewDidLoad()
var test = MyClass(name: "LXX")
print(test.name)
//编译错误:Cannot assign to property: 'name' setter is inaccessible
//test.name = "DLL"
}
26.数组拼接成字符串,字符串拆分成数组
override func viewDidLoad() {
super.viewDidLoad()
let names = ["DLL", "LXX", "LMY"]
let nameString = names.joined()
print(nameString)//默认拼接
let nameString2 = names.joined(separator: "-")
print(nameString2)//以"-"拼接
let array = nameString2.split(separator: "-")
print(array)//以"-"拆分成c数组
}
DLLLXXLMY
DLL-LXX-LMY
["DLL", "LXX", "LMY"]
27.switch的"穿透"效果
override func viewDidLoad() {
super.viewDidLoad()
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also"
fallthrough
default:
description += " an integer."
}
print(description)
}
The number 5 is a prime number, and also an integer.
28.泛型函数
override func viewDidLoad() {
super.viewDidLoad()
var num1 = 3
var num2 = 9
swapTwoValues(&num1, &num2)
print(num1)
print(num2)
}
func swapTwoValues(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
29.快速交换
override func viewDidLoad() {
super.viewDidLoad()
var num1 = "abc"
var num2 = "efg"
var num3 = "hij"
print(num1)
print(num2)
print(num3)
(num1, num2, num3) = (num2, num3, num1)
print(num1)
print(num2)
print(num3)
}
abc
efg
hij
efg
hij
abc
30.Builder Pattern
protocol Builder {}
extension Builder {
public func with(configure: (inout Self) -> Void) -> Self {
var this = self
configure(&this)
return this
}
}
//让NSObject遵守该协议
extension NSObject: Builder {}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// let tab = UITableView().with(configure: <#T##(inout UITableView) -> Void#>)
private let baseTableView = UITableView(frame: CGRect(x: 0, y: 0, width: 100, height: 200), style: .plain).with { (tableView) in
tableView.backgroundColor = .red
tableView.separatorColor = .darkGray
tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 10.0, right: 0)
tableView.allowsMultipleSelection = true
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.frame = CGRect(x: 100, y: 200, width: 300, height: 300)//此时这里的位置是有效的
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(baseTableView)
baseTableView.delegate = self
baseTableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "99999"
return cell
}
}