Krunal
Krunal

Reputation: 79726

Swift: Add prefix (string) into a string

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?

Upvotes: 2

Views: 10952

Answers (4)

LinusG.
LinusG.

Reputation: 28952

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")

Upvotes: 9

Mark Filter
Mark Filter

Reputation: 453

I feel that this thread should be retitled to dealing more with URL String Manipulation. To return to prefixing Strings, you don't have to do this using an extension, but to use a Higher Order function (for collections)

Collections of Strings

let prefix = "Mr."
self.dataSource = myMaleFriends.map({ (friend) -> String in
    return prefix + " " + friend
})

For prefixing a single word

var name = "Anderson"

name = name.withMutableCharacters({ (name) -> String in
    return "Mr. " + name
})

Upvotes: 1

vadian
vadian

Reputation: 285140

An alternative is URLComponents. This works with or without http

var urlComponents = URLComponents(string: "//www.testhost.com/pathToImage/testimage.png")!
if urlComponents.scheme == nil { urlComponents.scheme = "http" }
let imageURLString = urlComponents.url!.absoluteString

Upvotes: 9

Jacob King
Jacob King

Reputation: 6157

There is nothing built in but you could do this in one line with a conditional assignment. See the following: imageURLString = imageURLString.hasPrefix("http:") ? imageURLString : ("http:" + imageURLString)

Upvotes: 1

Related Questions