ルーム情報 : "droom" (290件)
最近更新されたメモ一覧 :
docs
被リンクメモ一覧 : (1件)
[index]
[Home] [List] [Recent] [Orphan] [Help] [Edit] [Remove]

Swift : Swift Standard Library

Links

Bool

Int

Double

Range

let underFive = 0.0..<5.0 // let underFive: Range<Double> =...
underFive.contains(3.14) -> true

ClosedRange

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

Optional

let shortForm: Int? = Int("42")
let longForm: Optional<Int> = Int("42")

Global Numeric Functions

String

文字列の検索

let str = "日本語でいきましょう"
print(str.range(of:"日本語")!) //->Index(_rawBits: 1)..<Index(_rawBits: 589825)
print(str.replacingOccurrences(of: "日本語", with: "英語")) //-> "英語でいきましょう"

StringProtocol

ComparisonResult

NSString.CompareOptions (= String.CompareOptions)

String.UnicodeScalarView

Unicode.Scalar

let letterK: Unicode.Scalar = "K"
let airplane = Unicode.Scalar(9992)
print("A".unicodeScalars.first!.properties.isEmoji) //-> false

String.Index

let cafe = "Caf&#233; &#127861;"
let stringIndex = cafe.firstIndex(of: "&#233;")!
let utf16Index = String.Index(stringIndex, within: cafe.utf16)!
print(cafe.utf16[...utf16Index])
// Prints "Caf&#233;"

// 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

var s = ""
for n in 1...5 {
  print(n, terminator: "", to: &s)
}
// s == "12345"

Substring

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"
[Home] [List] [Recent] [Orphan] [Help] [Edit] [Remove]
-->