Using the split function in Swift 2

后端 未结 3 1273
野趣味
野趣味 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:

      "

提交回复
热议问题