-6

I am trying to re-write the C# code which i have wrote previously to Swift.

public static string Right( string value, int length)
{
    if (String.IsNullOrEmpty(value)) return string.Empty;
    return value.Length <= length ? value : value.Substring(value.Length - length);
}

I am not able to write if statement effectively in swift.

pacification
  • 5,838
  • 4
  • 29
  • 51
John
  • 31
  • 5

3 Answers3

1

In Swift you can write,

func right(value: String, length: Int) -> String {
    if value.count <= length {
        return value
    } else {
        let index = value.index(value.startIndex, offsetBy: value.count-length)
        return String(value[..<index])
    }
}

There is no need to check for empty string. It will be covered in the else condition itself.

Example:

right(value: "abcdefgh", length: 3) //abcde
PGDev
  • 23,751
  • 6
  • 34
  • 88
1

It can be done as simple as that:

func right(value: String, length: Int) -> String {
    guard value.count > length, length > 0 else { return value }
    return String(
        value.dropLast(length) // we just drop `length` number of elements from the end
    )
}
user28434'mstep
  • 6,290
  • 2
  • 20
  • 35
0

Using prefix and ?: as a one-liner

func right(value: String, length: Int) -> String {
    return value.count > length ? String(value.prefix(value.count - length)) : value
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52