0

There are syntax error in it. New to Swift :(

var inputString: String = "Hello its question? </question> Oky its the answer"

let splitter: String = "</question>"
var splittedArray = [inputString .componentsSeparatedByString(splitter)]


var questionIndex = 0
var answerIndex = 0
var mQuestions = []
var mAnswers = []


for var index = 0; index < splittedArray.count; ++index {
if index % 2 == 0{
    // Question comes first
    splittedArray.append(mQuestions[questionIndex])
    questionIndex++
}else{
    // Answer comes second

 splittedArray.append(mAnswers[answerIndex])
    answerIndex++
   }
}

Error is:

An Object is not convertable to String,

at this line of code.

splittedArray.append(mQuestions[questionIndex])
1
  • An Object or AnyObject? Commented Dec 5, 2014 at 6:39

2 Answers 2

2

There are indeed syntax errors, but that's not all:

  • You can't inline Objective-C code as you're doing with [inputString.components...]
  • You can't initialize an empty array without specifying its type
  • You've got the object and the parameter reversed in your appends

Here's a quick rewrite addressing the above:

import Foundation

var inputString = "Hello its question? </question> Oky its the answer"

let splitter = "</question>"
var splittedArray = inputString.componentsSeparatedByString(splitter) as [String]

var mQuestions = [String]()
var mAnswers = [String]()

while splittedArray.count >= 2 {
    mQuestions.append(splittedArray.removeAtIndex(0))
    mAnswers.append(splittedArray.removeAtIndex(0))
}
Sign up to request clarification or add additional context in comments.

Comments

0
var splittedArray = [inputString .componentsSeparatedByString(splitter)]

Bit of an objective-c hangover here. With those square brackets, you're making this an array with an array inside it. That's going to make splittedArray have the wrong type, and the wrong contents.

Once this program compiles it will also crash, because you're then appending to splittedArray from an empty mQuestions array, using an out of bounds index.

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.