2

How do we find out the length (byte-wise) of a string [declared String type, not NSString] in Swift 2.2?

I know one way out is to use _bridgeToObejectiveC().length

Is there any other way out?

Raptor
  • 51,208
  • 43
  • 217
  • 353
KawaiKx
  • 8,919
  • 18
  • 67
  • 102
  • `someString.characters.count` returns the length of the String. I think I didn't get what you're asking really. – Onur Tuna Aug 09 '16 at 06:29
  • character count and length are two different things. Swift uses unicode. In unicode, different characters take different number of bytes for storage. I wish to know 'how many bytes a string' is taking. – KawaiKx Aug 09 '16 at 06:39

4 Answers4

3
let str: String = "Hello, World"
print(str.characters.count) // 12

let str1: String = "Hello, World"
print(str1.endIndex) // 12

let str2 = "Hello, World"
NSString(string: str2).length  //12

Refer String length in Swift 1.2 and Swift 2.0 and Get the length of a String

Community
  • 1
  • 1
gurmandeep
  • 1,207
  • 1
  • 13
  • 29
3
    let str: String = "Hello, World"
    print(str.characters.count) // 12
    let byteLength = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
    print("byte lenght: \(byteLength)")//12

    let str2: String = "你好"
    print(str2.characters.count) // 2
    let byteLength2 = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
    print("byte lenght: \(byteLength2)")//12
Ethan
  • 451
  • 4
  • 13
1

Try this code:

Swift

    let test : String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let bytes : NSInteger =   test.lengthOfBytesUsingEncoding(NSUTF8StringEncoding);
    NSLog("%i bytes", bytes);

Objective C

refer this link:

What is the length in bytes of a NSString?

Community
  • 1
  • 1
Bhadresh Kathiriya
  • 2,905
  • 2
  • 19
  • 36
  • This is pretty much what KawaiKx said they're *not* interested in: The `NSString` way... – Gero Aug 09 '16 at 06:27
  • you are also use String. This isn't imported string to find bytes imported. – Bhadresh Kathiriya Aug 09 '16 at 06:31
  • Okay, now you edited your answer. I agree that it doesn't really matter, I was just pointing it out. Also, I have no clue what your comment says, sorry. – Gero Aug 09 '16 at 06:35
1

I think type casting is another easier way to use the methods, properties of NSString class.

print((str as NSString).length)
KawaiKx
  • 8,919
  • 18
  • 67
  • 102