Swift #28:Foundation
发布: (2026年1月3日 GMT+8 04:43)
3 min read
原文: Dev.to
Source: Dev.to
请提供您希望翻译的具体文本内容(除代码块和 URL 之外),我将把它翻译成简体中文并保持原有的格式、Markdown 语法和技术术语不变。谢谢!
Foundation 库的一些函数
| 函数 | 描述 |
|---|---|
pow(_:_:) | 计算底数为 Double、指数为 Double 的幂运算。返回 Double。 |
sqrt(_:) | 计算 Double 参数的平方根。返回 Double。 |
log(_:) | 计算 Double 值的自然对数。还有 log2(_:) 和 log10(_:) 等变体。 |
sin(_:) | 返回 Double 值的正弦。变体:asin(_:)、sinh(_:)、asinh(_:)。 |
cos(_:) | 返回 Double 值的余弦。变体:acos(_:)、cosh(_:)、acosh(_:)。 |
tan(_:) | 返回 Double 值的正切。变体:atan(_:)、tanh(_:)、atanh(_:)。 |
Source: …
NSString
import Foundation
let text0: String = "Hola"
let text1: NSString = NSString(string: text0)
print(text1) // "Hola"
let text2: NSString = text0 as NSString
print(text2) // "Hola"
常用属性和方法
capitalized:返回每个单词首字母大写的字符串。length:返回字符数量。localizedStringWithFormat(_:_:):使用第一个参数(模板)和第二个可变参数提供的值创建字符串。contains(_:):如果参数是原始字符串的一部分,则返回true。localizedStandardContains(_:):在考虑语言(locale)规则的情况下返回true。components(separatedBy:):使用参数作为分隔符拆分字符串,并返回包含各部分的数组。replacingOccurrences(of:with:):返回一个新字符串,替换所有of:出现的内容为with:。trimmingCharacters(in:):删除in:中指定的字符在字符串开头和结尾的出现。最常用的参数是whitespaces。
localizedStringWithFormat 示例
let number = 44
let result1 = String.localizedStringWithFormat("Numero: %d", number)
print(result1) // "Numero: 44"
let pi = 3.14159
let lives = 7
let result2 = String.localizedStringWithFormat("Pi: %.2f", pi)
print(result2) // "Pi: 3.14"
let result3 = String.localizedStringWithFormat("Vidas: %.3d", lives)
print(result3) // "Vidas: 007"
注意:
String结构使用 Unicode 字符,而NSString使用 UTF‑16 编码。
NSNumber
| 属性 / 方法 | 描述 |
|---|---|
init(value:) | 使用指定的值创建一个 NSNumber。 |
doubleValue | 获取 NSNumber 的 Double 值。 |
intValue | 获取 NSNumber 的 Int 值。 |
formatted(_:) | 使用 FormatStyle 对值进行格式化。对于数字,有 IntegerFormatStyle 和 FloatingPointFormatStyle。 |
FormatStyle
precision(_:)integerAndFractionLength(integerLimits:fractionLimits:)rounded(rule:increment:)grouping(_:)sign(strategy:)decimalSeparator(strategy:).percentcurrency(code:)
使用示例
let result = (3.14159)
.formatted(
.number
.precision(.fractionLength(2))
)
print(result) // 3.14
Date
有多个类用于创建和处理日期:
Date 构造函数
-
Date()– 当前日期和时间。let now = Date() -
Date(timeIntervalSinceNow:)– 相对于当前时刻的日期和时间,使用秒数偏移。let fiveMinutesLater = Date(timeIntervalSinceNow: 5 * 60) -
Date(timeInterval:since:)– 基于另一日期创建,使用秒数偏移。let reference = Date() let tenSecondsLater = Date(timeInterval: 10, since: reference) -
Date(timeIntervalSinceReferenceDate:)– 基于 2001 年 1 月 1 日 00:00:00 UTC 创建日期,使用秒数偏移。let referenceDate = Date(timeIntervalSinceReferenceDate: 0) // 2001‑01‑01 00:00:00 UTC let oneDayLater = Date(timeIntervalSinceReferenceDate: 86_400) // 1 天之后