String
Swift的字符串类型String
,跟OC的NSString
,在API设计上还是有较大差异:
// 空字符串
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"
print(str.count, str.startIndex, str.endIndex)
// 3 Index(_rawBits: 1) Index(_rawBits: 196609)
- 注意:
startIndex
代表1后面位置,endIndex
代表2后面位置 -
insert("" , at:)
只能插入字符 -
insert(contentsOf: "", at: )
插入字符串
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))
// 从startIndex开始偏移4,插入hello
str.insert(contentsOf: "hello", at: str.index(str.startIndex, offsetBy: 4))
// 1666hello_2_3_8884
// 删除第一个字符
str.remove(at: str.firstIndex(of: "1")!) // 666hello_2_3_8884
// 删除含有6的字符
str.removeAll { $0 == "6" } //hello_2_3_8884
// 删除范围
var range = str.index(str.endIndex, offsetBy: -4)..<str.index(before: str.endIndex)
str.removeSubrange(range) //hello_2_3_4
Substring 子串
String可以通过下标、 prefix、 suffix等截取子串,子串类型不是String,而是Substring
var str = "1_2_3_4_5"
// 截取前3个字符的子串
var substr1 = str.prefix(3) //1_2
// 截取后3个字符的子串
var substr2 = str.suffix(3) // 4_5
// 1_2 从开始截取3个字符
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)
- Substring和它的base,共享字符串数据
- Substring发生
修改
或者转为String
时,会分配新的内存存储字符串数据
String 与 Character
for c in "jack" { // c是Character类型
print(c)
}
var str = "jack"
// c是Character类型
var c = str[str.startIndex]
String相关的协议
BidirectionalCollection 协议包含的部分内容:
- startIndex 、 endIndex 属性、index 方法
-
String
、Array
都遵守了这个协议
RangeReplaceableCollection 协议包含的部分内容:
- append、insert、remove 方法
-
String
、Array
都遵守了这个协议
Dictionary、Set 也有实现上述协议中声明的一些方法,只是并没有遵守上述协议
多行String
多行字符串: 三个双引号开头, 三个双引号结尾的字符串
- 注意: 字符串内容是按照最后一个三双引号对齐.
let str = """
1
"2"
3
'4'
"""
print(str)
打印结果:
1
"2"
3
'4'
// 以下2个字符串是等价的
let str1 = "These are the same."
let str2 = """
These are the same.
"""
// 如果要显示3引号,至少转义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 """
//缩进以结尾的3引号为对齐线
let str = """
1
"2"
3
'4'
"""
print(str)
打印结果:
1
"2"
3
'4'
String 与 NSString
1> String 与 NSString 之间可以随时随地桥接转换
- 如果你觉得String的API过于复杂难用,可以考虑将String转为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)
- 注意: String 与 NSString 之间桥接后是两个不同类型, 修改内容互补影响.
2> 比较字符串内容是否等价
- String使用 == 运算符
- NSString使用isEqual方法,也可以使用 == 运算符(本质还是调用了isEqual方法)
3> Swift、OC桥接转换表
- String与NSString可以互相桥接转换
- String不能桥接转换成NSMutableString
总结:
- 桥接指的是通过
as
as?
as!
转换类型 - Swift中
String
\Array
\Dictionary
\Set
可以和OC不可变类型相互桥接转换 - OC可变类型可以桥接转换成Swift中对应的
String
\Array
\Dictionary
\Set
- Swift中
String
\Array
\Dictionary
\Set
桥接转换成OC可变类型. 但可以创建新的可变类型存储内容.
var str = "123456"
//String 不能桥接转换为 NSMutableString
var str2 = str as? NSMutableString // nil
var str3 = NSMutableString(string: str) //123456
问题: Person 继承NSObject, 内存是否有变化?
class Person :NSObject{
var age = 10
var weight = 20
}
var p = Person()
答:
Person 继承NSObject, 内存是有变化的.
- Swift中 p占32个字节: 8个字节 metadata, 8个字节 引用计数相关, 8个字节 age , 8个字节weight
- OC中 p占32个字节: 8个字节 isa指针, 8个字节 age, 8个字节weight, 最后8个字节凑数
只能被class继承的协议
只能被class继承的协议, 如下三种方式:
protocol Runnable1: AnyObject {}
protocol Runnable2: class {}
@objc protocol Runnable3 {}
被 @objc 修饰的协议,还可以暴露给OC去遵守实现
可选协议
- 可以通过
@objc
定义可选协议,这种协议只能被class
遵守 - 还可以通过
extension
定义可选协议
@objc protocol Runnable {
func run1()
@objc optional func run2()
func run3()
}
extension Runnable {
func run2() { print("Dog run2") }
}
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
修饰的内容会具有动态性,比如调用方法会走runtime
那一套流程
class Dog: NSObject {
@objc dynamic func test1() {}
func test2() {}
}
var d = Dog()
d.test1()
d.test2()
KVC\KVO
Swift 支持 KVC \ KVO 的条件
- 属性所在的类、监听器最终继承自
NSObject
- 用
@objc dynamic
修饰对应的属性
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")
关联对象(Associated Object)
- 在Swift中,
class
依然可以使用关联对象 - 默认情况,
extension
不可以增加存储属性
- 借助关联对象,可以实现类似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)
-
这种做法实际上是参考了Android的资源名管理方式
-
实现原理:
enum R {
enum string: String {
case add = "添加"
}
enum image: String {
case logo
}
enum segue: String {
case login_main
}
}
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)
}
}
}
更多优秀的思路参考
https://github.com/mac-cain13/R.swift
https://github.com/SwiftGen/SwiftGen
多线程开发 – 异步
public typealias Task = () -> Void
public struct Asyncs {
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) {
//DispatchWorkItem(block:) 包装任务
let item = DispatchWorkItem(block: task)
DispatchQueue.global().async(execute: item)
if let main = mainTask {
//item 任务执行完后, 执行notify(), 执行主任务
item.notify(queue: DispatchQueue.main, execute: main)
}
}
}
调用:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Asyncs.async {
print(1)
}
Asyncs.async({
print(1, Thread.current)
}) {
print(2, Thread.current)
}
}
}
/*
1
1 <NSThread: 0x600000805c00>{number = 4, name = (null)}
2 <NSThread: 0x600000840e40>{number = 1, name = main}
*/
多线程开发 – 延迟
asyncAfter()
延迟
@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
}
多线程开发 – 异步延迟
@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
}
多线程开发 – once
-
dispatch_once
在Swift中已被废弃,取而代之 - 可以用
类型属性
或者全局变量\常量
- 默认自带
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
}
}
多线程开发 – 加锁
- 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
}
}
- NSLock() 互斥锁
但是有递归调用会死锁
private static var lock = NSLock()
static func set(_ key: String, _ value: Any) {
lock.lock()
defer { lock.unlock() }
}
- NSRecursiveLock() 递归锁
private static var lock = NSRecursiveLock()
static func set(_ key: String, _ value: Any) {
lock.lock()
defer { lock.unlock() }
}
网友评论