2016-10-12 49 views
0

我想要将图像的名称分配给按钮。图像名称存储在一个数组中。不过我正在错误的标题Swift - 不能用索引类型为NSNumber的值类型[String]下标吗?

我的代码:

//profilePic is the button 
//friend is a coredata object received from another view. picIndex is stored as int16 in the coredata 

profilePic.setImage(UIImage(named: imgArray[friend.picIndex]), forState: UIControlState.Normal); 

我的数组:

var imgArray = ["a.jpg", "aq3d.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg", 
    "fallout.jpg", "g.jpg", "h.jpg", "i.jpg", "j.jpg", "k.jpg", "overwatch.jpg", "space.jpg"]; 
+2

OT:你鸵鸟政策需要','在斯威夫特。 –

+0

'friend.picIndex'是一个'NSNumber'吗? – rmaddy

+0

@RashwanL是的,我知道。但是我想继续使用它,因为我也会使用其他语言。它的习惯 –

回答

0

斯威夫特需要通过调用intValue在此背景下,以 “解包” NSNumber

profilePic.setImage(
    UIImage(named: imgArray[friend.picIndex.intValue]) 
, forState: UIControlState.Normal //  ^^^^^^^^^ 
) 

如果您对的类有控制权变量,考虑制作picIndexInt而不是NSNumber

0

你可以确保it's真是一个int值

if let index = Int(friend.picIndex){ 
    profilePic.setImage(UIImage(named: friend[index]), for: .normal) 
} 
else{ 
    // Not a number 
} 
相关问题