Differences between NSString and SwiftString and nsstringstring

Source: Internet
Author: User

Differences between NSString and SwiftString and nsstringstring

Now there are more and more Swift projects, and you may often see str as NSString or str as String switching between the two, because some operations are more convenient with the OC String, on the contrary, mastering the characteristics of these two strings will certainly benefit the development of the project. This article is your own understanding and draws on the official documentation. If you have any understanding of the deviation, please give us some advice.

If you did not see this article in Dong Boran's blog, click to view the original article.


First, let's talk about the commonalities, that is, String retains most NSString APIs, such

. HasPrefix

. LowercaseString

. ComponentsSeparatedByString

. SubstringWithRange, etc.

Therefore, many common operations can be used in development. The difference is described below.


NSString is a reference type. SwiftString is a value type.
        var nsString:NSString = NSString()        var swiftString:String = String()                var nsString:NSString = "dsx"        var swiftString:String = "dsx"

Both of them can be initialized directly using their own class names. The following method is also initialization. Although the same writing method is used, NSString indicates initializing a pointer pointing to this string, but SwiftString means to assign the string literal value to the variable.


It is easier to splice SwiftString than NSString.

NSString needs to use append or stringWithFormat to splice two strings

        NSString *strA = @"My name";        NSString *strB = @" is dsx";        strA = [strA stringByAppendingString:strB];

SwiftString only needs to use "+ ".

        var strA = "My name"        var strB = " is dsx"        strA = "My name" + " is dsx"        strA = strA + strB        println(strA)

The syntax at the beginning of swift allows "+" to be directly spliced between strings and characters, but swift1.2 cannot be used in the future. Strings and characters can only be connected with append.


SwiftString can be used to traverse strings.

SwiftString can be used to traverse and output all characters inside a string. This is not what NSString can do, because the former inherits the CollectionType protocol (this protocol is no longer inherited after swift2, use the characters attribute to provide a character set)

        // swift1.2        for charater in "My name is dsx" {            println(charater)        }                // swift2.0        for character in "My name is dsx".characters {            print(character)        }

Swift strings are more like a product of a combination of multiple character elements into a sequence, such as but not a collection class; if we add as NSString after "This is a book", the following error is returned:

Type 'nsstring' does not conform to protocol 'sequencetype'

Writing as String after swift2.0 will also report the above error. 2.0 will sink the SequenceType and CollectionType protocols inherited from the original String to the String. characterView to inherit, I feel that Apple is doing this to reduce resource waste.


The method for calculating the string length of SwiftString is different from that of NSString.
Var strA: String = "mcdream" var strB: NSString = "mcdream" print (strA. lengthOfBytesUsingEncoding (NSUTF8StringEncoding) // 5 print (strA. characters. count) // 3 print (strB. length); // 3

NSString directly uses the String. length to obtain the length of the String, but the String. length can only be knocked out. lengthOfBytesUsingEncoding (NSUTF8StringEncoding). Therefore, the storage space of Chinese characters is three times that of English characters. Swift's real method similar to. lengh is to retrieve the characters attribute (array) And then. count


The method for comparing SwiftString to string is different from that for NSString.
        let strA:NSString = ""        let strB:NSString = ""        let strC:NSString = "dsx"        let strD:NSString = "dsx"                if(strA.isEqualToString(strB as String)){            print("yes");        }                if (strC == strD){            print("yes");        }

NSString has a method isEqualToString to determine whether two strings are completely equal. String does not have this method, but because String is a value type, you can use = to determine whether it is completely equal.


NSString can be converted in the same way as the basic data type.
        var strA:NSString = "12306"        var strB:NSString = "0.618"                var numOfInt = strA.integerValue;        var numOfDouble = strB.doubleValue;

This function is not available in Swift. Therefore, it is easier to use NSString for json parsing or dictionary-to-model conversion.


The SwiftString attribute can be used to determine whether the string is null.
        var emptyStr = ""        if emptyStr.isEmpty {            print("It is empty")        }

This is also a unique property of swiftString. (Dong Boran) Generally, NSString needs to check whether the value of. length is greater than 0 to determine whether the string is null. An error is returned when you determine whether the NSString = nil method is disabled.

Binary operator '= 'could not be applied to operands of type 'nsstring' and 'illiteralconvertible'


Unique Character String insertion function of SwiftString
        var strA:String = "My name is dx"        strA.insert("s", atIndex: strA.characters.indexOf("x")!);        print(strA) // My name is dsx

This method can only insert a single Character and Cannot insert a String. If it is written as "ss", the error Cannot convert value of type 'string' to expected argument type 'character 'will be reported'

If you did not see this article in Dong Boran's blog, click to view the original article.

NSString is a pointer that cannot perform this operation. In addition, String also has the subStringFromIndex or ToIndex function of NSString.



The overall function of String is more powerful than NSString. After all, regular army in Swift syntax. There are many differences between the two. Even functions you don't have are all value type and reference type. Some attributes are extended after swift2.0, which greatly changes the calling methods of many methods of String. There are also some differences in the process of exploration. I hope this article will be helpful to the readers. repost must be indicated by the repost and original article links.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.