Swift 调用 Objective-C代码 1)

公冶弘壮
2023-12-01

1. Initialization

For example, where in Objective-C you would do this:


OBJECTIVE-C


UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
In Swift, you do this:



SWIFT


let myTableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped)”


init 和 with 被砍掉了,随后的selector当作参数提示符。


2.  Factory methods -》Convenience Initializer

UIColor *color = [UIColor colorWithRed:0.5 green:0.0 blue:0.5 alpha:1.0];

let color = UIColor(red: 0.5, green: 0.0, blue: 0.5, alpha: 1.0)


color with 被砍掉了



3.  “Accessing Properties


Access and set properties on Objective-C objects in Swift using dot syntax.


<pre name="code" class="objc">UIColor.darkGrayColor()
是SWIFTmyTextField.textColor = UIColor.darkGrayColor() //class method : darkGrayColor()
myTextField.text = "Hello world"if myTextField.editing { myTextField.editing = false}

 



4, “Working with Methods
When calling Objective-C methods from Swift, use dot syntax.


When Objective-C methods come over to Swift, the first part of an Objective-C selector becomes the base method name and appears outside the parentheses. The first argument appears immediately inside the parentheses, without a name. The rest of the selector pieces correspond to argument names and go inside the parentheses. All selector pieces are required at the call site.


For example, whereas in Objective-C you would do this:

OBJECTIVE-C


[myTableView insertSubview:mySubview atIndex:2];


In Swift, you do this:

SWIFT


myTableView.insertSubview(mySubview, atIndex: 2)



5. id Compatibility

var myObject: AnyObject = UITableViewCell()
myObject = NSDate()

let futureDate = myObject.dateByAddingTimeInterval(10)
let timeSinceNow = myObject.timeIntervalSinceNow

“in contrast with Objective-C, if you invoke a method or access a property that does not exist on an AnyObject typed object, it is a runtime error”

myObject.characterAtIndex(5)

// crash, myObject does't respond to that method


安全方法:optional chain

let myLength = myObject.length?
let myChar = myObject.characterAtIndex?(5)
if let fifthCharacter = myObject.characterAtIndex(5) {
    println("Found \(fifthCharacter) at index 5")
}

let userDefaults = NSUserDefaults.standardUserDefaults()
let lastRefreshDate: AnyObject? = userDefaults.objectForKey("LastRefreshDate")
if let date = lastRefreshDate as? NSDate {
    println("\(date.timeIntervalSinceReferenceDate)")
}


确信可以downcast
let myDate = lastRefreshDate as NSDate
let timeInterval = myDate.timeIntervalSinceReferenceDate


6. Working with nil

“In Swift, all values—including structures and object references—are guaranteed to be non–nil. Instead, you represent a value that could be missing by wrapping the type of the value in an optional type.”

“Because Objective-C does not make any guarantees that an object is non-nil, Swift makes all classes in argument types and return types optional in imported Objective-C APIs. Before you use an Objective-C object, you should check to ensure that it is not missing.”

7. Extensions   (可以扩展OC的class)

extension UIBezierPath {
    convenience init(triangleSideLength: Float, origin: CGPoint) {
        self.init()
        let squareRoot = Float(sqrt(3))
        let altitude = (squareRoot * triangleSideLength) / 2
        moveToPoint(origin)
        addLineToPoint(CGPoint(triangleSideLength, origin.x))
        addLineToPoint(CGPoint(triangleSideLength / 2, altitude))
        closePath()
    }
}

8. Closures

“Swift closures and Objective-C blocks are compatible, so you can pass Swift closures to Objective-C methods that expect blocks. Swift closures and functions have the same type, so you can even pass the name of a Swift function.”

void (^completionBlock)(NSData *, NSError *) = ^(NSData *data, NSError *error) {/* ... */}

let completionBlock: (NSData, NSError) -> Void = {data, error in /* ... */}




 类似资料: