forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNSStringAPI.swift
2206 lines (1913 loc) · 82 KB
/
NSStringAPI.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Exposing the API of NSString on Swift's String
//
//===----------------------------------------------------------------------===//
// Important Note
// ==============
//
// This file is shared between two projects:
//
// 1. https://github.com/apple/swift/tree/master/stdlib/public/Darwin/Foundation
// 2. https://github.com/apple/swift-corelibs-foundation/tree/master/Foundation
//
// If you change this file, you must update it in both places.
#if !DEPLOYMENT_RUNTIME_SWIFT
@_exported import Foundation // Clang module
#endif
// Open Issues
// ===========
//
// Property Lists need to be properly bridged
//
func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray {
let result = NSMutableArray(capacity: a.count)
for s in a {
result.add(f(s))
}
return result
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// We only need this for UnsafeMutablePointer, but there's not currently a way
// to write that constraint.
extension Optional {
/// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the
/// address of `object` to `body`.
///
/// This is intended for use with Foundation APIs that return an Objective-C
/// type via out-parameter where it is important to be able to *ignore* that
/// parameter by passing `nil`. (For some APIs, this may allow the
/// implementation to avoid some work.)
///
/// In most cases it would be simpler to just write this code inline, but if
/// `body` is complicated than that results in unnecessarily repeated code.
internal func _withNilOrAddress<NSType : AnyObject, ResultType>(
of object: inout NSType?,
_ body:
(AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType
) -> ResultType {
return self == nil ? body(nil) : body(&object)
}
}
#endif
/// From a non-`nil` `UnsafePointer` to a null-terminated string
/// with possibly-transient lifetime, create a null-terminated array of 'C' char.
/// Returns `nil` if passed a null pointer.
internal func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? {
guard let cString = p else {
return nil
}
let len = UTF8._nullCodeUnitOffset(in: cString)
var result = [CChar](repeating: 0, count: len + 1)
for i in 0..<len {
result[i] = cString[i]
}
return result
}
extension String {
//===--- Class Methods --------------------------------------------------===//
//===--------------------------------------------------------------------===//
// @property (class) const NSStringEncoding *availableStringEncodings;
/// An array of the encodings that strings support in the application's
/// environment.
public static var availableStringEncodings: [Encoding] {
var result = [Encoding]()
var p = NSString.availableStringEncodings
while p.pointee != 0 {
result.append(Encoding(rawValue: p.pointee))
p += 1
}
return result
}
// @property (class) NSStringEncoding defaultCStringEncoding;
/// The C-string encoding assumed for any method accepting a C string as an
/// argument.
public static var defaultCStringEncoding: Encoding {
return Encoding(rawValue: NSString.defaultCStringEncoding)
}
// + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
/// Returns a human-readable string giving the name of the specified encoding.
///
/// - Parameter encoding: A string encoding. For possible values, see
/// `String.Encoding`.
/// - Returns: A human-readable string giving the name of `encoding` in the
/// current locale.
public static func localizedName(
of encoding: Encoding
) -> String {
return NSString.localizedName(of: encoding.rawValue)
}
// + (instancetype)localizedStringWithFormat:(NSString *)format, ...
/// Returns a string created by using a given format string as a
/// template into which the remaining argument values are substituted
/// according to the user's default locale.
public static func localizedStringWithFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
return String(format: format, locale: Locale.current,
arguments: arguments)
}
//===--------------------------------------------------------------------===//
// NSString factory functions that have a corresponding constructor
// are omitted.
//
// + (instancetype)string
//
// + (instancetype)
// stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
//
// + (instancetype)stringWithFormat:(NSString *)format, ...
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithCString:(const char *)cString
// encoding:(NSStringEncoding)enc
//===--------------------------------------------------------------------===//
//===--- Adds nothing for String beyond what String(s) does -------------===//
// + (instancetype)stringWithString:(NSString *)aString
//===--------------------------------------------------------------------===//
// + (instancetype)stringWithUTF8String:(const char *)bytes
/// Creates a string by copying the data from a given
/// C array of UTF8-encoded bytes.
public init?(utf8String bytes: UnsafePointer<CChar>) {
if let str = String(validatingUTF8: bytes) {
self = str
return
}
if let ns = NSString(utf8String: bytes) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
}
extension String {
//===--- Already provided by String's core ------------------------------===//
// - (instancetype)init
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithBytes:(const void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
/// Creates a new string equivalent to the given bytes interpreted in the
/// specified encoding.
///
/// - Parameters:
/// - bytes: A sequence of bytes to interpret using `encoding`.
/// - encoding: The ecoding to use to interpret `bytes`.
public init?<S: Sequence>(bytes: __shared S, encoding: Encoding)
where S.Iterator.Element == UInt8 {
let byteArray = Array(bytes)
if encoding == .utf8,
let str = byteArray.withUnsafeBufferPointer({ String._tryFromUTF8($0) })
{
self = str
return
}
if let ns = NSString(
bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// - (instancetype)
// initWithBytesNoCopy:(void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of bytes from the
/// given buffer, interpreted in the specified encoding, and optionally
/// frees the buffer.
///
/// - Warning: This initializer is not memory-safe!
public init?(
bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int,
encoding: Encoding, freeWhenDone flag: Bool
) {
if let ns = NSString(
bytesNoCopy: bytes, length: length, encoding: encoding.rawValue,
freeWhenDone: flag) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// - (instancetype)
// initWithCharacters:(const unichar *)characters
// length:(NSUInteger)length
/// Creates a new string that contains the specified number of characters
/// from the given C array of Unicode characters.
public init(
utf16CodeUnits: UnsafePointer<unichar>,
count: Int
) {
self = String._unconditionallyBridgeFromObjectiveC(NSString(characters: utf16CodeUnits, length: count))
}
// - (instancetype)
// initWithCharactersNoCopy:(unichar *)characters
// length:(NSUInteger)length
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of characters
/// from the given C array of UTF-16 code units.
public init(
utf16CodeUnitsNoCopy: UnsafePointer<unichar>,
count: Int,
freeWhenDone flag: Bool
) {
self = String._unconditionallyBridgeFromObjectiveC(NSString(
charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy),
length: count,
freeWhenDone: flag))
}
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
/// Produces a string created by reading data from the file at a
/// given path interpreted using a given encoding.
public init(
contentsOfFile path: __shared String,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from the file at
/// a given path and returns by reference the encoding used to
/// interpret the file.
public init(
contentsOfFile path: __shared String,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOfFile: path, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
public init(
contentsOfFile path: __shared String
) throws {
let ns = try NSString(contentsOfFile: path, usedEncoding: nil)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError**)error
/// Produces a string created by reading data from a given URL
/// interpreted using a given encoding. Errors are written into the
/// inout `error` argument.
public init(
contentsOf url: __shared URL,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOf: url, encoding: enc.rawValue)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from a given URL
/// and returns by reference the encoding used to interpret the
/// data. Errors are written into the inout `error` argument.
public init(
contentsOf url: __shared URL,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
public init(
contentsOf url: __shared URL
) throws {
let ns = try NSString(contentsOf: url, usedEncoding: nil)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithCString:(const char *)nullTerminatedCString
// encoding:(NSStringEncoding)encoding
/// Produces a string containing the bytes in a given C array,
/// interpreted according to a given encoding.
public init?(
cString: UnsafePointer<CChar>,
encoding enc: Encoding
) {
if enc == .utf8, let str = String(validatingUTF8: cString) {
self = str
return
}
if let ns = NSString(cString: cString, encoding: enc.rawValue) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// FIXME: handle optional locale with default arguments
// - (instancetype)
// initWithData:(NSData *)data
// encoding:(NSStringEncoding)encoding
/// Returns a `String` initialized by converting given `data` into
/// Unicode characters using a given `encoding`.
public init?(data: __shared Data, encoding: Encoding) {
if encoding == .utf8,
let str = data.withUnsafeBytes({
String._tryFromUTF8($0.bindMemory(to: UInt8.self))
}) {
self = str
return
}
guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil }
self = String._unconditionallyBridgeFromObjectiveC(s)
}
// - (instancetype)initWithFormat:(NSString *)format, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted.
public init(format: __shared String, _ arguments: CVarArg...) {
self = String(format: format, arguments: arguments)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to the user's default locale.
public init(format: __shared String, arguments: __shared [CVarArg]) {
self = String(format: format, locale: nil, arguments: arguments)
}
// - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: __shared String, locale: __shared Locale?, _ args: CVarArg...) {
self = String(format: format, locale: locale, arguments: args)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// locale:(id)locale
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: __shared String, locale: __shared Locale?, arguments: __shared [CVarArg]) {
#if DEPLOYMENT_RUNTIME_SWIFT
self = withVaList(arguments) {
String._unconditionallyBridgeFromObjectiveC(
NSString(format: format, locale: locale?._bridgeToObjectiveC(), arguments: $0)
)
}
#else
self = withVaList(arguments) {
NSString(format: format, locale: locale, arguments: $0) as String
}
#endif
}
}
extension StringProtocol where Index == String.Index {
//===--- Bridging Helpers -----------------------------------------------===//
//===--------------------------------------------------------------------===//
/// The corresponding `NSString` - a convenience for bridging code.
// FIXME(strings): There is probably a better way to bridge Self to NSString
var _ns: NSString {
return self._ephemeralString._bridgeToObjectiveC()
}
/// Return an `Index` corresponding to the given offset in our UTF-16
/// representation.
func _toIndex(_ utf16Index: Int) -> Index {
return self._toUTF16Index(utf16Index)
}
/// Return the UTF-16 code unit offset corresponding to an Index
func _toOffset(_ idx: String.Index) -> Int {
return self._toUTF16Offset(idx)
}
@inlinable
internal func _toRelativeNSRange(_ r: Range<String.Index>) -> NSRange {
return NSRange(self._toUTF16Offsets(r))
}
/// Return a `Range<Index>` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _toRange(_ r: NSRange) -> Range<Index> {
return self._toUTF16Indices(Range(r)!)
}
/// Return a `Range<Index>?` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _optionalRange(_ r: NSRange) -> Range<Index>? {
if r.location == NSNotFound {
return nil
}
return _toRange(r)
}
/// Invoke `body` on an `Int` buffer. If `index` was converted from
/// non-`nil`, convert the buffer to an `Index` and write it into the
/// memory referred to by `index`
func _withOptionalOutParameter<Result>(
_ index: UnsafeMutablePointer<Index>?,
_ body: (UnsafeMutablePointer<Int>?) -> Result
) -> Result {
var utf16Index: Int = 0
let result = (index != nil ? body(&utf16Index) : body(nil))
index?.pointee = _toIndex(utf16Index)
return result
}
/// Invoke `body` on an `NSRange` buffer. If `range` was converted
/// from non-`nil`, convert the buffer to a `Range<Index>` and write
/// it into the memory referred to by `range`
func _withOptionalOutParameter<Result>(
_ range: UnsafeMutablePointer<Range<Index>>?,
_ body: (UnsafeMutablePointer<NSRange>?) -> Result
) -> Result {
var nsRange = NSRange(location: 0, length: 0)
let result = (range != nil ? body(&nsRange) : body(nil))
range?.pointee = self._toRange(nsRange)
return result
}
//===--- Instance Methods/Properties-------------------------------------===//
//===--------------------------------------------------------------------===//
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// @property BOOL boolValue;
// - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
/// Returns a Boolean value that indicates whether the string can be
/// converted to the specified encoding without loss of information.
///
/// - Parameter encoding: A string encoding.
/// - Returns: `true` if the string can be encoded in `encoding` without loss
/// of information; otherwise, `false`.
public func canBeConverted(to encoding: String.Encoding) -> Bool {
return _ns.canBeConverted(to: encoding.rawValue)
}
// @property NSString* capitalizedString
/// A copy of the string with each word changed to its corresponding
/// capitalized spelling.
///
/// This property performs the canonical (non-localized) mapping. It is
/// suitable for programming operations that require stable results not
/// depending on the current locale.
///
/// A capitalized string is a string with the first character in each word
/// changed to its corresponding uppercase value, and all remaining
/// characters set to their corresponding lowercase values. A "word" is any
/// sequence of characters delimited by spaces, tabs, or line terminators.
/// Some common word delimiting punctuation isn't considered, so this
/// property may not generally produce the desired results for multiword
/// strings. See the `getLineStart(_:end:contentsEnd:for:)` method for
/// additional information.
///
/// Case transformations aren’t guaranteed to be symmetrical or to produce
/// strings of the same lengths as the originals.
public var capitalized: String {
return _ns.capitalized as String
}
// @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
/// A capitalized representation of the string that is produced
/// using the current locale.
@available(macOS 10.11, iOS 9.0, *)
public var localizedCapitalized: String {
return _ns.localizedCapitalized
}
// - (NSString *)capitalizedStringWithLocale:(Locale *)locale
/// Returns a capitalized representation of the string
/// using the specified locale.
public func capitalized(with locale: Locale?) -> String {
return _ns.capitalized(with: locale) as String
}
// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
/// Returns the result of invoking `compare:options:` with
/// `NSCaseInsensitiveSearch` as the only option.
public func caseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.caseInsensitiveCompare(aString._ephemeralString)
}
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// - (unichar)characterAtIndex:(NSUInteger)index
//
// We have a different meaning for "Character" in Swift, and we are
// trying not to expose error-prone UTF-16 integer indexes
// - (NSString *)
// commonPrefixWithString:(NSString *)aString
// options:(StringCompareOptions)mask
/// Returns a string containing characters this string and the
/// given string have in common, starting from the beginning of each
/// up to the first characters that aren't equivalent.
public func commonPrefix<
T : StringProtocol
>(with aString: T, options: String.CompareOptions = []) -> String {
return _ns.commonPrefix(with: aString._ephemeralString, options: options)
}
// - (NSComparisonResult)
// compare:(NSString *)aString
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range locale:(id)locale
/// Compares the string using the specified options and
/// returns the lexical ordering for the range.
public func compare<T : StringProtocol>(
_ aString: T,
options mask: String.CompareOptions = [],
range: Range<Index>? = nil,
locale: Locale? = nil
) -> ComparisonResult {
// According to Ali Ozer, there may be some real advantage to
// dispatching to the minimal selector for the supplied options.
// So let's do that; the switch should compile away anyhow.
let aString = aString._ephemeralString
return locale != nil ? _ns.compare(
aString,
options: mask,
range: _toRelativeNSRange(
range ?? startIndex..<endIndex
),
locale: locale?._bridgeToObjectiveC()
)
: range != nil ? _ns.compare(
aString,
options: mask,
range: _toRelativeNSRange(range!)
)
: !mask.isEmpty ? _ns.compare(aString, options: mask)
: _ns.compare(aString)
}
// - (NSUInteger)
// completePathIntoString:(NSString **)outputName
// caseSensitive:(BOOL)flag
// matchesIntoArray:(NSArray **)outputArray
// filterTypes:(NSArray *)filterTypes
/// Interprets the string as a path in the file system and
/// attempts to perform filename completion, returning a numeric
/// value that indicates whether a match was possible, and by
/// reference the longest path that matches the string.
///
/// - Returns: The actual number of matching paths.
public func completePath(
into outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
#if DEPLOYMENT_RUNTIME_SWIFT
var outputNamePlaceholder: String?
var outputArrayPlaceholder = [String]()
let res = self._ns.completePath(
into: &outputNamePlaceholder,
caseSensitive: caseSensitive,
matchesInto: &outputArrayPlaceholder,
filterTypes: filterTypes
)
if let n = outputNamePlaceholder {
outputName?.pointee = n
} else {
outputName?.pointee = ""
}
outputArray?.pointee = outputArrayPlaceholder
return res
#else // DEPLOYMENT_RUNTIME_SWIFT
var nsMatches: NSArray?
var nsOutputName: NSString?
let result: Int = outputName._withNilOrAddress(of: &nsOutputName) {
outputName in outputArray._withNilOrAddress(of: &nsMatches) {
outputArray in
// FIXME: completePath(...) is incorrectly annotated as requiring
// non-optional output parameters. rdar://problem/25494184
let outputNonOptionalName = unsafeBitCast(
outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self)
let outputNonOptionalArray = unsafeBitCast(
outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self)
return self._ns.completePath(
into: outputNonOptionalName,
caseSensitive: caseSensitive,
matchesInto: outputNonOptionalArray,
filterTypes: filterTypes
)
}
}
if let matches = nsMatches {
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
outputArray?.pointee = matches as! [String]
}
if let n = nsOutputName {
outputName?.pointee = n as String
}
return result
#endif // DEPLOYMENT_RUNTIME_SWIFT
}
// - (NSArray *)
// componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
/// Returns an array containing substrings from the string
/// that have been divided by characters in the given set.
public func components(separatedBy separator: CharacterSet) -> [String] {
return _ns.components(separatedBy: separator)
}
// - (NSArray *)componentsSeparatedByString:(NSString *)separator
/// Returns an array containing substrings from the string that have been
/// divided by the given separator.
///
/// The substrings in the resulting array appear in the same order as the
/// original string. Adjacent occurrences of the separator string produce
/// empty strings in the result. Similarly, if the string begins or ends
/// with the separator, the first or last substring, respectively, is empty.
/// The following example shows this behavior:
///
/// let list1 = "Karin, Carrie, David"
/// let items1 = list1.components(separatedBy: ", ")
/// // ["Karin", "Carrie", "David"]
///
/// // Beginning with the separator:
/// let list2 = ", Norman, Stanley, Fletcher"
/// let items2 = list2.components(separatedBy: ", ")
/// // ["", "Norman", "Stanley", "Fletcher"
///
/// If the list has no separators, the array contains only the original
/// string itself.
///
/// let name = "Karin"
/// let list = name.components(separatedBy: ", ")
/// // ["Karin"]
///
/// - Parameter separator: The separator string.
/// - Returns: An array containing substrings that have been divided from the
/// string using `separator`.
// FIXME(strings): now when String conforms to Collection, this can be
// replaced by split(separator:maxSplits:omittingEmptySubsequences:)
public func components<
T : StringProtocol
>(separatedBy separator: T) -> [String] {
return _ns.components(separatedBy: separator._ephemeralString)
}
// - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the string as a C string
/// using a given encoding.
public func cString(using encoding: String.Encoding) -> [CChar]? {
return withExtendedLifetime(_ns) {
(s: NSString) -> [CChar]? in
_persistCString(s.cString(using: encoding.rawValue))
}
}
// - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
//
// - (NSData *)
// dataUsingEncoding:(NSStringEncoding)encoding
// allowLossyConversion:(BOOL)flag
/// Returns a `Data` containing a representation of
/// the `String` encoded using a given encoding.
public func data(
using encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
switch encoding {
case .utf8:
return Data(self.utf8)
default:
return _ns.data(
using: encoding.rawValue,
allowLossyConversion: allowLossyConversion)
}
}
// @property NSString* decomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form D.
public var decomposedStringWithCanonicalMapping: String {
return _ns.decomposedStringWithCanonicalMapping
}
// @property NSString* decomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KD.
public var decomposedStringWithCompatibilityMapping: String {
return _ns.decomposedStringWithCompatibilityMapping
}
//===--- Importing Foundation should not affect String printing ---------===//
// Therefore, we're not exposing this:
//
// @property NSString* description
//===--- Omitted for consistency with API review results 5/20/2014 -----===//
// @property double doubleValue;
// - (void)
// enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block
/// Enumerates all the lines in a string.
public func enumerateLines(
invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void
) {
_ns.enumerateLines {
(line: String, stop: UnsafeMutablePointer<ObjCBool>)
in
var stop_ = false
body(line, &stop_)
if stop_ {
stop.pointee = true
}
}
}
// @property NSStringEncoding fastestEncoding;
/// The fastest encoding to which the string can be converted without loss
/// of information.
public var fastestEncoding: String.Encoding {
return String.Encoding(rawValue: _ns.fastestEncoding)
}
// - (BOOL)
// getCString:(char *)buffer
// maxLength:(NSUInteger)maxBufferCount
// encoding:(NSStringEncoding)encoding
/// Converts the `String`'s content to a given encoding and
/// stores them in a buffer.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
public func getCString(
_ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding
) -> Bool {
return _ns.getCString(&buffer,
maxLength: Swift.min(buffer.count, maxLength),
encoding: encoding.rawValue)
}
// - (NSUInteger)hash
/// An unsigned integer that can be used as a hash table address.
public var hash: Int {
return _ns.hash
}
// - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the number of bytes required to store the
/// `String` in a given encoding.
public func lengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.lengthOfBytes(using: encoding.rawValue)
}
// - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString
/// Compares the string and the given string using a case-insensitive,
/// localized, comparison.
public
func localizedCaseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCaseInsensitiveCompare(aString._ephemeralString)
}
// - (NSComparisonResult)localizedCompare:(NSString *)aString
/// Compares the string and the given string using a localized comparison.
public func localizedCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCompare(aString._ephemeralString)
}
/// Compares the string and the given string as sorted by the Finder.
public func localizedStandardCompare<
T : StringProtocol
>(_ string: T) -> ComparisonResult {
return _ns.localizedStandardCompare(string._ephemeralString)
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property long long longLongValue
// @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0);
/// A lowercase version of the string that is produced using the current
/// locale.
@available(macOS 10.11, iOS 9.0, *)
public var localizedLowercase: String {
return _ns.localizedLowercase
}
// - (NSString *)lowercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to lowercase, taking into account the specified
/// locale.
public func lowercased(with locale: Locale?) -> String {
return _ns.lowercased(with: locale)
}
// - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the maximum number of bytes needed to store the
/// `String` in a given encoding.
public
func maximumLengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.maximumLengthOfBytes(using: encoding.rawValue)
}
// @property NSString* precomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form C.
public var precomposedStringWithCanonicalMapping: String {
return _ns.precomposedStringWithCanonicalMapping
}
// @property NSString * precomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KC.
public var precomposedStringWithCompatibilityMapping: String {
return _ns.precomposedStringWithCompatibilityMapping
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (id)propertyList
/// Parses the `String` as a text representation of a
/// property list, returning an NSString, NSData, NSArray, or
/// NSDictionary object, according to the topmost element.
public func propertyList() -> Any {
return _ns.propertyList()
}
// - (NSDictionary *)propertyListFromStringsFileFormat
/// Returns a dictionary object initialized with the keys and
/// values found in the `String`.
public func propertyListFromStringsFileFormat() -> [String : String] {
return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:]
}
#endif
// - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Returns a Boolean value indicating whether the string contains the given
/// string, taking the current locale into account.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(macOS 10.11, iOS 9.0, *)
public func localizedStandardContains<
T : StringProtocol
>(_ string: T) -> Bool {
return _ns.localizedStandardContains(string._ephemeralString)
}
// @property NSStringEncoding smallestEncoding;