In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to realize the interaction between Swift and Objective-C API". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to realize the interaction between Swift and Objective-C API".
Swift and Objective-C are interoperable, which means that Swift code can be used in Objective-C projects and vice versa. Of course, the most important thing between this interoperability is that you can call the interface of Objective-C in Swift. After all, most of the interfaces are provided through Objective-C.
Initialization
When you instantiate an Objective-C class in Swift, you can call one of its initializers using the Swift syntax. The initialization method of Objective-C is divided into keywords. For example, "initWith" becomes "init", and the rest is used as the parameter name of the method.
The code for Objective-C:
UITableView * myTableView = [[UITableView alloc] initWithFrame: CGRectZero style: UITableViewStyleGrouped]
The corresponding Swift code is:
Let myTableView: UITableView = UITableView (frame: CGRectZero, style: .grouped)
There is no need to call the alloc method in Swift, it automatically handles the object creation function. Note: Swift does not explicitly call the init method.
When defining a variable or constant, its type can be omitted and Swift will automatically recognize it.
Let myTextField = UITextField (frame: CGRect (0.0,0.0,0.0,40.0))
For convenience, the factory method of Objective-C is mapped to an initializer in Swift. For example:
UIColor * color = [UIColor colorWithRed: 0.5 green: 0.0 blue: 0.5 alpha: 1.0]
Convert to Swift:
Let color = UIColor (red: 0.5, green: 0.0, blue: 0.5, alpha: 1.0) attribute access
The dot operator is used to access properties in both Objective-C and Swift.
MyTextField.textColor = UIColor.darkGrayColor () myTextField.text = "Hello world" if myTextField.editing {myTextField.editing = false}
You do not need to use parentheses when accessing and setting properties. The above darkGrayColor has parentheses because you are calling UIColor's class methods, not properties.
A method in Objective-C that does not require parameters and has a return value can be used as an implicit get method (getter), thus using the dot operator. However, in Swift, the point operator can only access properties defined in Objective-C using @ property.
Method call
Use the dot operator in Swift to call the methods in Objective-C.
When Objective-C 's method is called in Swift, the first part of it becomes the basic method of Swift appears before the parentheses. Then the first argument of the function has no name, and the rest is the name of the parameter corresponding to the Swift function.
Objective-C syntax:
[myTableView insertSubview: mySubview atIndex: 2]
Swift Code:
MyTableView.insertSubview (mySubview atIndex: 2)
Call a method with no parameters:
MyTableView.layoutIfNeeded () is compatible with id types
Swift contains a protocol called AnyObject, which is similar to id in Objective-C and can represent any type of object. The AnyObject protocol allows you to take advantage of the flexibility of untyped objects while maintaining type safety.
You can assign any value to a variable of type AnyObject:
Var myObject: AnyObject = NSData ()
You can directly method any properties and methods of an AnyObject type object without casting.
Let dateDescription = myObject.descriptionlet timeSinceNow = myObject.timeIntervalSinceNow
Because the type of a variable of type AnyObject cannot be determined until run time, it can lead to unsafe code. In particular, you can access a property or method that does not exist, it just reports an error at run time.
MyObject.characterAtIndex (5) / / crash, myObject doesn't respond to that method
When doing a type conversion, the conversion may not be successful, so Swift returns an option value. You can check whether the conversion is successful.
Let userDefaults = NSUserDefaults.standardUserDefaults () let lastRefreshDate: AnyObject? = userDefault.objectForKey ("LastRefreshDate") if let date = lastRefreshDate as? NSDate {println ("\ (date.timeIntervalSinceReferenceDate)")}
If you can determine the type of object and it is not nil, you can use the as operator to cast.
Let myDate = lastRefreshDate as NSDatelet timeInterval = myDate.timeIntervalSinceReferenceDatenil object
Nil is used in Objective-C to represent a reference to an empty object (null). All values in Swift will not be nil. If you need to represent a missing value, you can use Optional.
Because Objective-C cannot guarantee that all values are non-null, Swift represents the parameters and return values of the methods introduced in Objective-C as Optional. Before using Objective-C objects, you should check whether they exist.
Expansion
The extension of Swift is somewhat similar to the category of Objective-C. Extensions can add behavior to existing classes, structures, enumerations, and so on.
Here's how to add an extension to UIBezierPath:
Extension UIBezierPath {class func bezierPathWithTriangle (length: Float, origin: CGPoint)-> UIBezierPath {let squareRoot = Float (sqrt (3)) let altitude = (squareRoot * length) / 2 let myPath = UIBezierPath () myPath.moveToPoint (orgin) myPath.addLineToPoint (CGPoint (length, origin.x)) myPath.addLineToPoint (CGPoint (length / 2, altitude) myPath.closePath () return myPath}
You can use extensions to add properties (including class or static properties). However, these attributes can only be calculated, not stored. Let's add an area attribute to CGRect:
Extension CGRect {var area: CGFloat {return width * height}} let rect = CGRect (x: 0, y: 0, width: 10, height: 50) let area = rect.area//area: CGFloat = 500.0
Use extensions to make existing classes respond to a protocol without creating subclasses. It is important to note that extensions cannot overwrite existing methods and properties.
Closure
Block in Objective-C is automatically imported as a closure of Swift. For example:
Void (^ completionBlock) (NSData *, NSError *) = ^ (NSData * data, NSError * error) {/ *... * /}
In Swift, the corresponding is:
Let completionBlock: (NSData, NSError)-> void = {data, error in / *... * /}
Swift's closures are compatible with Block in Objective-C, and you can pass closures to Objective-C 's methods in Swift instead of Block objects.
Closures are a little different from Block objects in that the variables are mutable, that is, they behave the same as the variables modified by _ _ block.
Object comparison
There are two ways to compare objects in Swift. The first is equality (= =) (equality), which is used to compare whether the contents of two objects are the same. The second is identity (= =) (identity), which compares whether two variables or constants refer to the same object.
NSObject can only compare whether the same object (identity) is referenced, and if you want to compare whether the content is the same, you should implement the isEqual: method.
Swift type compatibility
Define a class that inherits from NSObject or other Objective-C, which is automatically compatible with Objective-C. If you don't need to import Swift objects into Objective-C code, there's no need to worry about type compatibility. But if the class defined in Swift is not a subclass of the Objective-C class, you need to use @ objc when using it in Objective-C.
@ objc makes Swift's API available for use in Objective-C and its runtime. The @ objc attribute is automatically added when using attributes such as @ IBOutlet, @ IBAction, or @ NSManaged.
@ objc can also be used to specify the name of a property or method in Swift in Objective-C. For example, Swift supports Unicode names, including the use of Objective-C incompatible characters such as Chinese. Also assign a Selectorde name to the function defined in Swift.
@ objc (Squirrel) class Camp David Education in Changsha {@ objc (hideNuts:inTree:) func Welcome to (Int, name: String) {/ *... * /}}
When the @ objc () attribute acts on a class of Swift, the use of this class in Objective-C is not restricted by namespaces. Similarly, when you unarchive an Objective-C archived object in Swift, you need to use @ objc to indicate the class name of Objective-C in Swift because there is a class name in the archived object.
Objective-C selector (Selector)
The selector of Objective-C is a reference to the method. In Swift, it corresponds to the Selector structure. Use string literals to build a selector object, such as let mySelector: Selector = "tappedButton:". Because string literal constants can be automatically converted to selector objects, you can use string literal constants wherever you need to pass selectors.
Import UIKitclass MyViewController: UIViewController {let myButton = UIButton (frame: CGRect (x: 0, y: 0, width: 100, height: 50) init (nibName nibNameOrNil: stringency, bundle nibBundleOrNil: NSBundle!) {super.init (nibName: nibName, bundle: nibBundle) myButton.targetForAction ("tappedButton:", withSender: self)} func tappedButton (sender: UIButton!) {println ("tapped button")}}
Prompt
PerformSelector: and the associated methods that call selectors are not introduced into Swfit because they are not completely safe.
If the Swift class inherits from Objective-C 's class, the methods and properties in it can be used as selectors for Objective-C. If it is not a subclass of Objective-C, it needs to be decorated with the @ objc attribute, which is described earlier in Swift type compatibility.
Thank you for reading, the above is the content of "how to achieve the interaction between Swift and Objective-C API". After the study of this article, I believe you have a deeper understanding of how to achieve the interaction between Swift and Objective-C API, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.