Instance member cannot be used on type of custom class

若如初见. 提交于 2019-12-17 05:15:28

问题


I have a classe named "whisky builder" which only initiates the new Whisky. Now i would like to add the new added whiskies in my "WhiskyOverViewController". But I face the following problem:

class WhiskyOverViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!

var whiskyArray = [WhiskyBuilder]()
let stringArray = whiskyArray.map({$0.whiskyName!})
var whiskies = [Character: [String]]()
var objectsArray = [Object]()

In the line of "stringArray" I get the error "Instance member 'whiskyArray' cannot be used on type 'WhiskyOverViewController'. Why am I not able to use the whiskyArray-variable there?

Thanks in advance for your help


回答1:


What you need there is a read only computed property:

var stringArray: [String] { 
    return whiskyArray.map{$0.whiskyName!} 
}



回答2:


You need to move this code to a function:

let stringArray = whiskyArray.map({$0.whiskyName!})



回答3:


The two types must be incompatible with each other. Just like you cannot assign a UIImage to a String, your program won't let you assign a [WhiskyBuilder] array type to a WhiskyOverViewController type. You must have declared stringArray globally, because otherwise Swift would infer its type.



来源:https://stackoverflow.com/questions/38651085/instance-member-cannot-be-used-on-type-of-custom-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!