Using the split function in Swift 2

后端 未结 3 1271
野趣味
野趣味 2020-12-23 11:26

Let\'s say I want to split a string by an empty space. This code snippet works fine in Swift 1.x. It does not work in Swift 2 in Xcode 7 Beta 1.

var str = \"         


        
相关标签:
3条回答
  • 2020-12-23 11:40

    split is a method in an extension of CollectionType which, as of Swift 2, String no longer conforms to. Fortunately there are other ways to split a String:

    1. Use componentsSeparatedByString:

      "ab cd".componentsSeparatedByString(" ") // ["ab", "cd"]
      

      As pointed out by @dawg, this requires you import Foundation.

    2. Instead of calling split on a String, you could use the characters of the String. The characters property returns a String.CharacterView, which conforms to CollectionType:

      "                                                                    
    0 讨论(0)
  • 2020-12-23 11:54

    Swift 4

    let str = "Hello Bob"
    let strSplitArray = str.split(separator: " ")
    strSplitArray.first!    // "Hello"
    strSplitArray.last!     // "Bob"
    

    Xcode 7.1.1 with Swift 2.1

    let str = "Hello Bob"
    let strSplit = str.characters.split(" ")
    String(strSplit.first!)
    String(strSplit.last!)
    
    0 讨论(0)
  • 2020-12-23 11:57

    In Swift 3 componentsSeparatedByString and split is used this way.

    let splitArray = "Hello World".components(separatedBy: " ") // ["Hello", "World"]
    

    split

    let splitArray = "Hello World".characters.split(separator: " ").map(String.init) // ["Hello", "World"]
    
    0 讨论(0)
提交回复
热议问题