-
Notifications
You must be signed in to change notification settings - Fork 233
Expand file tree
/
Copy pathURL.swift
More file actions
1852 lines (1562 loc) · 97.3 KB
/
URL.swift
File metadata and controls
1852 lines (1562 loc) · 97.3 KB
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 - 2024 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
//
//===----------------------------------------------------------------------===//
#if !FOUNDATION_FRAMEWORK
public struct URLResourceKey {}
#endif
#if FOUNDATION_FRAMEWORK
internal import _ForSwiftFoundation
internal import CoreFoundation_Private.CFURL
/// URLs to file system resources support the properties defined below.
///
/// Note that not all property values will exist for all file system URLs. For example, if a file is located on a volume that does not support creation dates, it is valid to request the creation date property, but the returned value will be nil, and no error will be generated.
///
/// Only the fields requested by the keys you pass into the `URL` function to receive this value will be populated. The others will return `nil` regardless of the underlying property on the file system. As a convenience, volume resource values can be requested from any file system URL. The value returned will reflect the property value for the volume on which the resource is located.
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public struct URLResourceValues {
var _values: [URLResourceKey: Any]
var _keys: Set<URLResourceKey>
public init() {
_values = [:]
_keys = []
}
#if !NO_FILESYSTEM
fileprivate init(keys: Set<URLResourceKey>, values: [URLResourceKey: Any]) {
_values = values
_keys = keys
}
init(values: [URLResourceKey: Any]) {
_values = values
_keys = Set(values.keys)
}
func contains(_ key: URLResourceKey) -> Bool {
return _keys.contains(key)
}
func _get<T>(_ key: URLResourceKey) -> T? {
return _values[key] as? T
}
func _get(_ key: URLResourceKey) -> Bool? {
return (_values[key] as? NSNumber)?.boolValue
}
func _get(_ key: URLResourceKey) -> Int? {
return (_values[key] as? NSNumber)?.intValue
}
private mutating func _set(_ key: URLResourceKey, newValue: __owned Any?) {
_keys.insert(key)
_values[key] = newValue
}
private mutating func _set(_ key: URLResourceKey, newValue: String?) {
_keys.insert(key)
_values[key] = newValue as NSString?
}
private mutating func _set(_ key: URLResourceKey, newValue: [String]?) {
_keys.insert(key)
_values[key] = newValue as NSObject?
}
private mutating func _set(_ key: URLResourceKey, newValue: Date?) {
_keys.insert(key)
_values[key] = newValue as NSDate?
}
private mutating func _set(_ key: URLResourceKey, newValue: URL?) {
_keys.insert(key)
_values[key] = newValue as NSURL?
}
private mutating func _set(_ key: URLResourceKey, newValue: Bool?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
private mutating func _set(_ key: URLResourceKey, newValue: Int?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
/// A loosely-typed dictionary containing all keys and values.
///
/// If you have set temporary keys or non-standard keys, you can find them in here.
public var allValues: [URLResourceKey: Any] {
return _values
}
/// The resource name provided by the file system.
public var name: String? {
get { return _get(.nameKey) }
set { _set(.nameKey, newValue: newValue) }
}
/// Localized or extension-hidden name as displayed to users.
public var localizedName: String? { return _get(.localizedNameKey) }
/// True for regular files.
public var isRegularFile: Bool? { return _get(.isRegularFileKey) }
/// True for directories.
public var isDirectory: Bool? { return _get(.isDirectoryKey) }
/// True for symlinks.
public var isSymbolicLink: Bool? { return _get(.isSymbolicLinkKey) }
/// True for the root directory of a volume.
public var isVolume: Bool? { return _get(.isVolumeKey) }
/// True for packaged directories.
///
/// - note: You can only set or clear this property on directories; if you try to set this property on non-directory objects, the property is ignored. If the directory is a package for some other reason (extension type, etc), setting this property to false will have no effect.
public var isPackage: Bool? {
get { return _get(.isPackageKey) }
set { _set(.isPackageKey, newValue: newValue) }
}
/// True if resource is an application.
@available(macOS 10.11, iOS 9.0, watchOS 2.0, tvOS 9.0, *)
public var isApplication: Bool? { return _get(.isApplicationKey) }
#if os(macOS)
/// True if the resource is scriptable. Only applies to applications.
@available(macOS 10.11, *)
public var applicationIsScriptable: Bool? { return _get(.applicationIsScriptableKey) }
#endif
/// True for system-immutable resources.
public var isSystemImmutable: Bool? { return _get(.isSystemImmutableKey) }
/// True for user-immutable resources
public var isUserImmutable: Bool? {
get { return _get(.isUserImmutableKey) }
set { _set(.isUserImmutableKey, newValue: newValue) }
}
/// True for resources normally not displayed to users.
///
/// - note: If the resource is a hidden because its name starts with a period, setting this property to false will not change the property.
public var isHidden: Bool? {
get { return _get(.isHiddenKey) }
set { _set(.isHiddenKey, newValue: newValue) }
}
/// True for resources whose filename extension is removed from the localized name property.
public var hasHiddenExtension: Bool? {
get { return _get(.hasHiddenExtensionKey) }
set { _set(.hasHiddenExtensionKey, newValue: newValue) }
}
/// The date the resource was created.
public var creationDate: Date? {
get { return _get(.creationDateKey) }
set { _set(.creationDateKey, newValue: newValue) }
}
/// The date the resource was last accessed.
public var contentAccessDate: Date? {
get { return _get(.contentAccessDateKey) }
set { _set(.contentAccessDateKey, newValue: newValue) }
}
/// The time the resource content was last modified.
public var contentModificationDate: Date? {
get { return _get(.contentModificationDateKey) }
set { _set(.contentModificationDateKey, newValue: newValue) }
}
/// The time the resource's attributes were last modified.
public var attributeModificationDate: Date? { return _get(.attributeModificationDateKey) }
/// Number of hard links to the resource.
public var linkCount: Int? { return _get(.linkCountKey) }
/// The resource's parent directory, if any.
public var parentDirectory: URL? { return _get(.parentDirectoryURLKey) }
/// URL of the volume on which the resource is stored.
public var volume: URL? { return _get(.volumeURLKey) }
/// Uniform type identifier (UTI) for the resource.
@available(macOS, introduced: 10.10, deprecated: 100000.0, message: "Use .contentType instead")
@available(iOS, introduced: 8.0, deprecated: 100000.0, message: "Use .contentType instead")
@available(watchOS, introduced: 2.0, deprecated: 100000.0, message: "Use .contentType instead")
@available(tvOS, introduced: 9.0, deprecated: 100000.0, message: "Use .contentType instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use .contentType instead")
public var typeIdentifier: String? { return _get(.typeIdentifierKey) }
/// User-visible type or "kind" description.
public var localizedTypeDescription: String? { return _get(.localizedTypeDescriptionKey) }
/// The label number assigned to the resource.
public var labelNumber: Int? {
get { return _get(.labelNumberKey) }
set { _set(.labelNumberKey, newValue: newValue) }
}
/// The user-visible label text.
public var localizedLabel: String? {
get { return _get(.localizedLabelKey) }
}
/// An identifier which can be used to compare two file system objects for equality using `isEqual`.
///
/// Two object identifiers are equal if they have the same file system path or if the paths are linked to same inode on the same file system. This identifier is not persistent across system restarts.
public var fileResourceIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.fileResourceIdentifierKey) }
/// An identifier that can be used to identify the volume the file system object is on.
///
/// Other objects on the same volume will have the same volume identifier and can be compared using for equality using `isEqual`. This identifier is not persistent across system restarts.
public var volumeIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.volumeIdentifierKey) }
/// The file system's internal inode identifier for the item. This value is not stable for all file systems or
/// across all mounts, so it should be used sparingly and not persisted. It is useful, for example, to match URLs from
/// the URL enumerator with paths from FSEvents.
@available( macOS 13.3, iOS 16.4, tvOS 16.4, watchOS 9.4, *)
public var fileIdentifier: UInt64? { return _get(.fileIdentifierKey) }
/// A 64-bit value assigned by APFS that identifies a file's content data stream. Only cloned files and their originals can have the same identifier.
@available(macOS 10.16, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
public var fileContentIdentifier: Int64? { return _get(.fileContentIdentifierKey) }
/// The optimal block size when reading or writing this file's data, or nil if not available.
public var preferredIOBlockSize: Int? { return _get(.preferredIOBlockSizeKey) }
/// True if this process (as determined by EUID) can read the resource.
public var isReadable: Bool? { return _get(.isReadableKey) }
/// True if this process (as determined by EUID) can write to the resource.
public var isWritable: Bool? { return _get(.isWritableKey) }
/// True if this process (as determined by EUID) can execute a file resource or search a directory resource.
public var isExecutable: Bool? { return _get(.isExecutableKey) }
/// The file system object's security information encapsulated in a FileSecurity object.
public var fileSecurity: NSFileSecurity? {
get { return _get(.fileSecurityKey) }
set { _set(.fileSecurityKey, newValue: newValue) }
}
/// True if resource should be excluded from backups, false otherwise.
///
/// This property is only useful for excluding cache and other application support files which are not needed in a backup. Some operations commonly made to user documents will cause this property to be reset to false and so this property should not be used on user documents.
public var isExcludedFromBackup: Bool? {
get { return _get(.isExcludedFromBackupKey) }
set { _set(.isExcludedFromBackupKey, newValue: newValue) }
}
#if os(macOS)
/// The array of Tag names.
public var tagNames: [String]? {
get { return _get(.tagNamesKey) }
@available(macOS 26.0, *)
set { _set(.tagNamesKey, newValue: newValue) }
}
#endif
/// The URL's path as a file system path.
public var path: String? { return _get(.pathKey) }
/// The URL's path as a canonical absolute file system path.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var canonicalPath: String? { return _get(.canonicalPathKey) }
/// True if this URL is a file system trigger directory. Traversing or opening a file system trigger will cause an attempt to mount a file system on the trigger directory.
public var isMountTrigger: Bool? { return _get(.isMountTriggerKey) }
/// An opaque generation identifier which can be compared using `==` to determine if the data in a document has been modified.
///
/// For URLs which refer to the same file inode, the generation identifier will change when the data in the file's data fork is changed (changes to extended attributes or other file system metadata do not change the generation identifier). For URLs which refer to the same directory inode, the generation identifier will change when direct children of that directory are added, removed or renamed (changes to the data of the direct children of that directory will not change the generation identifier). The generation identifier is persistent across system restarts. The generation identifier is tied to a specific document on a specific volume and is not transferred when the document is copied to another volume. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public var generationIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.generationIdentifierKey) }
/// The document identifier -- a value assigned by the kernel to a document (which can be either a file or directory) and is used to identify the document regardless of where it gets moved on a volume.
///
/// The document identifier survives "safe save" operations; i.e it is sticky to the path it was assigned to (`replaceItem(at:,withItemAt:,backupItemName:,options:,resultingItem:) throws` is the preferred safe-save API). The document identifier is persistent across system restarts. The document identifier is not transferred when the file is copied. Document identifiers are only unique within a single volume. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public var documentIdentifier: Int? { return _get(.documentIdentifierKey) }
/// The date the resource was created, or renamed into or within its parent directory. Note that inconsistent behavior may be observed when this attribute is requested on hard-linked items. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public var addedToDirectoryDate: Date? { return _get(.addedToDirectoryDateKey) }
#if os(macOS)
/// The quarantine properties as defined in LSQuarantine.h. To remove quarantine information from a file, pass `nil` as the value when setting this property.
@available(macOS 10.10, *)
public var quarantineProperties: [String: Any]? {
get {
let value = _values[.quarantinePropertiesKey]
// If a caller has caused us to stash NSNull in the dictionary (via set), make sure to return nil instead of NSNull
if value is NSNull {
return nil
} else {
return value as? [String: Any]
}
}
set {
// Use NSNull for nil, a special case for deleting quarantine properties
_set(.quarantinePropertiesKey, newValue: newValue ?? NSNull())
}
}
#endif // os(macOS)
/// True if the file may have extended attributes. False guarantees there are none.
@available(macOS 10.16, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
public var mayHaveExtendedAttributes: Bool? { return _get(.mayHaveExtendedAttributesKey) }
/// True if the file can be deleted by the file system when asked to free space.
@available(macOS 10.16, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
public var isPurgeable: Bool? { return _get(.isPurgeableKey) }
/// True if the file has sparse regions.
@available(macOS 10.16, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
public var isSparse: Bool? { return _get(.isSparseKey) }
/// True for cloned files and their originals that may share all, some, or no data blocks.
@available(macOS 10.16, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
public var mayShareFileContent: Bool? { return _get(.mayShareFileContentKey) }
/// Returns the file system object type.
public var fileResourceType: URLFileResourceType? { return _get(.fileResourceTypeKey) }
/// Returns the count of file system objects contained in the directory. If the URL is not a directory or the file system cannot cheaply compute the value, `nil` is returned.
@available( macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *)
public var directoryEntryCount: Int? { return _get(.directoryEntryCountKey) }
/// The user-visible volume format.
public var volumeLocalizedFormatDescription: String? { return _get(.volumeLocalizedFormatDescriptionKey) }
/// Total volume capacity in bytes.
public var volumeTotalCapacity: Int? { return _get(.volumeTotalCapacityKey) }
/// Total free space in bytes.
public var volumeAvailableCapacity: Int? { return _get(.volumeAvailableCapacityKey) }
#if os(macOS) || os(iOS)
/// Total available capacity in bytes for "Important" resources, including space expected to be cleared by purging non-essential and cached resources.
///
/// "Important" means something that the user or application clearly expects to be present on the local system, but is ultimately replaceable. This would include items that the user has explicitly requested via the UI, and resources that an application requires in order to provide functionality.
/// Examples: A video that the user has explicitly requested to watch but has not yet finished watching or an audio file that the user has requested to download.
/// This value should not be used in determining if there is room for an irreplaceable resource. In the case of irreplaceable resources, always attempt to save the resource regardless of available capacity and handle failure as gracefully as possible.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var volumeAvailableCapacityForImportantUsage: Int64? { return _get(.volumeAvailableCapacityForImportantUsageKey) }
/// Total available capacity in bytes for "Opportunistic" resources, including space expected to be cleared by purging non-essential and cached resources.
///
/// "Opportunistic" means something that the user is likely to want but does not expect to be present on the local system, but is ultimately non-essential and replaceable. This would include items that will be created or downloaded without an explicit request from the user on the current device.
/// Examples: A background download of a newly available episode of a TV series that a user has been recently watching, a piece of content explicitly requested on another device, and a new document saved to a network server by the current user from another device.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var volumeAvailableCapacityForOpportunisticUsage: Int64? { return _get(.volumeAvailableCapacityForOpportunisticUsageKey) }
#endif // os(macOS) || os(iOS)
/// Total number of resources on the volume.
public var volumeResourceCount: Int? { return _get(.volumeResourceCountKey) }
/// True if the volume format supports persistent object identifiers and can look up file system objects by their IDs.
public var volumeSupportsPersistentIDs: Bool? { return _get(.volumeSupportsPersistentIDsKey) }
/// True if the volume format supports symbolic links.
public var volumeSupportsSymbolicLinks: Bool? { return _get(.volumeSupportsSymbolicLinksKey) }
/// True if the volume format supports hard links.
public var volumeSupportsHardLinks: Bool? { return _get(.volumeSupportsHardLinksKey) }
/// True if the volume format supports a journal used to speed recovery in case of unplanned restart (such as a power outage or crash). This does not necessarily mean the volume is actively using a journal.
public var volumeSupportsJournaling: Bool? { return _get(.volumeSupportsJournalingKey) }
/// True if the volume is currently using a journal for speedy recovery after an unplanned restart.
public var volumeIsJournaling: Bool? { return _get(.volumeIsJournalingKey) }
/// True if the volume format supports sparse files, that is, files which can have 'holes' that have never been written to, and thus do not consume space on disk. A sparse file may have an allocated size on disk that is less than its logical length.
public var volumeSupportsSparseFiles: Bool? { return _get(.volumeSupportsSparseFilesKey) }
/// For security reasons, parts of a file (runs) that have never been written to must appear to contain zeroes. True if the volume keeps track of allocated but unwritten runs of a file so that it can substitute zeroes without actually writing zeroes to the media.
public var volumeSupportsZeroRuns: Bool? { return _get(.volumeSupportsZeroRunsKey) }
/// True if the volume format treats upper and lower case characters in file and directory names as different. Otherwise an upper case character is equivalent to a lower case character, and you can't have two names that differ solely in the case of the characters.
public var volumeSupportsCaseSensitiveNames: Bool? { return _get(.volumeSupportsCaseSensitiveNamesKey) }
/// True if the volume format preserves the case of file and directory names. Otherwise the volume may change the case of some characters (typically making them all upper or all lower case).
public var volumeSupportsCasePreservedNames: Bool? { return _get(.volumeSupportsCasePreservedNamesKey) }
/// True if the volume supports reliable storage of times for the root directory.
public var volumeSupportsRootDirectoryDates: Bool? { return _get(.volumeSupportsRootDirectoryDatesKey) }
/// True if the volume supports returning volume size values (`volumeTotalCapacity` and `volumeAvailableCapacity`).
public var volumeSupportsVolumeSizes: Bool? { return _get(.volumeSupportsVolumeSizesKey) }
/// True if the volume can be renamed.
public var volumeSupportsRenaming: Bool? { return _get(.volumeSupportsRenamingKey) }
/// True if the volume implements whole-file flock(2) style advisory locks, and the O_EXLOCK and O_SHLOCK flags of the open(2) call.
public var volumeSupportsAdvisoryFileLocking: Bool? { return _get(.volumeSupportsAdvisoryFileLockingKey) }
/// True if the volume implements extended security (ACLs).
public var volumeSupportsExtendedSecurity: Bool? { return _get(.volumeSupportsExtendedSecurityKey) }
/// True if the volume should be visible via the GUI (i.e., appear on the Desktop as a separate volume).
public var volumeIsBrowsable: Bool? { return _get(.volumeIsBrowsableKey) }
/// The largest file size (in bytes) supported by this file system, or nil if this cannot be determined.
public var volumeMaximumFileSize: Int? { return _get(.volumeMaximumFileSizeKey) }
/// True if the volume's media is ejectable from the drive mechanism under software control.
public var volumeIsEjectable: Bool? { return _get(.volumeIsEjectableKey) }
/// True if the volume's media is removable from the drive mechanism.
public var volumeIsRemovable: Bool? { return _get(.volumeIsRemovableKey) }
/// True if the volume's device is connected to an internal bus, false if connected to an external bus, or nil if not available.
public var volumeIsInternal: Bool? { return _get(.volumeIsInternalKey) }
/// True if the volume is automounted. Note: do not mistake this with the functionality provided by kCFURLVolumeSupportsBrowsingKey.
public var volumeIsAutomounted: Bool? { return _get(.volumeIsAutomountedKey) }
/// True if the volume is stored on a local device.
public var volumeIsLocal: Bool? { return _get(.volumeIsLocalKey) }
/// True if the volume is read-only.
public var volumeIsReadOnly: Bool? { return _get(.volumeIsReadOnlyKey) }
/// The volume's creation date, or nil if this cannot be determined.
public var volumeCreationDate: Date? { return _get(.volumeCreationDateKey) }
/// The `URL` needed to remount a network volume, or nil if not available.
public var volumeURLForRemounting: URL? { return _get(.volumeURLForRemountingKey) }
/// The volume's persistent `UUID` as a string, or nil if a persistent `UUID` is not available for the volume.
public var volumeUUIDString: String? { return _get(.volumeUUIDStringKey) }
/// The name of the volume
public var volumeName: String? {
get { return _get(.volumeNameKey) }
set { _set(.volumeNameKey, newValue: newValue) }
}
/// The user-presentable name of the volume
public var volumeLocalizedName: String? { return _get(.volumeLocalizedNameKey) }
/// True if the volume is encrypted.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsEncrypted: Bool? { return _get(.volumeIsEncryptedKey) }
/// True if the volume is the root filesystem.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsRootFileSystem: Bool? { return _get(.volumeIsRootFileSystemKey) }
/// True if the volume supports transparent decompression of compressed files using decmpfs.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsCompression: Bool? { return _get(.volumeSupportsCompressionKey) }
/// True if the volume supports clonefile(2).
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsFileCloning: Bool? { return _get(.volumeSupportsFileCloningKey) }
/// True if the volume supports renamex_np(2)'s RENAME_SWAP option.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsSwapRenaming: Bool? { return _get(.volumeSupportsSwapRenamingKey) }
/// True if the volume supports renamex_np(2)'s RENAME_EXCL option.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsExclusiveRenaming: Bool? { return _get(.volumeSupportsExclusiveRenamingKey) }
/// True if the volume supports making files immutable with isUserImmutable or isSystemImmutable.
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
public var volumeSupportsImmutableFiles: Bool? { return _get(.volumeSupportsImmutableFilesKey) }
/// True if the volume supports setting POSIX access permissions with fileSecurity.
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
public var volumeSupportsAccessPermissions: Bool? { return _get(.volumeSupportsAccessPermissionsKey) }
/// Returns the name of the file system type.
@available( macOS 13.3, iOS 16.4, tvOS 16.4, watchOS 9.4, *)
public var volumeTypeName: String? { return _get(.volumeTypeNameKey) }
/// Returns the file system subtype.
@available( macOS 13.3, iOS 16.4, tvOS 16.4, watchOS 9.4, *)
public var volumeSubtype: Int? { return _get(.volumeSubtypeKey) }
/// Returns the file system device location.
@available( macOS 13.3, iOS 16.4, tvOS 16.4, watchOS 9.4, *)
public var volumeMountFromLocation: String? { return _get(.volumeMountFromLocationKey) }
/// True if this item is synced to the cloud, false if it is only a local file.
public var isUbiquitousItem: Bool? { return _get(.isUbiquitousItemKey) }
/// True if this item has conflicts outstanding.
public var ubiquitousItemHasUnresolvedConflicts: Bool? { return _get(.ubiquitousItemHasUnresolvedConflictsKey) }
/// True if data is being downloaded for this item.
public var ubiquitousItemIsDownloading: Bool? { return _get(.ubiquitousItemIsDownloadingKey) }
/// True if there is data present in the cloud for this item.
public var ubiquitousItemIsUploaded: Bool? { return _get(.ubiquitousItemIsUploadedKey) }
/// True if data is being uploaded for this item.
public var ubiquitousItemIsUploading: Bool? { return _get(.ubiquitousItemIsUploadingKey) }
/// Returns the download status of this item.
public var ubiquitousItemDownloadingStatus: URLUbiquitousItemDownloadingStatus? { return _get(.ubiquitousItemDownloadingStatusKey) }
/// Returns the error when downloading the item from iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemDownloadingError: NSError? { return _get(.ubiquitousItemDownloadingErrorKey) }
/// Returns the error when uploading the item to iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemUploadingError: NSError? { return _get(.ubiquitousItemUploadingErrorKey) }
/// Returns whether a download of this item has already been requested with an API like `startDownloadingUbiquitousItem(at:) throws`.
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public var ubiquitousItemDownloadRequested: Bool? { return _get(.ubiquitousItemDownloadRequestedKey) }
/// Returns the name of this item's container as displayed to users.
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public var ubiquitousItemContainerDisplayName: String? { return _get(.ubiquitousItemContainerDisplayNameKey) }
/// True if the item is excluded from sync, which means it is locally on disk but won't be available on the server. An excluded item is no longer ubiquitous.
@available(macOS 11.3, iOS 14.5, watchOS 7.4, tvOS 14.5, *)
public var ubiquitousItemIsExcludedFromSync: Bool? {
get { return _get(.ubiquitousItemIsExcludedFromSyncKey) }
set { _set(.ubiquitousItemIsExcludedFromSyncKey, newValue: newValue) }
}
#if os(macOS) || os(iOS)
/// True if ubiquitous item is shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousItemIsShared: Bool? { return _get(.ubiquitousItemIsSharedKey) }
/// The current user's role for this shared item, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemCurrentUserRole: URLUbiquitousSharedItemRole? { return _get(.ubiquitousSharedItemCurrentUserRoleKey) }
/// The permissions for the current user, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemCurrentUserPermissions: URLUbiquitousSharedItemPermissions? { return _get(.ubiquitousSharedItemCurrentUserPermissionsKey) }
/// The name components for the owner, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemOwnerNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemOwnerNameComponentsKey) }
/// The name components for the most recent editor, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemMostRecentEditorNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemMostRecentEditorNameComponentsKey) }
#endif // os(macOS) || os(iOS)
/// The protection level for this file
@available(macOS 10.16, iOS 9.0, *)
public var fileProtection: URLFileProtection? { return _get(.fileProtectionKey) }
/// Total file size in bytes
///
/// - note: Only applicable to regular files.
public var fileSize: Int? { return _get(.fileSizeKey) }
/// Total size allocated on disk for the file in bytes (number of blocks times block size)
///
/// - note: Only applicable to regular files.
public var fileAllocatedSize: Int? { return _get(.fileAllocatedSizeKey) }
/// Total displayable size of the file in bytes (this may include space used by metadata), or nil if not available.
///
/// - note: Only applicable to regular files.
public var totalFileSize: Int? { return _get(.totalFileSizeKey) }
/// Total allocated size of the file in bytes (this may include space used by metadata), or nil if not available. This can be less than the value returned by `totalFileSize` if the resource is compressed.
///
/// - note: Only applicable to regular files.
public var totalFileAllocatedSize: Int? { return _get(.totalFileAllocatedSizeKey) }
/// true if the resource is a Finder alias file or a symlink, false otherwise
///
/// - note: Only applicable to regular files.
public var isAliasFile: Bool? { return _get(.isAliasFileKey) }
#endif // !NO_FILESYSTEM
}
@available(macOS, unavailable, introduced: 10.10)
@available(iOS, unavailable, introduced: 8.0)
@available(tvOS, unavailable, introduced: 9.0)
@available(watchOS, unavailable, introduced: 2.0)
@available(*, unavailable)
extension URLResourceValues : Sendable {}
#endif // FOUNDATION_FRAMEWORK
#if FOUNDATION_FRAMEWORK
internal func foundation_swift_url_enabled() -> Bool {
return _foundation_swift_url_feature_enabled()
}
internal func foundation_swift_nsurl_enabled() -> Bool {
return _foundation_swift_nsurl_feature_enabled()
}
internal func foundation_swift_url_v2_enabled() -> Bool {
return _foundation_swift_url_v2_enabled()
}
#else
internal func foundation_swift_url_enabled() -> Bool { return true }
internal func foundation_swift_url_v2_enabled() -> Bool { return true }
#endif
#if canImport(os)
internal import os
#endif
/// A URL is a type that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
///
/// You can construct URLs and access their parts. For URLs that represent local files, you can also manipulate properties of those files directly, such as changing the file's last modification date. Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example, you can use the URLSession classes to access the contents of remote resources, as described in URL Session Programming Guide.
///
/// URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference. For example, you can get the contents of a local file URL as `String` by calling `func init(contentsOf:encoding:) throws`, or as a `Data` by calling `func init(contentsOf:options:) throws`.
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public struct URL: Equatable, Sendable, Hashable {
#if canImport(os)
internal static let logger: Logger = {
Logger(subsystem: "com.apple.foundation", category: "url")
}()
#endif
#if FOUNDATION_FRAMEWORK
internal typealias _Impl = any _URLProtocol & AnyObject
private static var _type: any _URLProtocol.Type {
if URL.compatibility2 {
_BridgedURL.self
} else if foundation_swift_url_v2_enabled() {
_URL.self
} else if foundation_swift_url_enabled() {
_SwiftURL.self
} else {
_BridgedURL.self
}
}
#else
internal typealias _Impl = _URL
private static let _type = _Impl.self
#endif
internal let _url: _Impl
internal init(_ url: _Impl) {
_url = url
}
#if os(Linux)
// Workaround to fix a Linux-only crash in swift_release.
// Add padding to return struct URL to its original size
// before the _SwiftURL refactor.
private var _padding: URLParseInfo?
#endif
#if FOUNDATION_FRAMEWORK && !NO_FILESYSTEM
public typealias BookmarkResolutionOptions = NSURL.BookmarkResolutionOptions
public typealias BookmarkCreationOptions = NSURL.BookmarkCreationOptions
#endif
internal static let fileIDPrefix = Array("/.file/id=".utf8)
/// The public initializers don't allow the empty string, and we must maintain that behavior
/// for compatibility. However, there are cases internally where we need to create a URL with
/// an empty string, such as when `.deletingLastPathComponent()` of a single path
/// component. This previously worked since `URL` just wrapped an `NSURL`, which
/// allows the empty string.
internal init?(stringOrEmpty: String, relativeTo url: URL? = nil) {
guard let inner = URL._type.init(stringOrEmpty: stringOrEmpty, relativeTo: url) else { return nil }
_url = inner.convertingFileReference()
}
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: __shared String) {
guard let inner = URL._type.init(string: string) else { return nil }
_url = inner.convertingFileReference()
}
/// Initialize with string, relative to another URL.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: __shared String, relativeTo url: __shared URL?) {
guard let inner = URL._type.init(string: string, relativeTo: url) else { return nil }
_url = inner.convertingFileReference()
}
/// Initialize with a URL string and the option to add (or skip) IDNA- and percent-encoding of invalid characters.
///
/// If `encodingInvalidCharacters` is false, and the URL string is invalid according to RFC 3986, `nil` is returned.
/// If `encodingInvalidCharacters` is true, `URL` will try to encode the string to create a valid URL.
/// If the URL string is still invalid after encoding, `nil` is returned.
@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
public init?(string: __shared String, encodingInvalidCharacters: Bool) {
guard let inner = URL._type.init(string: string, encodingInvalidCharacters: encodingInvalidCharacters) else { return nil }
_url = inner.convertingFileReference()
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - Note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
@available(macOS, introduced: 10.10, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(iOS, introduced: 8.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(tvOS, introduced: 9.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(watchOS, introduced: 2.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
public init(fileURLWithPath path: __shared String, isDirectory: Bool, relativeTo base: __shared URL?) {
_url = URL._type.init(fileURLWithPath: path, isDirectory: isDirectory, relativeTo: base).convertingFileReference()
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
@available(macOS, introduced: 10.10, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(iOS, introduced: 8.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(tvOS, introduced: 9.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(watchOS, introduced: 2.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
public init(fileURLWithPath path: __shared String, relativeTo base: __shared URL?) {
_url = URL._type.init(fileURLWithPath: path, relativeTo: base).convertingFileReference()
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
@available(macOS, introduced: 10.10, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(iOS, introduced: 8.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(tvOS, introduced: 9.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(watchOS, introduced: 2.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
public init(fileURLWithPath path: __shared String, isDirectory: Bool) {
_url = URL._type.init(fileURLWithPath: path, isDirectory: isDirectory).convertingFileReference()
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
@available(macOS, introduced: 10.10, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(iOS, introduced: 8.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(tvOS, introduced: 9.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(watchOS, introduced: 2.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use init(filePath:directoryHint:relativeTo:) instead")
public init(fileURLWithPath path: __shared String) {
_url = URL._type.init(fileURLWithPath: path).convertingFileReference()
}
// NSURL(fileURLWithPath:) can return nil incorrectly for some malformed paths
// This is only to be used by FileManager when dealing with potentially malformed paths, and only when truly necessary
internal init?(_fileManagerFailableFileURLWithPath path: __shared String) {
#if FOUNDATION_FRAMEWORK
guard foundation_swift_url_enabled() else {
let url = _BridgedURL(fileURLWithPath: path, isDirectory: path.utf8.last == ._slash)
guard unsafeBitCast(url, to: UnsafeRawPointer?.self) != nil else {
return nil
}
_url = url.convertingFileReference()
return
}
#endif
// Infer from the path to prevent a file system check for what is likely a non-existent, malformed, or inaccessible path
_url = URL._type.init(filePath: path, directoryHint: .inferFromPath, relativeTo: nil).convertingFileReference()
}
/// Initializes a newly created URL using the contents of the given data, relative to a base URL.
///
/// If the data representation is not a legal URL string as ASCII bytes, the URL object may not behave as expected. If the URL cannot be formed then this will return nil.
@available(macOS 10.11, iOS 9.0, watchOS 2.0, tvOS 9.0, *)
public init?(dataRepresentation: __shared Data, relativeTo base: __shared URL?, isAbsolute: Bool = false) {
guard let inner = URL._type.init(dataRepresentation: dataRepresentation, relativeTo: base, isAbsolute: isAbsolute) else { return nil }
_url = inner.convertingFileReference()
}
#if !NO_FILESYSTEM && FOUNDATION_FRAMEWORK
/// Initializes a URL that refers to a location specified by resolving bookmark data.
@available(swift, obsoleted: 4.2)
public init?(resolvingBookmarkData data: __shared Data, options: BookmarkResolutionOptions = [], relativeTo url: __shared URL? = nil, bookmarkDataIsStale: inout Bool) throws {
try self.init(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &bookmarkDataIsStale)
}
/// Initializes a URL that refers to a location specified by resolving bookmark data.
@available(swift, introduced: 4.2)
public init(resolvingBookmarkData data: __shared Data, options: BookmarkResolutionOptions = [], relativeTo url: __shared URL? = nil, bookmarkDataIsStale: inout Bool) throws {
var stale: ObjCBool = false
let nsURL = try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale)
bookmarkDataIsStale = stale.boolValue
self.init(reference: nsURL)
}
/// Creates and initializes a URL that refers to the location specified by resolving the alias file at `url`. If the `url` argument does not refer to an alias file as defined by the `.isAliasFileKey` property, the URL returned is the same as the `url` argument. This method fails and returns `nil` if the `url` argument is unreachable, or if the original file or directory could not be located or is not reachable, or if the original file or directory is on a volume that could not be located or mounted. The `URLBookmarkResolutionWithSecurityScope` option is not supported by this method.
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public init(resolvingAliasFileAt url: __shared URL, options: BookmarkResolutionOptions = []) throws {
self.init(reference: try NSURL(resolvingAliasFileAt: url, options: options))
}
#endif // !NO_FILESYSTEM && FOUNDATION_FRAMEWORK
/// Initializes a newly created URL referencing the local file or directory at the file system representation of the path. File system representation is a null-terminated C string with canonical UTF-8 encoding.
public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeTo base: __shared URL?) {
_url = URL._type.init(fileURLWithFileSystemRepresentation: path, isDirectory: isDirectory, relativeTo: base).convertingFileReference()
}
/// Returns the data representation of the URL's relativeString.
///
/// If the URL was initialized with `init?(dataRepresentation:relativeTo:isAbsolute:)`, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the `relativeString` encoded with UTF8 string encoding.
@available(macOS 10.11, iOS 9.0, watchOS 2.0, tvOS 9.0, *)
public var dataRepresentation: Data {
return _url.dataRepresentation
}
/// Returns the absolute string for the URL.
public var absoluteString: String {
return _url.absoluteString
}
/// Returns the relative portion of a URL.
///
/// If `baseURL` is nil, or if the receiver is itself absolute, this is the same as `absoluteString`.
public var relativeString: String {
return _url.relativeString
}
/// Returns the base URL.
///
/// If the URL is itself absolute, then this value is nil.
public var baseURL: URL? {
return _url.baseURL
}
/// Returns the absolute URL.
///
/// If the URL is itself absolute, this will return self.
public var absoluteURL: URL {
return _url.absoluteURL ?? self
}
/// Returns the scheme of the URL.
public var scheme: String? {
return _url.scheme
}
/// Returns true if the scheme is `file:`.
public var isFileURL: Bool {
return _url.isFileURL
}
internal var hasAuthority: Bool {
return _url.hasAuthority
}
/// Returns the host component of the URL if present, otherwise returns `nil`.
///
/// - note: This function will resolve against the base `URL`.
@available(macOS, introduced: 10.10, deprecated: 100000.0, message: "Use host(percentEncoded:) instead")
@available(iOS, introduced: 8.0, deprecated: 100000.0, message: "Use host(percentEncoded:) instead")
@available(tvOS, introduced: 9.0, deprecated: 100000.0, message: "Use host(percentEncoded:) instead")
@available(watchOS, introduced: 2.0, deprecated: 100000.0, message: "Use host(percentEncoded:) instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use host(percentEncoded:) instead")
public var host: String? {
return _url.host
}
/// Returns the host component of the URL if present, otherwise returns `nil`.
///
/// - Parameter percentEncoded: Whether the host should be percent encoded,
/// defaults to `true`.
/// - Returns: The host component of the URL
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
public func host(percentEncoded: Bool = true) -> String? {
return _url.host(percentEncoded: percentEncoded)
}
/// Returns the port component of the URL if present, otherwise returns `nil`.
///
/// - note: This function will resolve against the base `URL`.
public var port: Int? {
return _url.port
}
/// Returns the user component of the URL if present, otherwise returns `nil`.
///
/// - note: This function will resolve against the base `URL`.
@available(macOS, introduced: 10.10, deprecated: 100000.0, message: "Use user(percentEncoded:) instead")
@available(iOS, introduced: 8.0, deprecated: 100000.0, message: "Use user(percentEncoded:) instead")
@available(tvOS, introduced: 9.0, deprecated: 100000.0, message: "Use user(percentEncoded:) instead")
@available(watchOS, introduced: 2.0, deprecated: 100000.0, message: "Use user(percentEncoded:) instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use user(percentEncoded:) instead")
public var user: String? {
return _url.user
}
/// Returns the user component of the URL if present, otherwise returns `nil`.
/// - Parameter percentEncoded: Whether the user should be percent encoded,
/// defaults to `true`.
/// - Returns: The user component of the URL.
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
public func user(percentEncoded: Bool = true) -> String? {
return _url.user(percentEncoded: percentEncoded)
}
/// Returns the password component of the URL if present, otherwise returns `nil`.
///
/// - note: This function will resolve against the base `URL`.
@available(macOS, introduced: 10.10, deprecated: 100000.0, message: "Use password(percentEncoded:) instead")
@available(iOS, introduced: 8.0, deprecated: 100000.0, message: "Use password(percentEncoded:) instead")
@available(tvOS, introduced: 9.0, deprecated: 100000.0, message: "Use password(percentEncoded:) instead")
@available(watchOS, introduced: 2.0, deprecated: 100000.0, message: "Use password(percentEncoded:) instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use password(percentEncoded:) instead")
public var password: String? {
return _url.password
}
/// Returns the password component of the URL if present, otherwise returns `nil`.
/// - Parameter percentEncoded: Whether the password should be percent encoded,
/// defaults to `true`.
/// - Returns: The password component of the URL.
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
public func password(percentEncoded: Bool = true) -> String? {
return _url.password(percentEncoded: percentEncoded)
}
internal func absolutePath(percentEncoded: Bool = true) -> String {
return _url.absolutePath(percentEncoded: percentEncoded)
}
/// Returns the path component of the URL if present, otherwise returns an empty string.
///
/// - note: This function will resolve against the base `URL`.
/// - returns: The path, or an empty string if the URL has an empty path.
@available(macOS, introduced: 10.10, deprecated: 100000.0, message: "Use path(percentEncoded:) instead")
@available(iOS, introduced: 8.0, deprecated: 100000.0, message: "Use path(percentEncoded:) instead")
@available(tvOS, introduced: 9.0, deprecated: 100000.0, message: "Use path(percentEncoded:) instead")
@available(watchOS, introduced: 2.0, deprecated: 100000.0, message: "Use path(percentEncoded:) instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use path(percentEncoded:) instead")
public var path: String {
return _url.path
}
/// Returns the path component of the URL if present, otherwise returns an empty string.
/// - note: This function will resolve against the base `URL`.
/// - Parameter percentEncoded: Whether the path should be percent encoded,
/// defaults to `true`.
/// - Returns: The path component of the URL.
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
public func path(percentEncoded: Bool = true) -> String {
return _url.path(percentEncoded: percentEncoded)
}
/// Returns the relative path of the URL if present, otherwise returns an empty string. This is the same as `path` if `baseURL` is `nil`.
///
/// - returns: The relative path, or an empty string if the URL has an empty path.
public var relativePath: String {
return _url.relativePath
}
internal func relativePath(percentEncoded: Bool = true) -> String {
return _url.relativePath(percentEncoded: percentEncoded)
}
/// Returns the query component of the URL if present, otherwise returns `nil`.
///
/// - note: This function will resolve against the base `URL`.
@available(macOS, introduced: 10.10, deprecated: 100000.0, message: "Use query(percentEncoded:) instead")
@available(iOS, introduced: 8.0, deprecated: 100000.0, message: "Use query(percentEncoded:) instead")
@available(tvOS, introduced: 9.0, deprecated: 100000.0, message: "Use query(percentEncoded:) instead")
@available(watchOS, introduced: 2.0, deprecated: 100000.0, message: "Use query(percentEncoded:) instead")
@available(visionOS, introduced: 1.0, deprecated: 100000.0, message: "Use query(percentEncoded:) instead")
public var query: String? {
return _url.query
}
/// Returns the password component of the URL if present, otherwise returns `nil`.
/// - Parameter percentEncoded: Whether the query should be percent encoded,
/// defaults to `true`.
/// - Returns: The query component of the URL.
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
public func query(percentEncoded: Bool = true) -> String? {
return _url.query(percentEncoded: percentEncoded)