Swift - which types to use? NSString or String

后端 未结 9 989
死守一世寂寞
死守一世寂寞 2020-12-23 00:06

With the introduction of Swift I\'ve been trying to get my head round the new language

I\'m an iOS developer and would use types such as NSString, NSInteger, N

相关标签:
9条回答
  • 2020-12-23 00:56

    String and NSString are interchangeable, so it doesn't really matter which one you use. You can always cast between the two, using

    let s = "hello" as NSString
    

    or even

    let s: NSString  = "hello"
    

    NSInteger is just an alias for an int or a long (depending on the architecture), so I'd just use Int.

    NSDictionary is a different matter, since Dictionary is a completely separate implementation.

    In general I'd stick to swift types whenever possibile and you can always convert between the two at need, using the bridgeToObjectiveC() method provided by swift classes.

    0 讨论(0)
  • 2020-12-23 00:57

    NSString : Creates objects that resides in heap and always passed by reference.

    String: Its a value type whenever we pass it , its passed by value. like Struct and Enum, String itself a Struct in Swift.

    public struct String {
     // string implementation 
    }
    

    But copy is not created when you pass. It creates copy when you first mutate it.

    String is automatically bridged to Objective-C as NSString. If the Swift Standard Library does not have, you need import the Foundation framework to get access to methods defined by NSString.

    Swift String is very powerful it has plethora of inbuilt functions.

    Initialisation on String:

    var emptyString = ""             // Empty (Mutable)
    let anotherString = String()     // empty String immutable    
    let a = String(false)           // from boolean: "false"
    let d = String(5.999)           //  "    Double "5.99"
    let e = String(555)             //  "     Int "555"
    // New in Swift 4.2 
    let hexString = String(278, radix: 18, uppercase: true) // "F8"
    

    create String from repeating values:

     let repeatingString = String(repeating:"123", count:2) // "123123"
    

    In Swift 4 -> Strings Are Collection Of Characters:

    Now String is capable of performing all operations which anyone can perform on Collection type.

    For more information please refer apple documents.

    0 讨论(0)
  • 2020-12-23 01:01

    String is a struct

    // in Swift Module

    public struct String

    {

    }

    NSString is a class

    // in Foundation Module

    open class NSString : NSObject

    {

    }

    0 讨论(0)
提交回复
热议问题