斯威夫特代表。

时间:2015-05-25 10:19:40

标签: objective-c swift protocols

在Objective-C中我可以做这样的事情:

@property (nonatomic, weak) id<SomeCustomProtocol> someObject;

如何快速制作? 我试过这个:

let someObject: AnyObject, SomeCustomProtocol = ....;

它不起作用。

4 个答案:

答案 0 :(得分:4)

在Swift中声明委托的正确方法是:

import Foundation
import Mixpanel

public class Tweaks : NSObject, MPTweakObserver {

  public static let sharedInstance = Tweaks(tweaks: [ ExecuteDiskCleanup])

  public static let ExecuteDiskCleanup = Tweak.Booln(name: "Cleanup-Disk", defaultValue:false)

  private var values = [String:AnyObject]()
  private let tweaks: [Tweak]

  public init(tweaks: [Tweak]) {
    self.tweaks = tweaks
    let defaults = NSUserDefaults.standardUserDefaults()
    for tweak in tweaks {
      if let value: AnyObject = defaults.objectForKey(Tweaks.generateKey(tweak.name)) {
        self.values[tweak.name] = value
        println("Initialized Tweak \(tweak.name) with value: \(value)")
      }
    }
  }

  public func setup() {
    tweaks.foreach(){ tweak  in
      let theTweak = MPTweak(name: tweak.name, andEncoding: "UTF-8")
      theTweak.defaultValue = tweak.defaultValue
      theTweak.addObserver(self)
      MPTweakStore.sharedInstance().addTweak(theTweak)
    }

    Mixpanel.sharedInstance().checkForVariantsOnActive = true
    Mixpanel.sharedInstance().joinExperiments()
  }

  public func get(tweaks: [Tweak]) -> [String:AnyObject] {
    var result = [String:AnyObject]()
    synced(values) {
      tweaks.foreach(){ tweak in
        result[tweak.name] = self.values[tweak.name]
      }
    }
    return result
  }

  public func tweakDidChange(tweak: MPTweak) {
    println("tweakDidChange Tweak \(tweak.name) current value :\(tweak.currentValue)")
    synced(self.values) {
      let localTweak = self.tweaks.filter{ $0.name == tweak.name}.first
      if let localTweak = localTweak{
        switch (localTweak) {
        case .Booln:
          self.values[tweak.name] = Bool(tweak.currentValue as? Int == 1)
        default:
          self.values[tweak.name] = tweak.currentValue
        }
        println("Tweak \(localTweak.name) -> \(self.values[localTweak.name])")
        NSUserDefaults.standardUserDefaults().setObject(self.values[localTweak.name], forKey: Tweaks.generateKey(localTweak.name))
        NSUserDefaults.standardUserDefaults().synchronize()
      }
    }
  }

  private class func generateKey(key: String) -> String {
    return "mp_tweak_\(key)"
  }

}

public enum Tweak {
  case Str(name: String, defaultValue: String)
  case Booln(name: String, defaultValue: Bool)
  case Integer(name: String, defaultValue: Int)
  case Flt(name: String, defaultValue: Float)

  var name : String {
    switch (self) {
    case let .Str(n, d): return n
    case let .Booln(n, d): return n
    case let .Integer(n, d): return n
    case let .Flt(n, d): return n
    }
  }

  var defaultValue : AnyObject {
    switch (self) {
    case let .Str(n, d): return d
    case let .Booln(n, d): return d
    case let .Integer(n, d): return d
    case let .Flt(n, d): return d
    }
  }

  public func get<T>() -> T? {
    return get(self.defaultValue as? T)
  }

  public func get<T>(defaultValue: T?) -> T? {
    var value = synced(Tweaks.sharedInstance.values){
      return Tweaks.sharedInstance.values[self.name] as? T
    }
    return value != nil ? value : defaultValue
  }

}

//  Examples :
//  public static let SomeIntegerZero = Tweak.Integer(name: "SomeIntegerZero", defaultValue:0)
//  public static let SomeIntegerNonZero = Tweak.Integer(name: "SomeIntegerNonZero", defaultValue:6666)
//  public static let SomeBooleanFalse = Tweak.Booln(name: "SomeBooleanFalse", defaultValue:false)
//  public static let SomeBooleanTrue = Tweak.Booln(name: "SomeBooleanTrue", defaultValue:true)
//  public static let SomeStringEmpty = Tweak.Str(name: "SomeEmptyString", defaultValue:"")
//  public static let SomeStringFull = Tweak.Str(name: "SomeFullString", defaultValue:"full")


/*** Utilities - sync methods ***/
func synced<T>(lock: AnyObject, closure: () -> T) -> T {
  objc_sync_enter(lock)
  let result = closure()
  objc_sync_exit(lock)
  return result
}

func synced(lock: AnyObject, closure: () -> ()) {
  objc_sync_enter(lock)
  closure()
  objc_sync_exit(lock)
}

Swift使用ARC进行内存管理,因此它仍然容易保留周期。

阅读good reference了解详情。

答案 1 :(得分:3)

应该是这样的:

 var delegate: SomeCustomProtocol?

here

查找更多指导

答案 2 :(得分:2)

let someObject:SomeCustomProtocol = ....;

答案 3 :(得分:0)

创建委托属性时需要考虑的一些事项是:

  • 使用weak关键字以避免保留周期
  • 将属性设置为协议的可选类型

例如:

//Protocol
protocol SomeProtocolDelegate: class {
func doSomething()
}

weak var delegate: SomeProtocolDelegate?

这是一个更完整,非常有用的实现。

EF+ Query IncludeFilter