簡體   English   中英

在for循環中鍵入強制轉換數組元素

[英]Type cast array elements in for loop

在委托方法中,我得到一個自定義對象類型的“結果”數組,我想循環遍歷數組元素。 我現在做以下,這是有效的

for result in results {
    if result is XYZClass {     
        //This Works!    
    }
}

有沒有辦法在for循環中輸入對象以避免寫兩行? swift允許這個嗎? 用於在Objective-C中相當容易地完成此操作

for (XYZClass *result in results) {

}

但是,我沒有在Swift中取得成功。 我試過沒有運氣的顯式演員。

for result as XYZClass in results {
    //ERROR: Expected ‘;’ in ‘for’ statements
}

for result:AGSGPParameterValue in results {
    /* ERROR: This prompts down cast as 
    for result:AGSGPParameterValue in results as AGSGPParameterValue { }
    which in turn errors again “Type XYZClass does not conform to Sequence Type”
*/
}

任何幫助表示贊賞

嘗試這個:

for result in results as [XYZClass] {
    // Do stuff to result
}

根據您使用for循環的方式,最好使用compactMap (如果您在Swift 4.1之前使用flatMap )將對象映射到新數組:

let onlyXyzResults: [XYZClass] = results.compactMap { $0 as? XYZClass }

現在只有一個數組XYZClass對象,刪除了所有其他對象類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM