mirror of
https://github.com/apple/swift.git
synced 2025-12-21 12:14:44 +01:00
61 lines
2.1 KiB
Swift
61 lines
2.1 KiB
Swift
//===--- StringCharacterView.swift - String's Collection of Characters ----===//
|
|
//
|
|
// This source file is part of the Swift.org open source project
|
|
//
|
|
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
|
|
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
//
|
|
// See http://swift.org/LICENSE.txt for license information
|
|
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
//
|
|
// String is-not-a SequenceType or CollectionType, but it exposes a
|
|
// collection of characters.
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
extension String {
|
|
/// A `String`'s collection of `Character`s ([extended grapheme
|
|
/// clusters](http://www.unicode.org/glossary/#extended_grapheme_cluster))
|
|
/// elements.
|
|
public struct CharacterView {
|
|
internal var _core: _StringCore
|
|
|
|
/// Create a view of the `Character`s in `text`
|
|
public init(_ text: String) {
|
|
self._core = s._core
|
|
}
|
|
|
|
public // @testable
|
|
init(_ _core: _StringCore) {
|
|
self._core = _core
|
|
}
|
|
}
|
|
|
|
/// A collection of `Characters` representing the `String`'s
|
|
/// [extended grapheme
|
|
/// clusters](http://www.unicode.org/glossary/#extended_grapheme_cluster)).
|
|
public var characters: CharacterView {
|
|
return CharacterView(self)
|
|
}
|
|
|
|
/// Efficiently mutate `self` by applying `body` to its `characters`.
|
|
///
|
|
/// - warning: Do not rely on anything about `self` (the `String`
|
|
/// that is the target of this method) during the execution of
|
|
/// `body`: it may not appear to have its correct value. Instead,
|
|
/// use only the `String.CharacterView` argument to `body`.
|
|
public mutating func withMutableCharacters<R>(body: (inout CharacterView)->R) -> R {
|
|
// Naively mutating self.characters forces multiple references to
|
|
// exist at the point of mutation. Instead, temporarily move the
|
|
// core of this string into a CharacterView.
|
|
var tmp = CharacterView("")
|
|
swap(&_core, &tmp._core)
|
|
let r = body(&tmp)
|
|
swap(&_core, &tmp._core)
|
|
return r
|
|
}
|
|
}
|
|
|