加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – component(separatedBy :)与.split(separator :)

发布时间:2020-12-14 04:43:13 所属栏目:百科 来源:网络整理
导读:在 Swift 4中,新方法.split(separator :)由apple在String struct中引入.所以要用一个更快的空格来分割一个字符串,例如.. let str = "My name is Sudhir"str.components(separatedBy: " ")//or str.split(separator: " ") 解决方法 我已经使用以下代码进行了
在 Swift 4中,新方法.split(separator :)由apple在String struct中引入.所以要用一个更快的空格来分割一个字符串,例如..

let str = "My name is Sudhir"

str.components(separatedBy: " ")

//or 

str.split(separator: " ")

解决方法

我已经使用以下代码进行了样本测试.

var str = """
                One of those refinements is to the String API,which has been made a lot easier to use (while also gaining power) in Swift 4. In past versions of Swift,the String API was often brought up as an example of how Swift sometimes goes too far in favoring correctness over ease of use,with its cumbersome way of handling characters and substrings. This week,let’s take a look at how it is to work with strings in Swift 4,and how we can take advantage of the new,improved API in various situations. Sometimes we have longer,static strings in our apps or scripts that span multiple lines. Before Swift 4,we had to do something like inline n across the string,add an appendOnNewLine() method through an extension on String or - in the case of scripting - make multiple print() calls to add newlines to a long output. For example,here is how TestDrive’s printHelp() function (which is used to print usage instructions for the script) looks like in Swift 3  One of those refinements is to the String API,here is how TestDrive’s printHelp() function (which is used to print usage instructions for the script) looks like in Swift 3
          """

    var newString = String()

    for _ in 1..<9999 {
        newString.append(str)
    }

    var methodStart = Date()

 _  = newString.components(separatedBy: " ")
    print("Execution time Separated By: (Date().timeIntervalSince(methodStart))")

    methodStart = Date()
    _ = newString.split(separator: " ")
    print("Execution time Split By: (Date().timeIntervalSince(methodStart))")

我在iPhone6上运行上面的代码,结果如下

执行时间分隔:8.27463299036026
?执行时间拆分:4.06880903244019

结论:split(separator :)比组件(separatedBy :)更快.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读