私はswiftの初心者で、この問題を数時間試しています。以下、私のコードです。
/* [1] error in this line */if filteredCustomReqList != nil {
for i in 0..<filteredCustomReqList?.count {
tempObj = filteredCustomReqList[i] as! [AnyHashable: Any]
bezeichString = tempObj?["bezeich"] as! String
specialRequestLabel.text = ("\(filteredString), \(bezeichString!)")
print (bezeichString!)
}
}
というエラーが出ました。
binary operator cannot be applied to operands of type int and int?
ここで、:
var filteredCustomReqList: [Any]? /* = [Any]() */
もし私が var filteredCustomReqList:[Any] = [Any]()
を使用すると、エラーはなくなりますが、私の if 条件は常に真になります。どうすればこの問題を解決できますか?私はこのを読みましたが、それは私の場合(その int
と CGFloat
)と同じではありません。
どんな回答や提案でも構いませんので、よろしくお願いします。ありがとうございました。
Optional Binding の if let
を使って、Optional 変数 filteredCustomReqList
をアンラップすることができます。
var filteredCustomReqList: [Any]?
if let filteredCustomReqList = filteredCustomReqList {
for i in 0..<filteredCustomReqList.count {
tempObj = filteredCustomReqList[i] as! [AnyHashable: Any]
bezeichString = tempObj?["bezeich"] as! String
specialRequestLabel.text = ("\(filteredString), \(bezeichString!)")
print (bezeichString!)
}
}
オプションバインディングを使うべきで、for
の行にオプションがないようにします。
if let list = filteredCustomReqList {
for i in 0..<list.count {
}
}
さらに良いのは、より良い for
ループを使用することです。
if let list = filteredCustomReqList {
for tempObj in list {
bezeichString = tempObj["bezeich"] as! String
}
}
しかし、これを行うには、filteredCustomReqList
を適切に宣言します。
var filteredCustomReqList: [[String: Any]]?
これは、String
をキーとし、Any
を値とする辞書を含む配列となる。
この線は怪しげですね。
for i in 0..<filteredCustomReqList?.count {
特に、filteredCustomReqList?.count
はオプショナルチェーンにより、 Int?
型 (Int
はオプショナル) になっています。つまり、配列 filteredCustomReqList
が non-nil の場合、その count
プロパティの値 (つまり要素数) が返されます。しかし、もし filteredCustomReqList
が nil
であれば、それは伝播して filteredCustomReqList?.count
も nil
になります。
両方の可能性を包含するために、Swift はオプションの型である Int?
(有効な Int
値と nil
の両方を表すことができます) を使用します。
これは Int
と 等価 ではないので、2つの Int
を表す式 (for
ループの範囲など) では 使用できません。
int?` を for ループの範囲の上限にすることはできません。ループする前に、配列をアンラップ**する必要があります。
if let count = filteredCustomReqList?.count {
// count is of type "Int", not "Int?"
for i in 0..<count {
// etc.