Can someone translate this code from java to swift or explain how it should look like in Swift (SHORT CODE) | Sololearn: Learn to code for FREE!

+1

Can someone translate this code from java to swift or explain how it should look like in Swift (SHORT CODE)

import java.util.Scanner; public class RunLengthEncoding { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter input string: "); String s = input.nextLine(); for (int a = 0; a < s.length(); a++) { if ((s.charAt(a) < 'A' || s.charAt(a) > 'Z')) { System.out.print("Bad input"); System.exit(0); } } System.out.print("Enter flag character: "); char flag = input.nextLine().charAt(0); if (flag == '#' || flag == '$' || flag == '*' || flag == '&') { int count = 0; for (int i = 1; i < s.length(); i++) { if(s.charAt(i)==s.charAt(i-1)); count++; if (count == 1) System.out.print(s.charAt(i)); if (count == 2) System.out.print(s.charAt(i) + s.charAt(i)); if (count == 3) System.out.print(s.charAt(i) + s.charAt(i) + s.charAt(i)); else System.out.print(flag + s.charAt(i) + (count + 1)); } } else System.out.print("Bad input"); } }

4/10/2021 10:46:46 PM

Dzondzula

3 Answers

New Answer

+1

Yes, you can: 1) Complete the Swift course here in Sololearn. 2) Use Google/Bing to search to find answers to questions like 'if statement in Swift' I found it hard to find information on input is Swift so I will give you a head start: var message = readLine()! let sales = Int(readLine()!)!

+1

The answer above me is correct however I can’t stress this enough: Force-unwrapping is Unsafe. Apple suggests you use more safe unwrapping techniques such as “if let” and “guard let” For example “guard let message = readLine() else { return }” Thanks.

+1

I agree with Pawel Zabinski on this point. Here, on these small codes, in the Sololearn playground, is one thing. But real world robust error handling is the proper way to write production code.