How to prepend url with http:// using stringWithFormat in Swift

前端 未结 3 1515
北恋
北恋 2020-12-17 09:12

I\'m building a custom browser using UIWebView.

Use case: User enters \"www.abc.com\" into the address bar. Error below thrown:

Error Domain=WebKitErrorDom         


        
相关标签:
3条回答
  • 2020-12-17 09:20

    The equivalent of NSString's formatWithString: is just "format:", as shown below, but there is no real need to do that for the example you have given. Just append strings, or use interpolation...

    let urlString = "www.abc.com"
    var modifiedURLString = NSString(format:"http://%@", urlString) as String
    // or just
    modifiedURLString = String(format:"http://%@", urlString)
    // or
    let simpler = "http://" + urlString
    // or use string interplotaion
    let simplest = "http://\(urlString)"
    
    0 讨论(0)
  • 2020-12-17 09:37

    Just for the sake of being complete here (though of a 4th way), here are your options:

    1: Swift way of using NSString's stringWithFormat:

    let url = NSString(format: "http://%@", aSuffix)
    

    2: Take advantage of Swift's ability concatenate strings with the "+" operator.

    let url = "http://" + aSuffix
    

    3: Use NSString's stringByAppendingString() method.

    let url = "http://"
    url.stringByAppendingString(aSuffix)
    

    4: String interpolation.

    let url = "http://\(aSuffix)"
    
    0 讨论(0)
  • 2020-12-17 09:44

    You can use string interpolation:

    let site = "www.abc.com"
    let url = "http://\(site)"
    
    0 讨论(0)
提交回复
热议问题