scinfu scinfu - 2 months ago 27
Swift Question

Swift decode and encode string

I'm trying to encode and decode strings and data with Swift.
In Java it's relatively simple , i can use

Charset
CharsetDecoder
CharsetEncoder
like in the below snippet code .
I think the solution is to use
String.Encoding
but how?

public static void Test() throws CharacterCodingException {
Charset charset = Charset.forName("UTF-8");
CharsetDecoder chdecoder = charset.newDecoder();
CharsetEncoder chencoder = charset.newEncoder();
String s = "Encode and Decode Example.";
if(!chencoder.canEncode((char) 9)) return;//not here but i need this method
ByteBuffer byteBuffer= ByteBuffer.wrap(s.getBytes());
CharBuffer charBuffer = chdecoder.decode(byteBuffer);
ByteBuffer newByteBuff = chencoder.encode(charBuffer);
while(newByteBuff.hasRemaining()){
char ch = (char) newByteBuff.get();
System.out.print(ch);
}
newByteBuff.clear();
}

Answer
let str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
if let base64Encoded =      utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) 
{
println("Encoded:  \(base64Encoded)")
if let base64Decoded = NSData(base64EncodedString: base64Encoded, options:   NSDataBase64DecodingOptions(rawValue: 0))
                      .map({ NSString(data: $0, encoding: NSUTF8StringEncoding) })
{
    // Convert back to a string
    println("Decoded:  \(base64Decoded)")
}
}