Convert Objective-C syntax to Swift 3 - objective-c

What will be the syntax of the following Objective-C method in Swift?
-(id)init
{
Viewcontroller static *vc=nil;
if(!vc)
{
vc=[super init];
return vc;
}
else return vc;
}

Below is the syntax in Swift 3
override init() {
var vc: Viewcontroller? = nil
if vc == nil {
vc = super.init()
return vc!
}
else {
return vc!
}
}

Related

How to pass parameter in swift controller to objective c model?

I couldn't figure out on how to pass variables with type String in swift controller files and pass it to object written in objective-c. However, if I pass a string directly as a parameter it works just fine. Thank you for your help.
This is the objective-c class below
#import "Message.h"
#implementation Message
- (instancetype)initWithDictionary:(NSDictionary *)dictionary
{
self = [super init];
if (self)
{
self.userID = dictionary[#"user_id"];
self.username = dictionary[#"username"];
self.avatarURL = dictionary[#"avatar_url"];
self.text = dictionary[#"message"];
}
return self;
}
- (instancetype)initWithTestName:(NSString *)name withTestMessage:(NSString *)message withUserId:(NSString *)userId withAvatarUrl:(NSString *)url
{
self = [super init];
if (self)
{
self.userID = userId;
self.username = name;
self.avatarURL = url;
self.text = message;
}
return self;
}
#end
and this is the swift controller file
import UIKit
class ChatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
private var messages = [Message]()
override func viewDidLoad() {
super.viewDidLoad()
// I can pass the string successfully to the messages this way
messages.append(Message(testName: "Test", withTestMessage: "Hello", withUserId: "1", withAvatarUrl: "http://www.example.com"))
// After successfully making Api Request, I wasn't able to pass a variable as parameter
if let data = dic as? [String:Any]{
let userId = data["user_id"] as? String
let url = data["avatar_url"] as? String
let name = data["name"] as? String
let message = data["message"] as? String
self.messages.append(Message(testName: name, withTestMessage: message, withUserId: userId, withAvatarUrl: url))
}
}
}

How to add swizzling method to UIApplication using Swift?

I have a code below trying to use swizzling method to UIApplication methods. But the methods not getting called. Meanwhile, I'm trying to add this code into a framework or a private pod.
extension UIApplication {
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
struct SwizzlingSelector {
let original:Selector
let swizzled:Selector
}
// make sure this isn't a subclass
if self !== UIApplication.self {
return
}
dispatch_once(&Static.token) {
let selectors = [
SwizzlingSelector(
original: Selector("application:didFinishLaunchingWithOptions:"),
swizzled: Selector("custome_application:didFinishLaunchingWithOptions:")
),
SwizzlingSelector(
original: Selector("applicationDidEnterBackground:"),
swizzled: Selector("custom_applicationDidEnterBackground:")
)
]
for selector in selectors {
let originalMethod = class_getInstanceMethod(self, selector.original)
let swizzledMethod = class_getInstanceMethod(self, selector.swizzled)
let didAddMethod = class_addMethod(self, selector.original, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, selector.swizzled, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
}
}
// MARK: - Method Swizzling
public func custome_application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
print("is here")
return true
}
func custom_applicationDidEnterBackground(application: UIApplication) {
print("is herer")
}
}
I think you should implement this swizzling method in your AppDelegate but not as extension of UIApplication. Cause you swizzle your AppDelegate's methods but not UIApplication's methods.
extension YourAppDelegate {
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
struct SwizzlingSelector {
let original:Selector
let swizzled:Selector
}
// make sure this isn't a subclass
if self !== YourAppDelegate.self {
return
}
dispatch_once(&Static.token) {
let selectors = [
SwizzlingSelector(
original: Selector("application:didFinishLaunchingWithOptions:"),
swizzled: Selector("custome_application:didFinishLaunchingWithOptions:")
),
SwizzlingSelector(
original: Selector("applicationDidEnterBackground:"),
swizzled: Selector("custom_applicationDidEnterBackground:")
)
]
for selector in selectors {
let originalMethod = class_getInstanceMethod(self, selector.original)
let swizzledMethod = class_getInstanceMethod(self, selector.swizzled)
let didAddMethod = class_addMethod(self, selector.original, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, selector.swizzled, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
}
}
// MARK: - Method Swizzling
public func custome_application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
print("is here")
return true
}
func custom_applicationDidEnterBackground(application: UIApplication) {
print("is herer")
}
}

converting setter, getter variable from objective C to swift 2.2

I am facing issues while converting from Objective C to Swift 2.2.. Can anyone help me..??
Here is the code in Objective C
variables declared as
#property (nonatomic, assign) NSInteger currentViewControllerIndex;
#property (nonatomic, getter = isWrapEnabled) BOOL wrapEnabled;
and the variable setting functions in Objective C are
- (void)setWrapEnabled:(BOOL)sWrapEnabled {
wrapEnabled = sWrapEnabled;
[self.view layoutIfNeeded];
}
- (void)setCurrentViewControllerIndex:(NSInteger)curViewControllerIndex {
[self scrollToViewControllerAtIndex:curViewControllerIndex animated:NO];
}
This is how i have written in Swift
var tmpWrapEnabled : Bool = Bool()
internal(set) var wrapEnabled : Bool? {
get {
return tmpWrapEnabled
}
set(newValue) {
if newValue == true {
tmpWrapEnabled = newValue!
self.view.layoutIfNeeded()
}
}
}
var tmpCurrentViewControllerIndex : NSInteger = 0
internal(set) var currentViewControllerIndex : NSInteger? {
get {
return tmpCurrentViewControllerIndex
}
set(newValue) {
tmpCurrentViewControllerIndex = newValue!
}
}
Basically you need only the didSet observers, for the rest the variable behaves as a normal variable.
var wrapEnabled : Bool {
didSet {
if wrapEnabled {
self.view.layoutIfNeeded()
}
}
}
var currentViewControllerIndex : Int {
didSet {
scrollToViewControllerAtIndex(currentViewControllerIndex, animated:false)
}
}
Consider that the observers are not called when the initial value is assigned to the variable.

Singleton in swift to Objective-C giving error property not found of type XYZ *

I have a function in swift as follows
public class XYZ:NSObject {
public static func getInstance() -> GlobalEventBus {
return globalEventBusInstance
}
public static var xyzInstance:XYZ = XYZ()
var initialized:Bool?
public func dispatchEvent(customEvent:CustomEvent) { }
override init() {
initialized = true
}
}
I used the getInstance function in objective C implementation as follows
#implementation SomeFile
- (instancetype)init
{
self = [super init];
if (self) {
}
return self;
}
/* log a message */
- (void)sendEvent:(CDVInvokedUrlCommand*)command
{
id message = [command argumentAtIndex:0];
XYZ *xyzInstance = [XYZ getInstance];
CustomEvent *customEvent = [CustomEvent alloc];
xyzInstance.dispatchEvent(customEvent)
//customEvent.eventType =
}
#end
The problem i am seeing is that I see an error
"Property dispatchEvent not found on object of type XYZ *"
Does it have anything to do with the fact that the instance variable being returned is a static variable? What am I doing wrong? Please help
Thank you
Nikhil
In your Objective-C code, you have a line that says:
xyzInstance.dispatchEvent(customEvent)
That's Swift. You want:
[xyzInstance dispatchEvent:customEvent];

How to invoke [self new] in Swift

Here is an UIView extension written in ObjectiveC to easily create view for using Auto-layout:
+(id)autolayoutView
{
UIView *view = [self new];
view.translatesAutoresizingMaskIntoConstraints = NO;
return view;
}
it invokes [self new] so any subclass of UIView can use this method. How can I achieve this in Swift?
OK, this appears to be the solution. The type must have a required initializer with the correct parameter list (in this case no parameters).
class SubView: UIView {
override required init() {
super.init()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
class func autolayoutView() -> UIView {
var view = self()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
return view
}
}
Though both Carrl and Gregory Higley are right with there solutions, including thr remark about the fact that self() needs to use a required init i wanted to post a more general example:
class Human {
var gender = String()
required init() {
self.gender = "any"
}
class func newHuman() -> Human {
return self()
}
}
class Man : Human {
required init() {
super.init()
self.gender = "male"
}
}
var someMan = Man.newHuman()
println(someMan.gender) // male
Inspired by Gregory Higley, i think the solution is here:
extension UIView{
class func autolayoutView() -> UIView {
var view = self()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
return view
}
}
Update for Swift2.1:
extension UIView{
class func autolayoutView() -> UIView {
let view = self.init()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}
}