肖卧、、
// : 類似于OC中的 #pragma mark
// : - 類似于OC中的 #pragma mark -
// : 用于標(biāo)記未完成的任務(wù)
// : 用于標(biāo)記待修復(fù)的問題
條件編譯
// 操作系統(tǒng):macOS\iOS\tvOS\watchOS\Linux\Android\Windows\FreeBSD
#if os(macOS) || os(iOS)
// CPU架構(gòu):i386\x86_64\arm\arm64
#elseif arch(x86_64) || arch(arm64)
// swift版本
#elseif swift(<5) && swift(>=3)
// 模擬器
#elseif targetEnvironment(simulator) // 可以導(dǎo)入某模塊
#elseif canImport(Foundation)
#else
#endif
條件編譯
// debug模式
#if DEBUG
// release模式
#else
#endif
#if TEST
print("test")
#endif
#if OTHER
print("other")
#endif
打印
func log<T>(_ msg: T,
file: NSString = #file,
line: Int = #line,
fn: String = #function) {
#if DEBUG
let prefix = "\(file.lastPathComponent)_\(line)_\(fn):" print(prefix, msg)
#endif
}
系統(tǒng)版本檢測
if #available(iOS 10, macOS 10.12, *) {
// 對于iOS平臺骄呼,只在iOS10及以上版本執(zhí)行
// 對于macOS平臺淋硝,只在macOS 10.12及以上版本執(zhí)行
// 最后的*表示在其他所有平臺都執(zhí)行
}
API 可用性說明
@available(iOS 10, macOS 10.15, *)
class Person {}
struct Student {
@available(*, unavailable, renamed: "study")
func study_() {}
func study() {}
@available(iOS, deprecated: 11)
@available(macOS, deprecated: 10.12)
func run() {}
}
iOS程序的入口
- 在AppDelegate上面默認(rèn)有個@UIApplicationMain標(biāo)記疮鲫,這表示
□ 編譯器自動生成入口代碼(main函數(shù)代碼),自動設(shè)置AppDelegate為APP的代理
□ 也可以刪掉@UIApplicationMain,自定義入口代碼:新建一個main.swift文件
Swift 調(diào)用 OC
- 新建1個橋接頭文件可帽,文件名格式默認(rèn)為:{targetName}-Bridging-Header.h
- 在{targetName}-Bridging-Header.h 文件中#import OC需要暴露給Swift的內(nèi)容
#import "MJPerson.h"
Swift 調(diào)用 OC – MJPerson.h
int sum(int a, int b);
@interface MJPerson : NSObject
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *name;
- (instancetype)initWithAge:(NSInteger)age name:(NSString *)name;
+ (instancetype)personWithAge:(NSInteger)age name:(NSString *)name;
- (void)run;
+ (void)run;
- (void)eat:(NSString *)food other:(NSString *)other;
+ (void)eat:(NSString *)food other:(NSString *)other;
@end
Swift 調(diào)用 OC – MJPerson.m
@implementation MJPerson
- (instancetype)initWithAge:(NSInteger)age name:(NSString *)name {
if (self = [super init]) {
self.age = age;
self.name = name;
}
return self;
}
+ (instancetype)personWithAge:(NSInteger)age name:(NSString *)name {
return [[self alloc] initWithAge:age name:name];
}
+ (void)run { NSLog(@"Person +run"); }
- (void)run { NSLog(@"%zd %@ -run", _age, _name); }
+ (void)eat:(NSString *)food other:(NSString *)other { NSLog(@"Person +eat %@ %@", food, other); }
- (void)eat:(NSString *)food other:(NSString *)other { NSLog(@"%zd %@ -eat %@ %@", _age, _name, food, other); }
@end
int sum(int a, int b) { return a + b; }
Swift 調(diào)用 OC – Swift代碼
var p = MJPerson(age: 10, name: "Jack")
p.age = 18
p.name = "Rose"
p.run() // 18 Rose -run
p.eat("Apple", other: "Water") // 18 Rose -eat Apple Water
MJPerson.run() // Person +run
MJPerson.eat("Pizza", other: "Banana") // Person +eat Pizza Banana
print(sum(10, 20)) // 30
Swift 調(diào)用 OC – @_silgen_name
如果C語言暴露給Swift的函數(shù)名跟Swift中的其他函數(shù)名沖突了
可以在Swift中使用 @_silgen_name 修改C函數(shù)名
// C語言
int sum(int a, int b) {
return a + b;
}
// Swift
@_silgen_name("sum") func swift_sum(_ v1: Int32, _ v2: Int32) -> Int32
print(swift_sum(10, 20)) // 30
print(sum(10, 20)) // 30
OC 調(diào)用 Swift
- Xcode已經(jīng)默認(rèn)生成一個用于OC調(diào)用Swift的頭文件擦盾,文件名格式是: {targetName}-Swift.h
OC 調(diào)用 Swift – Car.swift
import Foundation
@objcMembers class Car: NSObject {
var price: Double
var band: String
init(price: Double, band: String) {
self.price = price
self.band = band
}
func run() { print(price, band, "run") }
static func run() { print("Car run") }
}
extension Car {
func test() { print(price, band, "test") }
}
Swift暴露給OC的類最終繼承自NSObject
使用@objc修飾需要暴露給OC的成員
-
使用@objcMembers修飾類
代表默認(rèn)所有成員都會暴露給OC(包括擴展中定義的成員)
最終是否成功暴露,還需要考慮成員自身的訪問級別
OC 調(diào)用 Swift – {targetName}-Swift.h
- Xcode會根據(jù)Swift代碼生成對應(yīng)的OC聲明系忙,寫入{targetName}-Swift.h 文件
@interface Car : NSObject
@property (nonatomic) double price;
@property (nonatomic, copy) NSString * _Nonnull band;
- (nonnull instancetype)initWithPrice:(double)price band:(NSString * _Nonnull)band OBJC_DESIGNATED_INITIALIZER; - (void)run;
+ (void)run;
- (nonnull instancetype)init SWIFT_UNAVAILABLE;
+ (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable");
@end
@interface Car (SWIFT_EXTENSION(備課_Swift))
- (void)test;
@end
OC 調(diào)用 Swift – OC代碼
#import "備課_Swift-Swift.h" int sum(int a, int b) {
Car *c = [[Car alloc] initWithPrice:10.5 band:@"BMW"];
c.band = @"Bently";
c.price = 108.5;
[c run]; // 108.5 Bently run
[c test]; // 108.5 Bently test
[Car run]; // Car run
return a + b;
}
OC 調(diào)用 Swift – @ objc
- 可以通過@objc 重命名Swift暴露給OC的符號名(類名诵盼、屬性名、函數(shù)名等)
@objc(MJCar)
@objcMembers class Car: NSObject {
var price: Double
@objc(name)
var band: String
init(price: Double, band: String) {
self.price = price
self.band = band
}
@objc(drive)
func run() { print(price, band, "run") } static func run() { print("Car run") }
}
extension Car {
@objc(exec:v2:)
func test() { print(price, band, "test") }
}
MJCar *c = [[MJCar alloc] initWithPrice:10.5 band:@"BMW"]; c.name = @"Bently";
c.price = 108.5;
[c drive]; // 108.5 Bently run
[c exec:10 v2:20]; // 108.5 Bently test
[MJCar run]; // Car run
選擇器(Selector)
Swift中依然可以使用選擇器银还,使用#selector(name)定義一個選擇器
必須是被@objcMembers或@objc修飾的方法才可以定義選擇器
@objcMembers class Person: NSObject {
func test1(v1: Int) { print("test1") }
func test2(v1: Int, v2: Int) { print("test2(v1:v2:)") }
func test2(_ v1: Double, _ v2: Double) { print("test2(_:_:)") }
func run() {
perform(#selector(test1))
perform(#selector(test1(v1:)))
perform(#selector(test2(v1:v2:)))
perform(#selector(test2(_:_:)))
perform(#selector(test2 as (Double, Double) -> Void))
}
}
String
- Swift的字符串類型String风宁,跟OC的NSString,在API設(shè)計上還是有較大差異
// 空字符串
var emptyStr1 = ""
var emptyStr2 = String()
var str: String = "1"
// 拼接蛹疯,jack_rose
str.append("_2")
// 重載運算符 +
str = str + "_3"
// 重載運算符 +=
str += "_4"
// \()插值
str = "\(str)_5"
// 長度戒财,9,1_2_3_4_5
print(str.count)
var str = "123456"
print(str.hasPrefix("123")) // true
print(str.hasSuffix("456")) // true
String的插入和刪除
var str = "1_2"
// 1_2_
str.insert("_", at: str.endIndex)
// 1_2_3_4
str.insert(contentsOf: "3_4", at: str.endIndex)
// 1666_2_3_4
str.insert(contentsOf: "666", at: str.index(after: str.startIndex))
// 1666_2_3_8884
str.insert(contentsOf: "888", at: str.index(before: str.endIndex))
// 1666hello_2_3_8884
str.insert(contentsOf: "hello", at: str.index(str.startIndex, offsetBy: 4))
// 666hello_2_3_8884
str.remove(at: str.firstIndex(of: "1")!)
// hello_2_3_8884
str.removeAll { $0 == "6" }
var range = str.index(str.endIndex, offsetBy: -4)..<str.index(before: str.endIndex)
// hello_2_3_4
str.removeSubrange(range)
Substring
String可以通過下標(biāo)捺弦、 prefix饮寞、 suffix等截取子串孝扛,子串類型不是String,而是Substring
Substring和它的base幽崩,共享字符串?dāng)?shù)據(jù)
Substring發(fā)生修改 或者 轉(zhuǎn)為String時苦始,會分配新的內(nèi)存存儲字符串?dāng)?shù)據(jù)
var str = "1_2_3_4_5"
// 1_2
var substr1 = str.prefix(3)
// 4_5
var substr2 = str.suffix(3)
// 1_2
var range = str.startIndex..<str.index(str.startIndex, offsetBy: 3)
var substr3 = str[range]
// 最初的String,1_2_3_4_5
print(substr3.base)
// Substring -> String
var str2 = String(substr3)
String 與 Character
for c in "jack" { // c是Character類型
print(c)
}
var str = "jack"
// c是Character類型
var c = str[str.startIndex]
String相關(guān)的協(xié)議
-
BidirectionalCollection 協(xié)議包含的部分內(nèi)容
startIndex 慌申、 endIndex 屬性陌选、index 方法
String、Array 都遵守了這個協(xié)議
-
RangeReplaceableCollection 協(xié)議包含的部分內(nèi)容
append蹄溉、insert咨油、remove 方法
String、Array 都遵守了這個協(xié)議
Dictionary柒爵、Set 也有實現(xiàn)上述協(xié)議中聲明的一些方法臼勉,只是并沒有遵守上述協(xié)議
多行String
let str = """
1
"2"
3
'4'
"""
1
"2"
3"""
'4'
// 以下2個字符串是等價的
let str1 = "These are the same."
let str2 = """
These are the same.
"""
// 如果要顯示3引號,至少轉(zhuǎn)義1個引號
let str = """
Escaping the first quote \"""
Escaping two quotes \"\""
Escaping all three quotes \"\"\"
Escaping the first quote """
Escaping two quotes """
Escaping all three quotes """
/ 縮進(jìn)以結(jié)尾的3引號為對齊線
let str = """
1
2
3
4
"""
1
2
3
4
String 與 NSString
- String 與 NSString 之間可以隨時隨地橋接轉(zhuǎn)換
□ 如果你覺得String的API過于復(fù)雜難用餐弱,可以考慮將String轉(zhuǎn)為NSString
var str1: String = "jack"
var str2: NSString = "rose"
var str3 = str1 as NSString
var str4 = str2 as String
// ja
var str5 = str3.substring(with: NSRange(location: 0, length: 2))
print(str5)
- 比較字符串內(nèi)容是否等價
□ String使用 == 運算符
□ NSString使用isEqual方法宴霸,也可以使用 == 運算符(本質(zhì)還是調(diào)用了isEqual方法)
Swift 、 OC 橋接轉(zhuǎn)換表
只能被class繼承的協(xié)議
protocol Runnable1: AnyObject {}
protocol Runnable2: class {}
@objc protocol Runnable3 {}
- 被@objc 修飾的協(xié)議膏蚓,還可以暴露給OC去遵守實現(xiàn)
可選協(xié)議
- 可以通過@objc 定義可選協(xié)議瓢谢,這種協(xié)議只能被class 遵守
@objc protocol Runnable {
func run1()
@objc optional func run2()
func run3()
}
class Dog: Runnable {
func run3() { print("Dog run3") }
func run1() { print("Dog run1") }
}
var d = Dog()
d.run1() // Dog run1
d.run3() // Dog run3
dynamic
- 被 @objc dynamic 修飾的內(nèi)容會具有動態(tài)性,比如調(diào)用方法會走runtime那一套流程
class Dog: NSObject {
@objc dynamic func test1() {}
func test2() {}
}
var d = Dog()
d.test1()
d.test2()
KVC KVO
- Swift 支持 KVC \ KVO 的條件
□ 屬性所在的類驮瞧、監(jiān)聽器最終繼承自 NSObject
□ 用 @objc dynamic 修飾對應(yīng)的屬性
class Observer: NSObject {
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
print("observeValue", change?[.newKey] as Any)
}
}
class Person: NSObject {
@objc dynamic var age: Int = 0
var observer: Observer = Observer()
override init() {
super.init()
self.addObserver(observer,
forKeyPath: "age",
options: .new,
context: nil)
}
deinit {
self.removeObserver(observer,
forKeyPath: "age")
}
}
var p = Person()
// observeValue Optional(20)
p.age = 20
// observeValue Optional(25)
p.setValue(25, forKey: "age")
block方式的 KVO
class Person: NSObject {
@objc dynamic var age: Int = 0
var observation: NSKeyValueObservation?
override init() {
super.init()
observation = observe(\Person.age, options: .new) {
(person, change) in
print(change.newValue as Any)
}
}
}
var p = Person()
// Optional(20)
p.age = 20
// Optional(25)
p.setValue(25, forKey: "age")
關(guān)聯(lián)對象(Associated Object)
- 在Swift中氓扛,class依然可以使用關(guān)聯(lián)對象
□ 默認(rèn)情況,extension不可以增加存儲屬性
□ 借助關(guān)聯(lián)對象论笔,可以實現(xiàn)類似extension為class增加存儲屬性的效果
class Person {}
extension Person {
private static var AGE_KEY: Void?
var age: Int {
get {
(objc_getAssociatedObject(self, &Self.AGE_KEY) as? Int) ?? 0
}
set {
objc_setAssociatedObject(self, &Self.AGE_KEY, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
}
var p = Person()
print(p.age) // 0
p.age = 10
print(p.age) // 10
資源名管理
let img = UIImage(named: "logo")
let btn = UIButton(type: .custom)
btn.setTitle("添加", for: .normal)
performSegue(withIdentifier: "login_main", sender: self)
let img = UIImage(R.image.logo)
let btn = UIButton(type: .custom)
btn.setTitle(R.string.add, for: .normal)
performSegue(withIdentifier: R.segue.login_main, sender: self)
enum R {
enum string: String {
case add = "添加" }
enum image: String {
case logo
}
enum segue: String {
case login_main
}
}
- 這種做法實際上是參考了Android的資源名管理方式
資源名管理
extension UIImage {
convenience init?(_ name: R.image) {
self.init(named: name.rawValue)
}
}
extension UIViewController {
func performSegue(withIdentifier identifier: R.segue, sender: Any?) {
performSegue(withIdentifier: identifier.rawValue, sender: sender)
}
}
extension UIButton {
func setTitle(_ title: R.string, for state: UIControl.State) {
setTitle(title.rawValue, for: state)
}
}
資源名管理的其他思路
let img = UIImage(named: "logo")
let font = UIFont(name: "Arial", size: 14)
let img = R.image.logo
let font = R.font.arial(14)
enum R {
enum image {
static var logo = UIImage(named: "logo") }
enum font {
static func arial(_ size: CGFloat) -> UIFont? {
UIFont(name: "Arial", size: size)
}
}
}
多 線程 開發(fā) – 異步
public typealias Task = () -> Void
public static func async(_task: @escaping Task) {
_async(task)
}
public static func async(_task: @escaping Task, mainTask: @escaping Task) { _
_async(task, mainTask)
}
private static func async(_ task: @escaping Task, _ mainTask: Task? = nil) {
let item = DispatchWorkItem(block: task)
DispatchQueue.global().async(execute: item)
if let main = mainTask {
item.notify(queue: DispatchQueue.main, execute: main)
}
}
多 線程 開發(fā) – 延遲
@discardableResult
public static func delay(_ seconds: Double,
_ block: @escaping Task) -> DispatchWorkItem {
let item = DispatchWorkItem(block: block)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + seconds,
execute: item)
return item
}
多 線程 開發(fā) – 異步延遲
@discardableResult
public static func asyncDelay(_ seconds: Double,
_ task: @escaping Task) -> DispatchWorkItem {
return _asyncDelay(seconds, task)
}
@discardableResult
public static func asyncDelay(_ seconds: Double,
_ task: @escaping Task,
_ mainTask: @escaping Task) -> DispatchWorkItem {
return _asyncDelay(seconds, task, mainTask)
}
private static func asyncDelay(_ seconds: Double,
_ task: @escaping Task,
_ mainTask: Task? = nil) -> DispatchWorkItem {
let item = DispatchWorkItem(block: task)
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + seconds, execute: item)
if let main = mainTask {
item.notify(queue: DispatchQueue.main, execute: main)
}
return item
}
多 線程 開發(fā) – once
- dispatch_once在Swift中已被廢棄采郎,取而代之
□ 可以用類型屬性或者全局變量\常量 □ 默認(rèn)自帶 lazy + dispatch_once 效果
fileprivate let initTask2: Void = {
print("initTask2---------")
}()
class ViewController: UIViewController {
static let initTask1: Void = {
print("initTask1---------")
}()
override func viewDidLoad() {
super.viewDidLoad()
let _ = Self.initTask1
let _ = initTask2
}
}
多 線程 開發(fā) – 加鎖
- gcd信號量
class Cache {
private static var data = [String: Any]()
private static var lock = DispatchSemaphore(value: 1)
static func set(_ key: String, _ value: Any) {
lock.wait()
defer { lock.signal() }
data[key] = value
}
}
- Foundation
private static var lock = NSLock()
static func set(_ key: String, _ value: Any) {
lock.lock()
defer { lock.unlock() }
}
private static var lock = NSRecursiveLock()
static func set(_ key: String, _ value: Any) {
lock.lock()
defer { lock.unlock() }
}