Swift源码简介
- Swift于2015年正式开源,github地址: https://github.com/apple/swift
- 几个可能会经常看的目录
- docs:一些文档
- stdlib:Swift源码
- lib:C++源码
- include:C++头文件
Array分析
map底层源码:
public func map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
let initialCapacity = underestimatedCount
var result = ContiguousArray<T>()
result.reserveCapacity(initialCapacity)
var iterator = self.makeIterator()
// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
result.append(try transform(iterator.next()!))
}
// Add remaining elements, if any.
while let element = iterator.next() {
result.append(try transform(element))
}
return Array(result)
}
filter底层源码:
@inlinable
public __consuming func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _filter(isIncluded)
}
@_transparent
public func _filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
var result = ContiguousArray<Element>()
var iterator = self.makeIterator()
while let element = iterator.next() {
if try isIncluded(element) {
result.append(element)
}
}
return Array(result)
}
- flatMap、compactMap、reduce
- https://github.com/apple/swift/blob/master/stdlib/public/core/SequenceAlgorithms.swift
flatMap底层源码:
@inlinable
public func flatMap<SegmentOfResult: Sequence>(
_ transform: (Element) throws -> SegmentOfResult
) rethrows -> [SegmentOfResult.Element] {
var result: [SegmentOfResult.Element] = []
for element in self {
result.append(contentsOf: try transform(element))
}
return result
}
}
reduce底层源码:
public func reduce<Result>(
into initialResult: __owned Result,
_ updateAccumulatingResult:
(_ partialResult: inout Result, Element) throws -> ()
) rethrows -> Result {
var accumulator = initialResult
for element in self {
try updateAccumulatingResult(&accumulator, element)
}
return accumulator
}
}
compactMap源码:
@inlinable // protocol-only
@inline(__always)
public func _compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
var result: [ElementOfResult] = []
for element in self {
if let newElement = try transform(element) {
result.append(newElement)
}
}
return result
}
SubString分析
- append、lowercased、uppercased
- https://github.com/apple/swift/blob/master/stdlib/public/core/Substring.swift
append底层源码:
@inlinable // specialize
public mutating func append<S: Sequence>(contentsOf elements: S)
where S.Element == Character {
var string = String(self)
self = Substring() // Keep unique storage if possible
string.append(contentsOf: elements)
self = Substring(string)
}
owercased、uppercased的底层源码:
extension Substring {
public func lowercased() -> String {
return String(self).lowercased()
}
public func uppercased() -> String {
return String(self).uppercased()
}
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> String {
return try String(self.lazy.filter(isIncluded))
}
}
Optional分析
map底层源码:
@inlinable
public func map<U>(
_ transform: (Wrapped) throws -> U
) rethrows -> U? {
switch self {
case .some(let y):
return .some(try transform(y))
case .none:
return .none
}
}
flatMap底层源码:
@inlinable
public func flatMap<U>(
_ transform: (Wrapped) throws -> U?
) rethrows -> U? {
switch self {
case .some(let y):
return try transform(y)
case .none:
return .none
}
}
map和flatMap代码结果对比:
var age: Int? = 10
var age2 = age.map { Optional.some($0 + 2)} //age2类型为Int??
var age3 = age.flatMap{Optional.some($0 + 2)} //age3类型为Int?
==的底层源码:
左边是可选型,右边是nil
public static func ==(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
switch lhs {
case .some:
return false
case .none:
return true
}
}
左边是nil,右边是可选型
public static func ==(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return false
case .none:
return true
}
}
两边都是可选型
public static func ==(lhs: Wrapped?, rhs: Wrapped?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l == r
case (nil, nil):
return true
default:
return false
}
}
三种底层代码调用的对比:
extension Optional where Wrapped: Equatable {
public static func ==(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
switch lhs {
case .some:
return false
case .none:
return true
}
}
public static func ==(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return false
case .none:
return true
}
}
public static func ==(lhs: Wrapped?, rhs: Wrapped?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l == r
case (nil, nil):
return true
default:
return false
}
}
}
var age1: Int??? = nil
var age2: Int? = nil
print(age1 == age2) //false 进入 == 方法后,age1为Int???类型, age2转化为Int???, 解包后age1为nil,age2为可选型,所以不等
var age3: Int??? = 10
var age4: Int? = 10
print(age3 == age4) //true 进入 == 方法后,age3为Int???类型, age4转化为Int???, 解包后age3为10,age4为10,比的是值,所以相等
??的底层源码:
左右两边可选型不一致(问号数不一致):
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T)
rethrows -> T {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
左右两边可选型一致(问号数一致):
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T?)
rethrows -> T? {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
上面两种方法的调用对比:
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T)
rethrows -> T {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T?)
rethrows -> T? {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
var age1: Int? = 10
var age2: Int = 10
print(age1 ?? age2) //10
var age3: Int?? = 10
var age4: Int? = 10
print(age3 ?? age4) //Optional(10)
var age5: Int?? = nil
var age6: Int = 10
print(age5 ?? age6) //Optional(10)
Metadata分析
- 文档: https://github.com/apple/swift/blob/master/docs/ABI/TypeMetadata.rst
- 其他参考:
- https://github.com/apple/swift/blob/master/include/swift/ABI/Metadata.h
- https://github.com/apple/swift/blob/master/include/swift/ABI/MetadataKind.def
- https://github.com/apple/swift/blob/master/include/swift/ABI/MetadataValues.h
- https://github.com/apple/swift/blob/master/include/swift/Reflection/Records.h
通过Metadata我们可以获得类和结构体的属性还有属性类型等信息,可以用来字典转模型(JSON->Model)和模型转字典(Model->JSON).
反射
- 反射是编程语言中一项强大的能力,比如Java语言的反射机制
- 对于任意一个类型,都能够动态获取这个类的所有属性和方法信息
- 对于任意一个实例,都能够动态调用它的任意方法和属性
- Swift的反射机制目前还比较弱,通过 Mirror 类型来提供简单的反射功能