Your question somewhat vague, but I think the word you are looking for is "protocol", exhaustively explained in Apple's docs:
The following example defines a protocol with a single instance
method requirement:
protocol RandomNumberGenerator {
func random() -> Double
}
Somewhere else you create a class that implements the required method:
class LinearCongruentialGenerator: RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29573.0
func random() -> Double {
lastRandom = ((lastRandom * a + c) % m)
return lastRandom / m
}
}
And somewhere else you store / use the protocol, calling the method defined on the delegate (that implements the protocol).
class Dice {
let sides: Int
let generator: RandomNumberGenerator // delegate object that implements the protocol
init(sides: Int, generator: RandomNumberGenerator) {
self.sides = sides
self.generator = generator
}
func roll() -> Int {
return Int(generator.random() * Double(sides)) + 1
}
}
As to where you do this, it's the same as Obj-c. Swift makes it easier as it does not require you to import header files, so you can either put it in the file of the client (the class that uses it), or in it's own file. Per above, you would declare and implement the protocol method(s) in the class that will become the delegate instance.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…