无法将类型“ IndexPath”的值分配为类型“ Int”

时间:2019-01-18 21:51:08

标签: swift

我想知道如何声明IndexPath类型的变量。如果有人可以向我展示如何使用内联条件,这也将非常有帮助。

var indexPath = 0
if  PlaylistController.shared.playlists.count == 1 {
    indexPath = IndexPath(item: sender.tag +1, section: 0)
}
else {
    indexPath = IndexPath(item: sender.tag -1, section: 0)
}

3 个答案:

答案 0 :(得分:1)

let indexPath : IndexPath = 
    PlaylistController.shared.playlists.count == 1 ?
        IndexPath(item: sender.tag+1, section: 0) :
        IndexPath(item: sender.tag-1, section: 0)

或者,我想更清楚:

let item = PlaylistController.shared.playlists.count == 1 ? sender.tag+1 :sender.tag-1
let indexPath = IndexPath(item:item, section:0)

答案 1 :(得分:1)

只需更改行:

var indexPath = 0

收件人:

let indexPath: IndexPath

或将整个内容替换为:

let indexPath = IndexPath(item: sender.tag + (PlaylistController.shared.playlists.count == 1 ? 1 : -1), section: 0)

答案 2 :(得分:1)

只需将变量的类型指定为IndexPath,因为这是您需要存储的类型(您不想保存数字)

var indexPath: IndexPath