遇到的一时间不好理解的方法整理,持续更新
1. resolvingAgainstBaseURL
系统的URLComponents
结构体能很好的将URL分成多个部分,其中的一个初始化方法包含了resolvingAgainstBaseURL
如下, 经过查词典和运行结果比对,翻译为:处理生成URLComponents
时以第一个参数URL中的BaseURL为背景。
public init?(url: URL, resolvingAgainstBaseURL resolve: Bool)
// 1.对于以relativeTo初始化的URL,会生效。
let baseURL = URL(string: "http://server/foo/")!
let url = URL(string: "bar/file.html", relativeTo: baseURL)!
print(url.absoluteString) // "http://server/foo/bar/file.html"
let comp1 = URLComponents(url: url, resolvingAgainstBaseURL: false)!
print(comp1.string) // Optional("bar/file.html")
let comp2 = URLComponents(url: url, resolvingAgainstBaseURL: true)!
print(comp2.string) // Optional("http://server/foo/bar/file.html")
// 2.对于不是以relativeTo初始化的URL,不会生效。
let url2 = URL(string: "http://server/foo/bar/file.html")!
print(url2.absoluteString) // "http://server/foo/bar/file.html"
let comp11 = URLComponents(url: url2, resolvingAgainstBaseURL: false)!
print(comp11.string) // ptional("http://server/foo/bar/file.html")
let comp22 = URLComponents(url: url2, resolvingAgainstBaseURL: true)!
print(comp22.string) // Optional("http://server/foo/bar/file.html")
2. truncatingRemainder(dividingBy other: Double)
对于Double类型数据,Swift基础库中提供了一个截断除法取余的方法:
其实现的原理是,将数据a除以除数b后向下取整得到c,然后用余数r = a - b*c.
/// let x = 8.625
/// print(x / 0.75)
/// // Prints "11.5"
///
/// let q = (x / 0.75).rounded(.towardZero)
/// // q == 11.0
/// let r = x.truncatingRemainder(dividingBy: 0.75)
/// // r == 0.375
///
/// let x1 = 0.75 * q + r
/// // x1 == 8.625
@inlinable public func truncatingRemainder(dividingBy other: Double) -> Double
网友评论