Search code examples
arraysobjecttypesswift2func

Swift 2: Call a function using an object array as a parameter


Here is my code: I already have an object called "Rooms"

class BuildRooms  {
func build(room: [Rooms]){
    room[0].setExits([-1,-1,-1,-1])
}

I am trying to use it by typing:

var room: [Rooms] = []
BuildRooms.build(room)

Error occurs at BuildRooms.build(room) It says: can not convert value of type 'Rooms' to expected argument type of 'BuildRooms'

thanks


Solution

  • you tried to call function build as class / or static / function but it is declared as an instance function. I agree, that the error message which you received could be confusing, but it is correct.

    class Rooms {}
    class BuildRooms  {
        class func build(room: [Rooms]){
            print("room: \(room)")
        }
    }
    
    var room: [Rooms] = []
    BuildRooms.build(room) // room: []
    

    what did you do ... could be done this way

    class Rooms {}
    class BuildRooms  {
        func build(room: [Rooms]){
            print("room: \(room)")
        }
    }
    
    var room: [Rooms] = []
    let br = BuildRooms()
    let bf = BuildRooms.build(br) // here the parameter expected is concrete instance of BuildRooms class and returning type is ...
    print(bf.dynamicType) // Array<Rooms> -> ()
    bf(room) // room: []