1

I am using the SwiftSocket library and I am trying to convert the data the UDP socket receives from type 'UInt8?, String, Int' to type String.

    let data = client.recv(1024)
    let string = NSData.withBytes(data)
    let str = NSString(data: string, encoding: NSUTF8StringEncoding) as String?

When I attempt this I get the following error:

Cannot convert value of type '((UInt8]?,String,Int)' (aka'(Optional>, String, Int)') to be expected argument type '[UInt8'

If I print out 'data', i receive the following:

(Optional([104, 101, 108, 108, 111]), "127.0.0.1", 34835)

Where 104,101,108,108,111 is the string "hello".

Is there way to convert the data read to string?

8
  • stackoverflow.com/questions/24196820/… Commented Nov 19, 2015 at 0:15
  • You have to cast it to an UInt8 Array. Commented Nov 19, 2015 at 0:17
  • in the link you posted, the answer says: var endMarker = NSData(bytes: [0xFF, 0xD9] as [UInt8], length: 2). What are FF and D9? Can you show me an example? Commented Nov 19, 2015 at 0:19
  • How would you like that data represented as a string? Commented Nov 19, 2015 at 0:30
  • in the code I gave above, I would have expected the variable str to be 'hello' Commented Nov 19, 2015 at 0:31

1 Answer 1

0

Your approach is right, but you forgot to get the data from the received object. It's data.0.

    let receivedData:([UInt8], String, Int) = ([104, 101, 108, 108, 111], "", 0)
    let data = NSData(bytes: receivedData.0, length: receivedData.0.count)
    let str = NSString(data: data, encoding: NSUTF8StringEncoding) as! String

    print(str)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.