简体   繁体   中英

Difference between (Type) and Type

Currently, I'm writing a class and protocol named Control and Controllable .

Control must conform to Controllable .

Control will have an array of other Controllable s as a stack. Every time before adding Controllable to the stack, I should check whether the stack contains that element. If yes, move the element to the top of stack.

Okay. VERSION_1:

import Foundation

protocol Controllable: Equatable {
}

func ==<T: Controllable>(lhs: T, rhs: T) -> Bool {
    return ObjectIdentifier(lhs).uintValue == ObjectIdentifier(rhs).uintValue
}


class Control: Controllable {
    static var mainControl = Control()

    private init() {

    }

    private var stack: [Controllable] = []

    func addToStack(controllable: Controllable) {

    }
}

There is an error (Xcode 7.3):

return ObjectIdentifier(lhs).uintValue == ObjectIdentifier(rhs).uintValue

Cannot invoke initializer for type 'ObjectIdentifier' with an argument list of type '(T)'

QUESTION 1: Why? How can I construct ObjectIdentifier from lhs and rhs ?


VERSION_2:

import Foundation

protocol Controllable {
}

class Control: Controllable {
    static var mainControl = Control()

    private init() {

    }

    private var stack: [Controllable] = []

    func addToStack(controllable: Controllable) {
        stack.contains({ element in
            return ObjectIdentifier(element).uintValue == ObjectIdentifier(controllable).uintValue
        })
    }
}

There is an error (, again):

return ObjectIdentifier(element).uintValue == ObjectIdentifier(controllable).uintValue

Cannot invoke initializer for type 'ObjectIdentifier' with an argument list of type '((Controllable))'

QUESTION 2: Is (Controllable) tuple? How should I extract Controllable from the tuple?


Sorry for my English

ObjectIdentifier only works on objects and metatypes as argument in the constructor.

Types that conforms to Controllable are not conforming to the type constraint in the ObjectIdentifier constructor.

init(_ x: AnyObject)
init(_ x: Any.Type)

see here .

You want to give the ObjectIdentifier the metatype of a type, like String.self. Or you want to give the ObjectIdentifier an object, like "hello". You could add the object constraint to the protocol like this:

import Foundation

protocol Controllable: Equatable, AnyObject {
}

func ==<T: Controllable>(lhs: T, rhs: T) -> Bool {
    return ObjectIdentifier(lhs).uintValue == ObjectIdentifier(rhs).uintValue
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM