Search code examples
swiftinputtransformation

Transform whitespace to + as a result of user input in Swift


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


Solution

  • 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?