Bash to Swift

If this in the code in Bash ...

printf "username:password" | iconv -t ISO-8859-1 | base64 -i -

What would this be in Swift?

Something like this?

import Foundation

let str = "username:password"
let converted = str.data(using: .isoLatin1, allowLossyConversion: false)
let base64 = converted!.base64EncodedData()
let base64String = String(data: base64, encoding: .utf8)!
print(base64String)
4 Likes
let base64 = converted!.base64EncodedData()

While I’m a big fan of force unwrapping in general, in this case I think that it’d be best to test for and then handle this optional. ISO-Latin-1 only covers a tiny fraction of Unicode space; if the string contains a character that’s not representable in that encoding, this force unwrap will crash )-:

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

3 Likes

@eskimo Agreed in general, but assuming this is replacing a "quick and dirty" bash script that does also not accommodate for this, a crash (and non-zero exit code) may be desirable if the given output is not as possible.

Fair enough, but if that’s the goal then I’d suggest this:

let converted = str.data(using: .isoLatin1, allowLossyConversion: false)!
let base64 = converted.base64EncodedData()

I prefer to deal with the optional at the point of creation, rather than let it ‘infect’ the rest of my code.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

5 Likes
Terms of Service

Privacy Policy

Cookie Policy