Swift与OC部分方法、类型区别与互转

Swift与OC转换

1、获取对象类型

OC:

NSDate* date = [NSDate date];

NSLog(@"%@",NSStringFromClass([date class]));

Swift:

letdate =NSDate()

letname = date.dynamicType

共有:

let name:AnyClass! = object_getClass(date)

2、函数入参中对象转化

OC转Swift,对象变为可选类型

Swift转OC,不用改变

3、枚举

1)Swift按位操作使用OptionSetType

struct MyOptions : OptionSetType {    

let rawValue: Int    

static let None        = MyOptions(rawValue: 0)    

static let FirstOption  = MyOptions(rawValue: 1 << 0)    

static let SecondOption = MyOptions(rawValue: 1 << 1)    

static let ThirdOption  = MyOptions(rawValue: 1 << 2)}

Now we can use set-based semantics withMyOptions:

let singleOption = MyOptions.FirstOption

let multipleOptions: MyOptions = [.FirstOption, .SecondOption]

if multipleOptions.contains(.SecondOption) { 

print("multipleOptions has SecondOption")

}

let allOptions = MyOptions(rawValue: 7)

if allOptions.contains(.ThirdOption) { 

print("allOptions has ThirdOption")

}

2)OC调用Swift,只需增加前缀@objc

@objc enum Bear: Int {    case Black, Grizzly, Polar}

Shamelessly taken from the[Swift Blog](https://developer.apple.com/swift/blog/?id=22)

In Objective-C this would look like

Bear type = BearBlack;switch (type) { 

case BearBlack: 

case BearGrizzly: 

case BearPolar:[self runLikeHell];

}

3)Swift调用OC直接使用rawValue

你可能感兴趣的:(Swift与OC部分方法、类型区别与互转)