2016-03-01 81 views
2
print(itemToRefresh) 
print(cell.item!.id) 

if (itemToRefresh == cell.item!.id) { 
    print("MATCHED") 
} 

輸出:迅速字符串比較工作不正常

Optional("PI096") 
Optional("PI096") 

「匹配」 不打印它。爲什麼?

+0

是數據類型itemToRefresh和cell.item!.ID是一樣的嗎? –

回答

0

itemToRefresh是一個字符串,但事實證明,較早在我的代碼我已經指派它像這樣:

讓itemToRefresh =「\(富)」

應該已經

讓利itemToRefresh = 「\(foo的!)」

0

它應該已經讓itemToRefresh = 「(FOO!)」 爲如

let foo: String? = "ABC" 

let itemToRefresh = "\(foo!)" // will be -> ABC 
// let itemToRefresh = "\(foo)" // will be -> optional(ABC) 
// and optional(ABC) will not be equal to ABC 

let itemb = "ABC" 

print(itemToRefresh) // ABC 
print(itemb)  // ABC 

if itemToRefresh == itemb { // true 
    print("123") // print 123 
} 

,如果你願意,你可以放心地解開可選值,並檢查

if (foo != nil) { 

    let itemToRefresh = "\(foo!)" // will be -> ABC 
    // let itemToRefresh = "\(foo)" // will be -> "optional(ABC)" 

    let itemb = "ABC" 

    print(itemToRefresh) 
    print(itemb) 

    if itemToRefresh == itemb { 
    print("123") 
    } 
}