2

Pardon me as I am a newbie on this language.

Edit: Is there a way to reverse the position of a array element?

I am trying to create a function that test the given input if its a palindrome or not. I'm trying to avoid using functions using reversed()

let word = ["T","E","S","T"]
var temp = [String]()
let index_count = 3

for words in word{
    var text:String = words
    print(text)
    temp.insert(text, atIndex:index_count)
    index_count = index_count - 1
}
12
  • Could you give an example input and the output you wish to get? Commented Aug 17, 2016 at 20:16
  • word = ["T","E","S","T"] expected output temp = ["T","S","E","T"] Commented Aug 17, 2016 at 20:17
  • So you want to swap chars? Commented Aug 17, 2016 at 20:18
  • 2
    Okay hold up, none of this is making sense. 1) word is actually an Array<String>, and not String, words is a String 2) index_count is being mutated despite being a let constanty, 3) Swapping those letters has nothing to do with appending. OP, could you please clarify exactly what you wish to do? Commented Aug 17, 2016 at 20:22
  • 1
    So please update your question. Right know is impossible to find out what you mean ;) Commented Aug 17, 2016 at 20:26

8 Answers 8

6

Your approach can be used to reverse an array. But you have to insert each element of the original array at the start position of the destination array (moving the other elements to the end):

// Swift 2.2:
let word = ["T", "E", "S", "T"]
var reversed = [String]()
for char in word {
    reversed.insert(char, atIndex: 0)
}
print(reversed) // ["T", "S", "E", "T"]

// Swift 3:
let word = ["T", "E", "S", "T"]
var reversed = [String]()
for char in word {
    reversed.insert(char, at: 0)
}
print(reversed) // ["T", "S", "E", "T"]

The same can be done on the characters of a string directly:

// Swift 2.2:
let word = "TEST"
var reversed = ""
for char in word.characters {
    reversed.insert(char, atIndex: reversed.startIndex)
}
print(reversed) // "TSET"

// Swift 3:
let word = "TEST"
var reversed = ""
for char in word.characters {
    reversed.insert(char, at: reversed.startIndex)
}
print(reversed)
Sign up to request clarification or add additional context in comments.

4 Comments

This error shows up for: ERROR at line 4, col 20: incorrect argument label in call (have ':atIndex:', expected ':at:') reversed.insert(char, atIndex: 0) ^ ~~~~~~~ atme. swiftlang.ng.bluemix.net/#/repl/57b4cc908a6856ae58be653a
@JioM.: My code was Swift 2.2. Updated for Swift 3 now.
May I ask why atIndex was removed on Swift 3.0?
@JioM.: It was renamed to insert(_, at:). At lot changed with Swift 3. See github.com/apple/swift-evolution, in particular swift.org/documentation/api-design-guidelines.
2

Swift 5

extension String {
    func invert() -> String {
        var word = [Character]()
        for char in self {
            word.insert(char, at: 0)
        }
        return String(word)
    }
}
var anadrome = "god"
anadrome.invert()

// "dog"

Comments

0

Here's my solution:

extension String {
    func customReverse() -> String {
        var chars = Array(self)
        let count = chars.count

        for i in 0 ..< count/2 {
            chars.swapAt(i, count - 1 - i)
        }

        return String(chars)
    }
}

let input = "abcdef"
let output = input.customReverse()
print(output)

You can try it here.

1 Comment

i have updated answer to latest swift
0
func reverse(_ str: String) -> String {

    let arr = Array(str) // turn the string into an array of all of the letters

    let reversed = ""

    for char in arr {

        reversed.insert(char, at: reversed.startIndex)
    }

    return reversed
}

To use it:

let word = "hola"

let wordReversed = reverse(word)

print(wordReversed) // prints aloh

Comments

-1

Another solution for reversing:

var original : String = "Test"
var reversed : String = ""
var c = original.characters
for _ in 0..<c.count{
    reversed.append(c.popLast()!)
}

It simply appends each element of the old string that is popped, starting at the last element and working towards the first

Comments

-1

Solution 1

let word = "aabbaa"

let chars = word.characters
let half = chars.count / 2
let leftSide = Array(chars)[0..<half]
let rightSide = Array(chars.reverse())[0..<half]
let palindrome = leftSide == rightSide

Solution 2

var palindrome = true
let chars = Array(word.characters)
for i in 0 ..< (chars.count / 2) {
    if chars[i] != chars[chars.count - 1 - i] {
        palindrome = false
        break
    }
}
print(palindrome)

Comments

-1
 static func reverseString(str : String) {
        var data = Array(str)
        var i = 0// initial
        var j = data.count // final
        //either j or i for while , data.count/2 buz only half we need check
        while j != data.count/2  {
            print("befor i:\(i) j:\(j)" )
            j = j-1 
            data.swapAt(i, j) //  swapAt API avalible only for array in swift
            i = i+1 
        }
        print(String(data))
    }

Comments

-1
    //Reverse String
    
    let str = "Hello World"
    
    var reverseStr = ""

    for char in Array(str) {
        
        print(char)
        
        reverseStr.insert(char, at: str.startIndex)

    }

    print(reverseStr)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.