Swift類型兼容性
定義一個繼承自NSObject
或者其他Objective-C的類,它自動與Objective-C兼容。如果你不需要將Swift對象導入Objective-C代碼的話,沒必要關注類型的兼容性。但是如果在Swift中定義的類不是Objective-C類的子類,在Objective-C中使用的時候,需要用@objc
進行說明。
@objc
使得Swift的API可以在Objective-C和它的運行時中使用。當使用@IBOutlet
、@IBAction
或者@NSManaged
等屬性時,自動添加@objc
屬性。
@objc
還可以用來指定Swift中的屬性或方法在Objective-C中的名字,比如Swift支持Unicode名字,包括使用中文等Objective-C不兼容的字符。還有給Swift中定義的函數指定一個Selectorde名字。
@objc(Squirrel)
class 長沙戴維營教育 {
@objc(hideNuts:inTree:)
func 歡迎光臨(Int, 姓名: String) {
/* ... */
}
}
當@objc(<#name#>)
屬性作用在Swift的類上時,這個類在Objective-C的使用不受命名空間的限制。同樣,在Swift中解歸檔Objective-C歸檔的對象時,由於歸檔對象中存放有類名,因此需要在Swift中用@objc<#name>
說明Objective-C的類名。
Objective-C選擇器(Selector)
Objective-C的選擇器是方法的一個引用。在Swift中對應的是Selector
結構體。使用字符串字面量可以構建一個選擇器對象,如let
mySelector: Selector = "tappedButton:"
。由於字符串字面常量可以自動轉換爲選擇器對象,因此可以在任何需要傳遞選擇器的地方使用字符串字面常量。
<code class="ocaml hljs" data-origin="" <pre><code="" uikit"="" style="margin: 0px; padding: 0px; border: 0px; font-size: inherit; font-variant: inherit; font-weight: bold; line-height: inherit; vertical-align: baseline; color: rgb(110, 107, 94); font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace !important;">import UIKit
class MyViewController: UIViewController {
let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
{
super.init(nibName: nibName, bundle: nibBundle)
myButton.targetForAction("tappedButton:", withSender: self)
}
func tappedButton(sender: UIButton!) {
println("tapped button")
}
}
提示
performSelector:
以及相關的調用選擇器的方法沒有被引入到Swfit中來,因爲它們不是完全安全的。
如果Swift類繼承自Objective-C的類,則它裏面的方法和屬性都能夠作爲Objective-C的選擇器使用。而如果不是Objective-C的子類,需要使用@objc
屬性修飾,這個在前面的Swift類型兼容性中有描述。