Skip to content

Commit 28d0806

Browse files
committed
Add URL extensions
1 parent 4fd054d commit 28d0806

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

Sources/HTTP/Extensions/URL.swift

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//
2+
// URL.swift
3+
// HTTP
4+
//
5+
// Created by Alsey Coleman Miller on 10/1/25.
6+
//
7+
8+
import Foundation
9+
#if canImport(FoundationNetworking)
10+
import FoundationNetworking
11+
#endif
12+
13+
public extension URL {
14+
15+
func appending(_ queryItems: URLQueryItem?...) -> URL {
16+
let items = queryItems.compactMap({ $0 })
17+
return appending(items)
18+
}
19+
20+
func appending(_ queryItems: [URLQueryItem]) -> URL {
21+
guard queryItems.isEmpty == false else {
22+
return self
23+
}
24+
#if canImport(FoundationNetworking)
25+
return appending(queryItems: queryItems)
26+
#else
27+
if #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) {
28+
return appending(queryItems: queryItems)
29+
} else {
30+
return URLComponents.appending(queryItems: queryItems, to: self)
31+
}
32+
#endif
33+
}
34+
35+
mutating func append(_ queryItems: [URLQueryItem]) {
36+
guard queryItems.isEmpty == false else {
37+
return
38+
}
39+
#if canImport(FoundationNetworking)
40+
append(queryItems: queryItems)
41+
#else
42+
if #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) {
43+
append(queryItems: queryItems)
44+
} else {
45+
self = URLComponents.appending(queryItems: queryItems, to: self)
46+
}
47+
#endif
48+
}
49+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//
2+
// URLComponents.swift
3+
// HTTP
4+
//
5+
// Created by Alsey Coleman Miller on 10/1/25.
6+
//
7+
8+
import Foundation
9+
#if canImport(FoundationNetworking)
10+
import FoundationNetworking
11+
#endif
12+
13+
internal extension URLComponents {
14+
15+
static func appending(
16+
queryItems: [URLQueryItem],
17+
to url: URL
18+
) -> URL {
19+
guard queryItems.isEmpty == false else {
20+
return url
21+
}
22+
guard var components = URLComponents(string: url.absoluteString) else {
23+
assertionFailure()
24+
return url
25+
}
26+
components.queryItems = queryItems
27+
guard let newURL = components.url else {
28+
assertionFailure()
29+
return url
30+
}
31+
return newURL
32+
}
33+
}

0 commit comments

Comments
 (0)