String is the newly added type in swift, and it can be easily converted to each other with the original nsstring. But in the actual development, how should we choose?
1, the string type can be used as much as possible for the following reasons:
(1) Now all APIs in cocoa can accept and return string types, so there is no need to specifically convert.
(2) Swift's string is a struct, and the NSString class is NSObject, so string is more consistent with the character "invariant". At the same time, by using the string method, the performance will be improved without touching the unique operation and dynamic characteristics of nsstring.
(3) Because string implements an interface like CollectionType, some swift syntax features are only used by string, while NSString does not. For example, For...in's enumeration iterates through all the characters
| 1234 |
letwords = "Hangge.com"for i inwords{ print(i) //Hangge.com} |
2, to use the case of NSString
(1) string has a Hasprefix/hassuffix method to determine whether a string starts or ends, but there is no containsstring method to determine if the interior contains another string. But this method NSString, all we can do is convert string to NSString first.
| 1234 |
let words = "hangge.com " if (words as nsstring      println ( " Yes " " //yes } |
(2) string and range with the trouble, such as the following interception of the string part, respectively, converted to nsstring and then interception and direct use of string interception to do the demonstration, we can compare themselves. (This is just a bit of trouble, but it's not a big problem)
| 12345678910 |
let words = "Hangge.com"//先转换成NSStringvar rangeStr1 = (words as NSString).substringWithRange(NSMakeRange(4,2)) //ge//不转换let index = advance(words.startIndex, 4)let index2 = advance(words.startIndex, 6)var range = Range<String.Index>(start: index, end: index2)var rangeStr2 = words.substringWithRange(range) //ge |
The difference between swift-string and NSString, and the respective usage scenarios