protocol
StringProtocol
A type that can represent a string as a collection of characters.
Inheritance | BidirectionalCollection, Comparable, ExpressibleByStringInterpolation, Hashable, LosslessStringConvertible, TextOutputStream, TextOutputStreamable |
---|---|
Conforming Types | Substring |
Associated Types |
|
Initializers
Creates a string from the null-terminated, UTF-8 encoded sequence of bytes at the given pointer.
- Parameter nullTerminatedUTF8: A pointer to a sequence of contiguous, UTF-8 encoded bytes ending just before the first zero byte.
Declaration
init
(
cString
nullTerminatedUTF8
:
UnsafePointer
<
CChar
>
)
Creates a string from the given Unicode code units in the specified encoding.
Declaration
init
<
C
,
Encoding
>
(
decoding
codeUnits
:
C
,
as
sourceEncoding
:
Encoding
.
Type
)
where
C
:
Collection
,
Encoding
:
_UnicodeEncoding
,
C
.
Element
==
Encoding
.
CodeUnit
Creates a string from the null-terminated sequence of bytes at the given pointer.
Declaration
init
<
Encoding
>
(
decodingCString
nullTerminatedCodeUnits
:
UnsafePointer
<
Encoding
.
CodeUnit
>
,
as
sourceEncoding
:
Encoding
.
Type
)
where
Encoding
:
_UnicodeEncoding
Instance Variables
Instance Methods
Calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of UTF-8 code units.
The pointer passed as an argument to body
is valid only during the
execution of withCString(_:)
. Do not store or return the pointer for
later use.
- Parameter body: A closure with a pointer parameter that points to a
null-terminated sequence of UTF-8 code units. If
body
has a return value, that value is also used as the return value for thewithCString(_:)
method. The pointer argument is valid only for the duration of the method's execution.
Declaration
func
withCString
<
Result
>
(
_
body
: (
UnsafePointer
<
CChar
>
)
throws
-
>
Result
)
rethrows
-
>
Result
Calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of code units.
The pointer passed as an argument to body
is valid only during the
execution of withCString(encodedAs:_:)
. Do not store or return the
pointer for later use.
Declaration
func
withCString
<
Result
,
Encoding
>
(
encodedAs
targetEncoding
:
Encoding
.
Type
,
_
body
: (
UnsafePointer
<
Encoding
.
CodeUnit
>
)
throws
-
>
Result
)
rethrows
-
>
Result
where
Encoding
:
_UnicodeEncoding
Default Implementations
Returns a partial range up to, and including, its upper bound.
Use the prefix closed range operator (prefix ...
) to create a partial
range of any type that conforms to the Comparable
protocol. This
example creates a PartialRangeThrough<Double>
instance that includes
any value less than or equal to 5.0
.
let
throughFive
= ...
5.0
throughFive
.
contains
(
4.0
)
// true
throughFive
.
contains
(
5.0
)
// true
throughFive
.
contains
(
6.0
)
// false
You can use this type of partial range of a collection's indices to represent the range from the start of the collection up to, and including, the partial range's upper bound.
let
numbers
= [
10
,
20
,
30
,
40
,
50
,
60
,
70
]
(
numbers
[...
3
])
// Prints "[10, 20, 30, 40]"
- Parameter maximum: The upper bound for the range.
Declaration
prefix
public
static
func
...(
maximum
:
Self
) -
>
PartialRangeThrough
<
Self
>
Returns a partial range extending upward from a lower bound.
Use the postfix range operator (postfix ...
) to create a partial range
of any type that conforms to the Comparable
protocol. This example
creates a PartialRangeFrom<Double>
instance that includes any value
greater than or equal to 5.0
.
let
atLeastFive
=
5.0
...
atLeastFive
.
contains
(
4.0
)
// false
atLeastFive
.
contains
(
5.0
)
// true
atLeastFive
.
contains
(
6.0
)
// true
You can use this type of partial range of a collection's indices to represent the range from the partial range's lower bound up to the end of the collection.
let
numbers
= [
10
,
20
,
30
,
40
,
50
,
60
,
70
]
(
numbers
[
3
...])
// Prints "[40, 50, 60, 70]"
- Parameter minimum: The lower bound for the range.
Declaration
postfix
public
static
func
...(
minimum
:
Self
) -
>
PartialRangeFrom
<
Self
>
Returns a closed range that contains both of its bounds.
Use the closed range operator (...
) to create a closed range of any type
that conforms to the Comparable
protocol. This example creates a
ClosedRange<Character>
from "a" up to, and including, "z".
let
lowercase
=
"a"
...
"z"
(
lowercase
.
contains
(
"z"
))
// Prints "true"
Declaration
public
static
func
...(
minimum
:
Self
,
maximum
:
Self
) -
>
ClosedRange
<
Self
>
Returns a partial range up to, but not including, its upper bound.
Use the prefix half-open range operator (prefix ..<
) to create a
partial range of any type that conforms to the Comparable
protocol.
This example creates a PartialRangeUpTo<Double>
instance that includes
any value less than 5.0
.
let
upToFive
= ..
<
5.0
upToFive
.
contains
(
3.14
)
// true
upToFive
.
contains
(
6.28
)
// false
upToFive
.
contains
(
5.0
)
// false
You can use this type of partial range of a collection's indices to represent the range from the start of the collection up to, but not including, the partial range's upper bound.
let
numbers
= [
10
,
20
,
30
,
40
,
50
,
60
,
70
]
(
numbers
[..
<
3
])
// Prints "[10, 20, 30]"
- Parameter maximum: The upper bound for the range.
Declaration
prefix
public
static
func
..
<
(
maximum
:
Self
) -
>
PartialRangeUpTo
<
Self
>
Returns a half-open range that contains its lower bound but not its upper bound.
Use the half-open range operator (..<
) to create a range of any type
that conforms to the Comparable
protocol. This example creates a
Range<Double>
from zero up to, but not including, 5.0.
let
lessThanFive
=
0.0
..
<
5.0
(
lessThanFive
.
contains
(
3.14
))
// Prints "true"
(
lessThanFive
.
contains
(
5.0
))
// Prints "false"
Declaration
public
static
func
..
<
(
minimum
:
Self
,
maximum
:
Self
) -
>
Range
<
Self
>
Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.
This is the default implementation of the less-than-or-equal-to
operator (<=
) for any type that conforms to Comparable
.
Declaration
@
inlinable
public
static
func
<
=(
lhs
:
Self
,
rhs
:
Self
) -
>
Bool
Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.
This is the default implementation of the greater-than operator (>
) for
any type that conforms to Comparable
.
Declaration
@
inlinable
public
static
func
>
(
lhs
:
Self
,
rhs
:
Self
) -
>
Bool
Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.
This is the default implementation of the greater-than-or-equal-to operator
(>=
) for any type that conforms to Comparable
.
Declaration
@
inlinable
public
static
func
>
=(
lhs
:
Self
,
rhs
:
Self
) -
>
Bool
Returns the difference needed to produce this collection's ordered elements from the given collection, using the given predicate as an equivalence test.
This function does not infer element moves. If you need to infer moves,
call the inferringMoves()
method on the resulting difference.
Complexity: Worst case performance is O(n * m), where n is the count of this collection and m is
other.count
. You can expect faster execution when the collections share many common elements.
Declaration
@
available
(
OSX
10.15
,
iOS
13
,
tvOS
13
,
watchOS
6
, *)
public
func
difference
<
C
>
(
from
other
:
C
,
by
areEquivalent
: (
C
.
Element
,
Self
.
Element
) -
>
Bool
) -
>
CollectionDifference
<
Self
.
Element
>
where
C
:
BidirectionalCollection
,
Self
.
Element
==
C
.
Element
Declaration
@
inlinable
public
func
distance
(
from
start
:
Self
.
Index
,
to
end
:
Self
.
Index
) -
>
Int
Returns a subsequence containing all but the specified number of final elements.
If the number of elements to drop exceeds the number of elements in the collection, the result is an empty subsequence.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
dropLast
(
2
))
// Prints "[1, 2, 3]"
(
numbers
.
dropLast
(
10
))
// Prints "[]"
- Parameter k: The number of elements to drop off the end of the
collection.
k
must be greater than or equal to zero.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(k), where k is the number of elements to drop.
Declaration
@
inlinable
public
func
dropLast
(
_
k
:
Int
) -
>
Self
.
SubSequence
Replaces the given index with its predecessor.
- Parameter i: A valid index of the collection.
i
must be greater thanstartIndex
.
Declaration
@
inlinable
public
func
formIndex
(
before
i
:
inout
Self
.
Index
)
Declaration
@
inlinable
public
func
index
(
_
i
:
Self
.
Index
,
offsetBy
distance
:
Int
) -
>
Self
.
Index
Declaration
@
inlinable
public
func
index
(
_
i
:
Self
.
Index
,
offsetBy
distance
:
Int
,
limitedBy
limit
:
Self
.
Index
) -
>
Self
.
Index
?
The last element of the collection.
If the collection is empty, the value of this property is nil
.
let
numbers
= [
10
,
20
,
30
,
40
,
50
]
if
let
lastNumber
=
numbers
.
last
{
(
lastNumber
)
}
// Prints "50"
Complexity: O(1)
Declaration
var
last
:
Self
.
Element
?
Returns the last element of the sequence that satisfies the given predicate.
This example uses the last(where:)
method to find the last
negative number in an array of integers:
let
numbers
= [
3
,
7
,
4
, -
2
,
9
, -
6
,
10
,
1
]
if
let
lastNegative
=
numbers
.
last
(
where
: { $
0
<
0
}) {
(
"The last negative number is \(
lastNegative
)."
)
}
// Prints "The last negative number is -6."
- Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
func
last
(
where
predicate
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Self
.
Element
?
Returns the index of the last element in the collection that matches the given predicate.
You can use the predicate to find an element of a type that doesn't
conform to the Equatable
protocol or to find an element that matches
particular criteria. This example finds the index of the last name that
begins with the letter A:
let
students
= [
"Kofi"
,
"Abena"
,
"Peter"
,
"Kweku"
,
"Akosua"
]
if
let
i
=
students
.
lastIndex
(
where
: { $
0
.
hasPrefix
(
"A"
) }) {
(
"\(
students
[
i
]
) starts with 'A'!"
)
}
// Prints "Akosua starts with 'A'!"
- Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
func
lastIndex
(
where
predicate
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Self
.
Index
?
Returns a view presenting the elements of the collection in reverse order.
You can reverse a collection without allocating new space for its
elements by calling this reversed()
method. A ReversedCollection
instance wraps an underlying collection and provides access to its
elements in reverse order. This example prints the characters of a
string in reverse order:
let
word
=
"Backwards"
for
char
in
word
.
reversed
() {
(
char
,
terminator
:
""
)
}
// Prints "sdrawkcaB"
If you need a reversed collection of the same type, you may be able to
use the collection's sequence-based or collection-based initializer. For
example, to get the reversed version of a string, reverse its
characters and initialize a new String
instance from the result.
let
reversedWord
=
String
(
word
.
reversed
())
(
reversedWord
)
// Prints "sdrawkcaB"
Complexity: O(1)
Declaration
@
inlinable
public
func
reversed
() -
>
ReversedCollection
<
Self
>
Returns a subsequence, up to the given maximum length, containing the final elements of the collection.
If the maximum length exceeds the number of elements in the collection, the result contains the entire collection.
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
(
numbers
.
suffix
(
2
))
// Prints "[4, 5]"
(
numbers
.
suffix
(
10
))
// Prints "[1, 2, 3, 4, 5]"
- Parameter maxLength: The maximum number of elements to return.
maxLength
must be greater than or equal to zero.
Complexity: O(1) if the collection conforms to
RandomAccessCollection
; otherwise, O(k), where k is equal tomaxLength
.
Declaration
@
inlinable
public
func
suffix
(
_
maxLength
:
Int
) -
>
Self
.
SubSequence
Do not declare new conformances to
StringProtocol
. Only theString
andSubstring
types in the standard library are valid conforming types.