Seapoe Seapoe - 8 months ago 27
Swift Question

Swift URL String Template Equivalent to Python

I'm making url requests to a web api. I'd like to make a template URL and then use string format to pass in the parameters. In Python this is very easy. Here's an example:
Python Url Template Example

I've been trying to do the equivalent in swift but it's made difficult since they use the percent sign with their format specifiers. I tried to research but came up on confusing constructs like percent encoding. Can I accomplish this in Swift?


You can do this easily in Swift without any special string "magic" by creating a function that takes in a String and an Int then returning a String.

// Create the template function
let urlTemplate: (String, Int) -> String = { (string, number) in
    return "\(string)&page=\(number)"

// Then call it with whatever parameter (they will have to be a String and and Int though
urlTemplate("One", 1) // => ""
urlTemplate("Banana", 82) // => ""