0

I am almost finished with my GitHub Repo Search app. I would need that if users' input contained whitespace, it would be changed to + instead (as GitHub's original browser does while changing the input to the part of the URL).

How to do this?

The code is quite complicated, has many dependancies and is scattered in several files, so if possible I don't want to copy all the passages.

From the frontend side, input is handled like this:

 TextField("Enter search", text: $viewModel.query)

where viewModel is a variable that represents struct having a function that allows the screens to change based on the query.

Query itself is a Published var in that struct (Content View Model: Observable Object)

@Published var query = ""

If you need any more information, please let me know in comments. I can copy whole passages as I said but I don't know if it wouldn't complicate understanding the case further ;P

Swantewit
  • 966
  • 1
  • 7
  • 19
  • Is the question how to replace whitespace with a "+" in a Swift `String`? – jnpdx Jan 14 '22 at 20:07
  • I wonder if we can simplify this that way. Some of the strings will have whitespaces while others will not. They are passed by the user to the app, @jnpdx – Swantewit Jan 14 '22 at 20:10
  • What difference does it make? replacing it should be the same. – Leo Dabus Jan 14 '22 at 20:16
  • 2
    Note that if you are composing an URL you should be using URLQueryItem (URLComponents). No string manipulation is needed – Leo Dabus Jan 14 '22 at 20:16
  • Ok, @LeoDabus, will check it tomorrow. – Swantewit Jan 14 '22 at 21:07
  • you could try something very simple, like this: `let urlQuery = query.replacingOccurrences(of: " ", with: "+")` and use it like this: `let url = URL(string: "https://api.github.com/search/repositories?q=\(urlQuery)&per_page=20")` – workingdog support Ukraine Jan 15 '22 at 01:01

1 Answers1

0

All right, so @jnpdx and @LeoDabus were right and the easiest way in my case was to just transform the String.

I am posting the passage, that I made the transformation in (it has a pointing comment in the line):

import Foundation
import Combine

(...)
    
private func createRequest(with query: String) -> AnyPublisher<[Item], Error> {
            let fixedQuery = query.replacingOccurrences(of: " ", with: "+") //the transformation command
            guard let url = URL(string: "https://api.github.com/search/repositories?q=\(fixedQuery)&per_page=20"), !query.isEmpty else {
                return Just<[Item]>([])
                    .setFailureType(to: Error.self)
                    .eraseToAnyPublisher()
            }

I also add an URL to the more elaborative answer I have found: Any way to replace characters on Swift String?

Swantewit
  • 966
  • 1
  • 7
  • 19