2014-12-13 42 views
0

嘗試將客觀C轉換爲swift令人非常沮喪。我有以下代碼適用於目標c。展開Plist並查找對象

NSMutableArray *path = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sequence List" ofType:@"plist"]]; 

//Shuffle the array of questions 
numberSequenceList = [self shuffleArray:path]; 

currentQuestion = currentQuestion + 1; 

if (Round==1) { 
    //Take first object in shuffled array as the first question 
    NSMutableArray *firstQuestion = [[NSMutableArray alloc] initWithArray:[numberSequenceList objectAtIndex:0]]; 

    //Find question and populate text view 
    NSString *string = [firstQuestion objectAtIndex:0]; 

    self.lblNumber.text = string; 

    //Find and store the answer 
    NSString *findAnswer = [firstQuestion objectAtIndex:1]; 

    Answer = [findAnswer intValue]; 
} 

但我似乎無法得到這個迅速工作。我可以用

var path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist") 

拉出plist中的內容,但我看不到有一個相當於objectAtIndex在迅速。如果我嘗試以下,我會收到一條錯誤消息,建議「字符串沒有名爲subscript的成員」,這顯然意味着我需要展開路徑。

let firstQuestion = path[0] 

回答

0

您正在調用的方法(如NSBundle.mainBundle().pathForResource)會返回可選項,因爲它們可能會失敗。在Objective-C中,該失敗由nil表示,而Swift使用可選項。

所以在你的例子:

var path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist") 

pathOptional<String>型(或String?)的,而不是String類型。 Optional<String>沒有下標方法(即不支持[ ])。要使用字符串中,你必須檢查是否包含可選的值(即調用pathForResource成功):

// the if let syntax checks if the optional contains a valid 
if let path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist」) { 
    // use path, which will now be of type String 
} 
else { 
    // deal with pathForResource failing 
} 

你可以閱讀更多關於引進the Swift book選配。

+0

嗨,感謝您的解釋。然而,當我嘗試使用if函數時,我現在得到一條消息,建議「下標不可用:不能用int下標字符串」。我如何使用字符串中的第一個對象? – user1759949 2014-12-13 13:20:01

+0

'first(mystring)'(它再次返回可選字符串,因爲字符串可能爲空)。或'mystring [mystring.startIndex]' - 字符串不是整數索引,因爲它們不能保證是隨機訪問的(因爲某些字符可以是不同的字節長度) – 2014-12-13 13:21:29

0

您尚未翻譯Objective-C的整個第一行。您錯過了從文件內容創建數組的NSMutableArray的調用。原始代碼很混亂,因爲它實際上是問題時調用文件path的內容。試試這個:

if let path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist") { 
    let questions = NSMutableArray(contentsOfFile: path) 

    //Shuffle the array of questions 
    numberSequenceList = self.shuffleArray(questions) 

    currentQuestion = currentQuestion + 1 

    if Round == 1 { 
     //Take first object in shuffled array as the first question 
     let firstQuestion = numberSequenceList[0] as NSArray 

     //Find question and populate text view 
     let string = firstQuestion[0] as NSString 

     self.lblNumber.text = string 

     //Find and store the answer 
     let findAnswer = firstQuestion[1] as NSString 

     Answer = findAnswer.intValue 
    } 
}