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

Swift: Add prefix (string) into a string

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

我遇到的问题是:有时,我从没有关键字 http:[=40= 的 Web 服务响应中得到一个 URL 字符串].

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

但有时我 //www.testhost.com/pathToImage/testimage.png 来自网络服务。

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

是否有任何字符串(或子字符串或字符串操作)函数可以将前缀添加到我的 URL 字符串中?

我尝试查看 Apple 文档:String 但找不到任何帮助。

我的另一种方法是串联字符串。

这是我的代码:

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

if !imageURLString.hasPrefix("http:") {
   imageURLString = "http:\(imageURLString)"  // or  "http:"+ imageURLString
}
print(imageURLString)

但是我可以在这里使用任何标准方法或 iOS 字符串默认函数吗?

没有内置任何内容,但您可以使用条件赋值在一行中完成此操作。请参阅以下内容: imageURLString = imageURLString.hasPrefix("http:") ? imageURLString : ("http:" + imageURLString)

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

extension String {
    mutating func add(prefix: String) {
        self = prefix + self
    }
}

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

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
    }
}

用法:

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

另一种选择是 URLComponents。这适用于或不适用 http

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

我觉得应该将此线程重新命名为更多地处理 URL 字符串操作。要 return 为字符串添加前缀,您不必使用扩展来执行此操作,而是使用高阶函数(对于集合)

字符串集合

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

为单个单词添加前缀

var name = "Anderson"

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