Swift and objective-c A concise tutorial for mixing
Reprinted from: HTTPS://GITHUB.COM/LIFEDIM/SWIFTCASTS/TREE/MASTER/000_MIX_SWIFT_OBJC
I think many iOS developers know Swift, the biggest problem in the mind is how to apply Swift to the original project. Below I will briefly describe the mix of these 2 languages, which is referenced from the official document Using Swift with Cocoa and Objective-c, which is recommended for everyone to read.
Using the Objective-c class in Swift
To create a new file (? +n) in Xcode6, select Swift, and then the system box prompts you to make sure that the Xxx-bridging-header.h file (XXX is your project name) is created at the same time.
This automatically created Bridging-header.h file is a bridge between the Swift world and the Objective-c world . any custom objective-c classes that need to be used in swift files must first be introduced into this header file .
Suppose the project name is TestSwift
, where there is a Objective-c class note ( Note.m
defined in):
@interface Note:nsobject -(void) log; @end
To refer to this class in Swift, you first need TestSwift-Bridging-Header.h
to import the note in the file:
#import " Note.h "
You can then use the note in Swift code:
class Viewcontroller:uiviewcontroller { override func viewdidload () { Super.viewdidload () = Note () a.log () } }
Using the Swift class in Objective-c
To refer to the classes defined in the Swift file in the Objective-c file, you need to introduce a special header file in the Objective-c file: Xxx-swift.h, assuming the project name is TestSwift
, So the header file that needs to be introduced is TestSwift-Swift.h
:
Suppose there is a book class (defined in the Book.swift
file):
Import Foundation class book:nsobject { var title:string init () { "Defaultbook" } func log () { println (self.title) } }
In the objective-c file that needs to refer to the book class, first introduce the TestSwift-Swift.h
header file (this file does not need to be created)
#import " testswift-swift.h "
Then you can use the book:
New ]; [book log];
In the end, the XXX-Swift.h
file is not visible in the project (it is estimated to be generated automatically at compile time), and it is OK to follow Apple's established rules when using it.