Swift : Swift Standard Library
Links
Bool
- @frozen struct Bool
- toggle(), random(), random<T>(using: inout T)
- description, customMirror, hashValue, hash(into: inout Hasher)
- init?(_ description: String) - true/false以外はnilとなる。case-sensitive.
- init?(exactly number: NSNumber) - 試したところ0/1でfalse/trueとなる。overviewなし。
- init()はfalseを返す。
Int
- @frozen struct Int
- 他の数値から生成される場合は0方向に丸められる。
- static func random(in: Range<Int>)-> Int
static func random<T>(in: Range<Int>, using: inout T) -> Int
- func isMultiple(of: Int) -> Bool // 倍数であるか否か。
- func quotientAndRemainder(dividingBy rhs: Int) -> (quotient: Int, Remainder: Int) // 商と余りを求める。
Double
- @frozen struct Double
- static func random(in: Range<Double>) -> Double
- static func minimum/minimumMagnitude/maximum/maximumMagnitude(Double, Double) -> Double
- static var zero/pi: Double
- func squareRoot() -> Double
- func rounded() -> Double // 最も近い整数またはちょうど中間であればより絶対値の大きい整数
- func rounded(_ rule: FloatingPointRoundingRule) -> Double ---FloatingPointRoundingRule
Range
- @frozen struct Range<Bound> where Bound : Comparable
- var isEmpty: Bool
- var fisrt: Bound? ; var last: Bound?
- var count: Int // BoundがIntの時のみ使用可能
- let LowerBound: Bound; let upperBound: Bound
- func contains(Bound) -> Bool
- func contains(where: (Bound) -> Bool) -> Bool
- func clamped(to: Range<Bound>) -> Range<Bound>
to:で挟まれた領域を返す。overlapなければempty rangeが返る。
- init?(NSRange)
- func prefix(_ maxLength: Int) -> Range<Bound> // 前からmaxLength個分のサブシーケンスを返す。prefix(through: Bound)の場合はインデックス0からBoundまでのサブシーケンスを返す。
- func dropFirst(Int) -> Range<Bound> //最初の1つを外したサブシーケンスを返す。
- func forEach((Bound) -> Void )
- func sorted(by: (Bound, Bound) -> Bool) -> [Bound??]
let underFive = 0.0..<5.0 // let underFive: Range<Double> =...
underFive.contains(3.14) -> true
ClosedRange
- @frozen struct ClosedRange<Bound> where Bound : Comparable
- let throughFive = 0...5
Error
enum IntParsingError: Error {
case overflow
case invalidInput(Character)
}
extension Int {
init(validating input: String) throws {
// ...
let c = _nextCharacter(from: input)
if !_isValid(c) {
throw IntParsingError.invalidInput(c)
}
// ...
}
}
do {
let price = try Int(validating: "$100")
} catch IntParsingError.invalidInput(let invalid) {
print("Invalid character: '\(invalid)'")
} catch IntParsingError.overflow {
print("Overflow error")
} catch {
print("Other error")
}
// -> prints "Invalid character: '$'"
// for more data including...
struct XMLParsingError: Error {
enum ErrorKind {
case invalidCharacter
case mismatchedTag
case internalError
}
let line: Int
let column: Int
let kind: ErrorKind
}
func parse(_ source: String) throws -> XMLDoc {
// ...
throw XMLParsingError(line: 19, colum: 5, kind: .mismatchedTag)
// ...
}
do {
let xmlDoc = try parse(myXMLData)
} catch let e as XMLParsingError {
print("Pasing error: \(e.kind) [\(e.line):\(e.column)]")
} catch {
print("Other error: \(error)") // <- errorという変数は出てこない…
}
Result
- @frozen enum Result<Success, Failure> where Failure : Error
- これについては後日。
Optional
- @frozen enum Optional<Wrapped>
let shortForm: Int? = Int("42")
let longForm: Optional<Int> = Int("42")
Global Numeric Functions
- func min<T>(T, T) -> T
- func min<T>(T, T, T, T...) -> T (func min<T>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T where T : Comparable)
- func max<T>(T, T) -> T
- func max<T>(T, T, T, T...) -> T
- func abs<T>(T) -> T
String
- @frozen struct String
- init(), init(Character), init<S>(S), init(SubString)
- init(repeating: String, count: Int)
- init(repeating: Character, count: Int)
- var isEmpty: Bool, var count: Int
- init(Unicode.Scalar), init?(data: Data, encoding: String.Encoding)
init?(utf8String: UnsafePointer<CChar>)
- func write(String) -- 既存のStringインスタンスに追加。
- func write<Target>(to: inout Target)
func write<Target>(to target: inout Target) where Target : TextOutputStream
- func append(String), func append(character)
- func insert(Character, at: String.Index)
- func insert(Character, at: Index)
- func replaceSubrange<C>(Range<String.Index>, with: C)
- func replaceSubrange<C, R>(R, with: C)
- func remove(at: String.Index) -> Character
- func removeAll(keepingCapacity: Bool)
- func removeAll(where: (Character) -> Bool)
- func removeFirst() -> Chacacter, func removeFirst(Int)
- func removeLast() -> Character, func removeLast(Int)
- func removeSubrange(Range<String.Index>)
- func removeSubRange<R>(R)
- func filter((Character) -> Bool) -> String
- func drop(while:)
func drop(while predicate: (Character) throws -> Bool) rethrows -> Substring
predicateの関数が初めてfalseを返したindex以降の文字列を返す。
例えば"abcde"でpredicateを"a"の時のみtrueとした場合、"bcde"が返る。
- func dropFirst(Int) -> Substring, func dropLast(Int) -> Substring
いずれもInt分だけ前方または後方から文字をカットして残りを返す。デフォルト1文字。
- popLast() -> Character?
- func lowercased() -> String, func uppercased() -> String
- func starts<PossiblePrefix>(with: PossiblePrefix) -> Bool
- func hasPrefix(String) -> Bool, func hasSuffix(String) -> Bool
- func contains(Character) -> Bool
- func contains(where: (Character) -> Bool) -> Bool
- func first(where: (Character) -> Bool) -> Bool, last...
- func firstIndex(of: Character) -> Index?, last...
- func firstIndex(where: (Character) -> Bool) -> Index?, last...
- func max() -> Character?, min...
- subscript(Range<String.Index>) -> Substring
- subscript(String.Index) -> Character
- var first: Character?, var last: Character?
- func prefix(Int) -> Substring // 最初のInt文字。Intが長さを越えていれば全部。
- func prefix(through: Index) -> Substring // Indexを含む前全て。
- func prefix(upTo end: Index) -> Substring // Indexより前まで全て。
- func split(separator: Character, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true) -> [Substring??]
- func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Character) throws -> Bool) rethrows -> [Substring??]
'print(line.split(whereSeparator: { $0 == " " }))'
- static var availableStringEncodings: [String.Encoding??]
- static var defaultCStringEncoding: String.Encoding
- static func localizedName(of: String.Encoding) -> String
- var unicodeScalars: String.UnicodeScalarView
- var utf16: String.UTF16View, var utf8: String.UTF8View
- var indices: DefaultIndices<String> { get }
DefaultIndices<String>(_elements: "日本語でいきましょう。", _startIndex: Swift.String.Index(_rawBits: 1), _endIndex: Swift.String.Index(_rawBits: 2162689)) // こういうリストを返す。
- String.Index(encodedOffset: Int)…はすでにdepricatedの様子。
文字列の検索
- Swiftで特定の文字列を検索・置換する方法によるとSwift5のStringにはrange(of:)というインスタンスメソッドがあると書かれているが、リファレンスには収載されていない。実際に試してみると動作する。なにこれ。
-> なるほど、StringProtocolプロトコルに実装されてるみたい。
let str = "日本語でいきましょう"
print(str.range(of:"日本語")!) //->Index(_rawBits: 1)..<Index(_rawBits: 589825)
print(str.replacingOccurrences(of: "日本語", with: "英語")) //-> "英語でいきましょう"
StringProtocol
- protocol StringProtocol where Self.Element == Character, Self.Index == String.Index, Self.StringInterpolation == DefaultStringInterPolation, Self.SubSequence : StringProtocol
- 全然内容のない解説。https://developer.apple.com/documentation/swift/stringprotocol
- var capitalized: String
- func canBeConverted(to: String.Encoding) -> Bool
- func caseInsensitiveCompare<T>(T) -> ComparisonResult
- func compare<T>(_ aString: T, options mask: String.CompareOptions = [], range: Range<Self.Index>? = nil, locale: Locale? = nil) -> ComparisonResult where T : StringProtocol
String.CompareOptionsはNSStrring.CompareOptionsのタイプエイリアス。
- func components(searatedBy: CharacterSet) -> [String??]
- func contains<T>(T) -> Bool
- func data(using encoding: String.Encoding, allowLossyConversion: Bool = false) -> Data?
- func range<T>(of aString: T, options mask: String.CompareOptions = [], range searchRange: Range<Self.Index>? = nil, locale: Locale? = nil) -> Range<Self.Index>? where T : StringProtocol
最初のひとつを返す仕様らしい。返されたらsearchRangeをその分後ろにずらして再検索することで全ての検索結果が得られそう。
- func replacingOccurrences<Target, Replacement>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<Self.Index>? = nil) -> String where Target : StringProtocol, Replacement : StringProtocol
破壊的メソッド。
ComparisonResult
- @frozen enum ComparisonResult : Int
- case orderedAscending
- case orderedSame
- case orderedDescending
- ... only 3 members.
NSString.CompareOptions (= String.CompareOptions)
String.UnicodeScalarView
- @frozen struct UnicodeScalarView
- String構造体のunicodeScalarsプロパティとしてアクセスされる。
- StringProtocol準拠。
Unicode.Scalar
- @frozen struct Scalar
- var value: UInt32
- var properties: Unicode.Scalar.Properties
- struct Unicode.Scalar.Properties
var age: Unicode.Version?
lowercase/uppercase、絵文字などについての様々な設定がある。
Unicode 13.0.0
let letterK: Unicode.Scalar = "K"
let airplane = Unicode.Scalar(9992)
print("A".unicodeScalars.first!.properties.isEmoji) //-> false
String.Index
- @frozen struct Index
- Indexの内部的な値はIndex(_rawBits: 1770241)といった形。まだはっきり分からないが、オクテット単位ではなくビット単位で位置を設定している様子。
- init?(_ idx: String.Index, within target: String.UTF16View)
- func samePosition(in: String.UTF8View) -> String.UTF8View.Index?
Stringのインスタンスから得たString.Indexを特定のエンコーングのindexに変換する。
…現在のところ、絵文字の入った文字列のindexであってもutf8・utf16・
let cafe = "Café 🍵"
let stringIndex = cafe.firstIndex(of: "é")!
let utf16Index = String.Index(stringIndex, within: cafe.utf16)!
print(cafe.utf16[...utf16Index])
// Prints "Café"
// String上のindexを特定のエンコーディングでのindexに変換する。
let str = "日本語のサンプル"
let i = str.firstIndex(of: "語")!
let j = i.samePosition(in: str.utf8)!
print(Array(str.utf8[j...]))
String.UTF8View
TextOutputStream
- protocol TextOutputStream
- write(_:)メソッドが要求される。
var s = ""
for n in 1...5 {
print(n, terminator: "", to: &s)
}
// s == "12345"
Substring
- @frozen struct Substring
- 元のStringインスタンスとデータを共有するため、効率はよいが元のインスタンスが消滅するより前に使用を中止する必要がある。
- インターフェイスはStringと同じ。
- String(_:)でStringインスタンスに変換できる。
let greeting = "Hi there! It's nice to meet you!"
let endOfSentence = greeting.firstIndex(of: "!")!
let firstSentence = greeting[...endOfSentence]
// firstSentence == "Hi there!"
let rawInput = "126 a.b 22219 zzzzzz"
let numericPrefix = rawInput.prefix(while: {"0"..."9" ~= $0})
// numericPrefix is the substring "126"