Want to put in my variables part of String, how can I do it easily?

this is my string whaen i print it:

Optional("https://api.github.com/search/repositories?sort=stars&q=language%3A&order=desc&per_page=30&page=2; rel="next", https://api.github.com/search/repositories?sort=stars&q=language%3A&order=desc&per_page=30&page=34; rel="last"")

and i want to put inside 2 variables :
var next = "page=2"
var last = "page=34"

how can I do it easily?

I'm not really sure what you mean with put variables part of string but I guess you can do something like

var next = "page=2"
"https://api.github.com(next)"

I want to take from this string:

var str = "Optional("https://api.github.com/search/repositories?sort=stars&q=language%3A&order=desc&per_page=30& page=2 ; rel="next", https://api.github.com/search/repositories?sort=stars&q=language%3A&order=desc&per_page=30& page=34 ; rel="last"")"

but get it from the string and finelly it will be:
var next = "page=2"

If you have a URL, the best way to get query items is via URLComponents:

let s = "https://api.github.com/search/repositories?sort=stars&q=language%3A&order=desc&per_page=30&page=2"
let uc = URLComponents(string: s)!
let q = (uc.queryItems ?? []).first {
    $0.name == "page"
}!
print(q.value!)     // prints: 2

There’s lots of force unwraps there, something you’d want to fix unless you can absolutely trust the input data.

Getting a URL from the string you have is a bit tricky, primarily because it’s not clear how you got that string in the first place. Can you explain more about that?

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

2 Likes

I get the string in the link header and i can use this data to know what is the url for the next and last page,

thank you for your answer!

This would be more concise (and does less work when optimization is off):

uc.queryItems?.first