Swift與OC的區別
1、基礎篇
2、監聽方法
OC ? ? ?使用 @selector(actionName)
Swift ? 直接使用字符串,提示:可以先用智能提示敲出方法名,然后增加引號
oc
-(void)test{
? ? ? ? ? ?UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
? ? ? ? ? [button addTarget:self action:@selector(didClick:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)didClick:(UIButton*)button{
}
swift
override func viewDidLoad() {
? ? ? ? // 創建按鈕
? ? ? ? ?let ?btn =UIButton(type:UIButtonType.ContactAdd)? ? ? ??
? ? ? ? ?v.addSubview(btn)
? ? ? ? // 監聽方法
? ? ? ? btn.addTarget(self, action:"clickButton", forControlEvents: .TouchUpInside)? ?
?}
func ?clickButton(btn: UIButton){
? ? ? ? print(__FUNCTION__)
? ? ? ? ?print(btn)??
? }
如果有參數直接增加 ':'
3、常量與變量聲明
oc的變量聲明使用? 類型 變量名 = 變量值的方式,其中類型為系統內置數據類型或自定義類型,變量名需由英文字母開頭且不能包含特殊字符
swift變量聲明使用 var 變量名 = 變量值的方式,其中變量名可以使用任何你喜歡的字符,甚至是表情符號emoji等
oc常量聲明使用const放在變量定義前即為聲明常量,如:const NSString *str = @"Hello";
swift常量聲明使用 let 常量名 = 常量值的方式,同樣可以使用任何你喜歡的字符作為常量名
swift 可以自動推斷出常量與變量的數據類型,當然也可以使用“:數據類型”的方式指定其具體數據類型,如 let age:Int = 10
PS:swift嚴格要求變量在使用前必須進行初始化,如上所示,必須給定變量值,而oc則不強制
4、屬性和變量(propertry,variable)
在OC中使用屬性一般都使用如下格式:
? ? ? ? ? ?@property (strong,nonatomic) NSString *string;
而在Swift中的屬性一般都使用如下格式:
? ? ? ? ? ?class Shape { var name = "shape"}
在oc中可以直接與變量打交道,swift中則行不通,在Swift的世界里,我們只與property打交道。在Swift中,屬性分為存儲屬性和計算屬性。簡單來說,就是存儲屬性能夠保存值,而計算屬性只提供getter與setter,利用存儲屬性來生成自己的值。計算屬性更像方法,而不是傳統意義的屬性。但是這樣一個特性存在,使得我們更容易組織我們的代碼。
構造變量
? ? ? ? ? ? ? 在OC中,只能通過單例,或者static變量加類方法來構造類變量:
@interface Model
+ (int) value;
+ (void) setValue:(int)val;
@end
@implementation Modelstatic
? ? ? ?int value;
? ? ? + (int) value{
@synchronized(self) {
? ? ? ?return value;
}
+ (void) setValue:(int)val{
? ? ? ?@synchronized(self) {
? ? ? ? ? ? ? ? value = val;
}
}
@end
// Foo.h@interface Foo {}
+ (NSDictionary *) dictionary;
// Foo.m oc單例
+ (NSDictionary *) dictionary{
? ? ? ?static NSDictionary* fooDict = nil;
? ? ? ? static dispatch_once_t oncePredicate;
? ? ? ? dispatch_once(&oncePredicate, ^{
? ? ? ? ?// create dict
? ? ? ? });
? ? ? ? return fooDict;
}
? ? ? ? ? ? ? ?在swift中,可以通過清晰的語法便能定義類變量,通過static定義的類變量無法在子類重寫,通過class定義的類變量則可在子類重寫。
struct SomeStructure {
? ? ? ? ?static var storedTypeProperty = "Some value."
? ? ? ? ?static var computedTypeProperty: Int {
? ? ? ? ?return 1
? ? ? ? ?}
? ? ? ? class var overrideableComputedTypeProperty: Int {
? ? ? ? ? ? ? ? ? ?return 107
? ? ? ? ?}
}
//swift單例
class singletonClass {
? ? ? ? ? static let sharedInstance = singletonClass()
? ? ? ? ? ?private init() {}?
? ? ? ? ?// 這就阻止其他對象使用這個類的默認的'()'初始化方法
}
5、控制語句
分支語句: if,switch和guard(新增)
if后面的語句必須為bool類型,可以不加括號
switch 可以支持Int,Float,Double,String,Tuple等AnyObject,無需break
guard 是Swift2.x新增關鍵字,必須配合else使用,解決if-else多層嵌套問題,判斷一個條件為true下執行某語句,否則終止或跳轉執行其他語句
循環語句: while, repeat-while,for(改動),for-in
for循環 摒棄掉了c的style,一律以...來替代,不得不說很贊。
for i in 1...arr.count{
//循環體
}
swift專門提供了遍歷集合的方法for-in
let numbers = [1,2,3,4,5,6,7,8,9,10]
for (index,element) in numbers.enumerate(){
print("Item \(index) : \(element)")? ? //index和item都有了
}
swift中的for循環提供了類似NSRange方式的跨步查找方式
for index in stride(from: 1, through: 5, by: 2) { print(index)}
跳轉語句: break,continue,fallthrough(新增),return,throw(新增)
fall through 是貫通語句,只能在switch中使用,如果一個case執行完畢,需要執行另一個case,則需要用fallthough跳轉至下一個case
throw 在oc中的NSError一定很熟悉了,在swift里,借助java的try..catch語句可以將程序中拋出(throw)的異常收集起來。
值綁定: 常用于if,guard,switch,where
在控制語句中將表達式的值臨時賦給一個常量或者變量,這些常量或者變量可以在該控制語句中使用,稱為"值綁定"。
where語句類似于sql中的where語句,非常好用。
//switch中使用元祖類型
var student = (id:"1002",name:"李四",age:32, ChineseScore:80, EnglishScore:89)
var desc: String
switch student {
case (_, _, _, 90...100, 90...100) where age > 20:? //where語句
desc = "優"
case (_, _, _, 80...90, 80...90):
desc = "良"
case (_, _, _, 60...80, 60...80):
desc = "中"
case (_, _, _, 60...80, 90...100), (_,_, _, 90...100, 60...80):
desc = "偏科"
case (_, _, _, 0...80, 90...100), (_,_, _, 90...100, 0...80):
desc = "嚴重偏科"
default:
desc = "無"
}
print("說明:\(desc)")