Swift:在字符串中添加前缀(字符串)

Kru*_*nal 0 string url prefix ios swift

我正在寻找一个String将前缀字符串添加到现有字符串中的函数.

问题我是:有时候,我从没有关键字http的 Web服务响应中获取url字符串.

URL的一般形式(url字符串)应为:http://www.testhost.com/pathToImage/testimage.png

但有时我会//www.testhost.com/pathToImage/testimage.png从网络服务中获得.

现在,我知道我可以检查http:字符串中是否有前缀,但如果没有,那么我需要在现有的url字符串中添加前缀.

是否有任何String(或子字符串或字符串操作)函数在我的url字符串中添加前缀?

我试过Apple文档:String但找不到任何帮助.

我有另一种方法是连接字符串.

这是我的代码:

var imageURLString = "//www.testhost.com/pathToImage/testimage.png"

if !imageURLString.hasPrefix("http:") {
   imageURLString = "http:\(imageURLString)"  // or  "http:"+ imageURLString
}
print(imageURLString)
Run Code Online (Sandbox Code Playgroud)

但是我可以在这里使用任何标准方式或iOS String默认功能吗?

vad*_*ian 7

另一种选择是URLComponents.无论是否有效都有效http

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

  • 打算提出类似的东西:) - 也许检查`如果urlComponents.scheme == nil ...`以便保留现有的方案. (2认同)

Lin*_*rth 6

如果"http:" + "example.com"不适合您,您可以编写自己的扩展来执行此操作:

extension String {
    mutating func add(prefix: String) {
        self = prefix + self
    }
}
Run Code Online (Sandbox Code Playgroud)

...或者在添加前缀之前测试字符串,只有在它不存在时添加它:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

// 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")
Run Code Online (Sandbox Code Playgroud)