I'm looking for a String function that adds prefix string into an existing string.
The problem I've is: Sometimes, I get a URL string from web service response without keyword http:.
The general form of URL (URL string) should be: http://www.testhost.com/pathToImage/testimage.png
But sometimes I get //www.testhost.com/pathToImage/testimage.png from web service.
Now, I know that I can check, whether prefix http: is there in a string or not, but if there isn't then I need to add prefix into an existing URL string.
Is there any String (or substring or string manipulation) function that adds prefix into my URL string?
I tried into Apple document: String but couldn't find any help.
An alternate way I have is a concatenation of string.
Here is my code:
var imageURLString = "//www.testhost.com/pathToImage/testimage.png"
if !imageURLString.hasPrefix("http:") {
imageURLString = "http:\(imageURLString)" // or "http:"+ imageURLString
}
print(imageURLString)
But is there any standard way or iOS String default function that I can use here?
If "http:" + "example.com" doesn't suit you, you could write your own extension that does this:
extension String {
mutating func add(prefix: String) {
self = prefix + self
}
}
...or make it test the string before adding the prefix, to add it only if it doesn't exist yet:
extension String {
/**
Adds a given prefix to self, if the prefix itself, or another required prefix does not yet exist in self.
Omit `requiredPrefix` to check for the prefix itself.
*/
mutating func addPrefixIfNeeded(_ prefix: String, requiredPrefix: String? = nil) {
guard !self.hasPrefix(requiredPrefix ?? prefix) else { return }
self = prefix + self
}
}
Usage:
// method 1
url.add(prefix: "http:")
// method 2: adds 'http:', if 'http:' is not a prefix
url.addPrefixIfNeeded("http:")
// method 2.2: adds 'http:', if 'http' is not a prefix (note the missing colon which includes to detection of 'https:'
url.addPrefixIfNeeded("http:", requiredPrefix: "http")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With