Search Your Question

Write a program to reverse string in swift

Ans : 

Using Self made function : 

func reverse(_ s: String) -> String {
       var str = ""
       //.String is just like array of characters

       for character in s.characters {
            str = "\(character)" + str
            print ( str)
       }
   return str
}

print (reverse("!pleH"))


Using Swift Direct method : 

Swift 4.0

let str = "abc"

String(str.reversed())

or 

String(str.characters.reversed())



1 comment:

  1. Revised solution of reverse string as characters that used in for loop is deprecated in 3.2 version so, let's used below solution:

    func reverse(_ s: String) -> String {
    var str = ""
    //.String is just like array of characters

    for character in s {
    str = "\(character)" + str
    print ( str)
    }
    return str
    }

    print (reverse("!pleH"))


    ReplyDelete

Thanks