2014-12-05 57 views
1

其中存在語法錯誤。新斯威夫特:(將元素添加到數組中的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++ 
    } 
} 

錯誤是:

對象並不可轉換爲字符串,

在這行代碼

splittedArray.append(mQuestions[questionIndex]) 
+0

一個對象或AnyObject? – 2014-12-05 06:39:33

回答

2

確有語法錯誤,但是這還不是全部:

  • 可以作爲你與[inputString.components...]
  • 做不在線Objective-C代碼你不能沒有指定初始化一個空數組其類型
  • 你有對象和參數在appends

逆轉

這裏是一個快速重寫尋址上述:

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)) 
} 
0
var splittedArray = [inputString .componentsSeparatedByString(splitter)] 

一個objective-c hango的位ver在這裏。有了這些方括號,你就可以將這個數組放在裏面。這將使splittedArray有錯誤的類型和錯誤的內容。

一旦這個程序編譯它也會崩潰,因爲你使用一個出界索引從空的mQuestions數組中追加到splittedArray