Jurian Amatsahip Jurian Amatsahip - 7 months ago 20
Swift Question

Swift equivalent of String.format and .Replace?

I have the snippet of java code.

functionReturnValue = String.format("%1$2s", jDay).replace(' ', '0') + "/" + String.format("%1$2s", i).replace(' ', '0') + "/" + dateIn.substring(0, 4);


What is the swift equivalent of this?
This is what I have so far

let string1 = String(format: "%1$2s", jDay);
let replacedString = String(string1.characters.map{$0 == " " ? "0" : $0})
let string2 = String(format: "%1$2s", i);
let replacedString2 = String(string2.characters.map{$0 == " " ? "0" : $0})
let string3 = dateIn[year];
let stringFinal = replacedString + "/" + replacedString2 + "/" + string3;

Answer

Format strings in Swift and in Java are different, so you cannot use %1$2s for your format. Also, since the call of replace in your Java code is there to add leading zeros, you could replace it with a call of format. Finally, use string interpolation to construct the final string:

let s1 = String(format: "%02d", jDay)
let s2 = String(format: "%02d", i)
let s3 = dateIn[year]
let stringFinal = "\(s1)/\(s2)/\(s3)"
Comments