Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift 2.0 what is the maximum length of a string?

I have an application which utilizes a single string. This string contains data loaded from an array and then the string is exported to a text file.

My question is what is the longest length possible for this string, and when does it become a problem that it is getting too long?

like image 330
Big Green Alligator Avatar asked May 15 '16 05:05

Big Green Alligator


2 Answers

Following the official Apple documentation:

String is bridged to Objective-C as NSString, and a String that originated in Objective-C may store its characters in an NSString.

Since all devices were capable of running iOS are 32 bit, this means NSUIntegerMax is 2^32.

According to Swift opensource GitHub repo It would seem that its value is 2^64 = 18,446,744,073,709,551,615 ; hexadecimal 0xFFFFFFFFFFFFFFFF for the 64 bit devices, following this code:

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif

// + (instancetype)
    //     stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
...
maxLength:(NSUInteger)maxBufferCount
...

TEST: (on iPhone 6)

enter image description here

like image 166
Alessandro Ornano Avatar answered Oct 01 '22 02:10

Alessandro Ornano


String is bridged to Objective-C as NSString, and a String that originated in Objective-C may store its characters in an NSString. Since any arbitrary subclass of NSString can become a String, there are no guarantees about representation or efficiency in this case.

What is the maximum length of an NSString object?

The hard limit for NSString would be NSUIntegerMax characters. NSUIntegerMax is 2^32 - 1 and NSString can hold a little over 4.2 billion characters.

According comments: for iPhone 5S and above since they are 64 Bit. It's 2^(64 - 1)

like image 24
phnmnn Avatar answered Oct 01 '22 02:10

phnmnn