When to use delegate, inout or completion in Swift? - swift

When we call some code and need a response with multiple parameters we have multiple options in Swift:
Completion block
Delegate
Inout parameters
Wrapper object (simply put all parameters inside an object)
I was wondering if there were some good guidelines to when to use what? Specifically when would it be a bad practise to use inout instead of delegate?
To be VERY specific:
Also an example that can be used to explain:
I have class A that communicates with class B. Class A needs a list of data AND an optional error.
So right now I'm leaning towards using inouts:
Class A:
var error = ServiceError()
let wordSuggestions = B.parseSuggestionResponse(json: result as! NSDictionary, error: &error)
if error.type == .none {
// Success, now use wordSuggestions for something!
} else {
self.handleError(error: error)
}
Is there some disadvantages for this approach vs using delegates?

I will explain when each method should be used.
A completion block is used when the operation takes time. For example, UIView.animate has a completion block parameter because animating views take time.
A delegate is used only when some of object is present especially when that object can have multiple states. This is widely used for communication between the view and the controller When there is only a method, delegates don't work. For example, a GADInterstitial has a delegate because it can have different states, such as the user dismissing the ad, user clicks the ad and leaves the app, the ad is loaded etc.
Inout parameters are mainly used for passing value types as references. I can't find any usage of this in the iOS SDK because there is no inout in Objective-C. The closest thing to it is UnsafeMutablePointer<T>. Basically, if you want to make a method that takes a bunch of value type arguments and you want to change their value, use inout! Refer to this page for more info.
From my own experience, wrapper objects are rarely used in swift. That is because we have tuples! You can wrap everything in a tuple and pass that around. I don't usually create a new struct or class just to wrap a few parameters. But do use them if your data structure becomes something complicated like [(String, [String: (String, Int)])].

Related

Is it possible to use an alias for `self` in swift?

Swift appears to share with python one characteristic of requiring the class instance reference to access the members - even inside the class itself. The default in both languages is self. In particular
self.someClassMethod()
This is identical between python and swift. I also dislike this requirement finding it to be intrusive: it attracts my attention to self and away from which method is actually being invoked. In python I reduce (though do not remove) the annoyance by using s instead:
def someInstanceMethod(s, param1, param2)
instead of the standard
def someInstanceMethod(self, param1, param2)
Then inside the method I can access other instance methods :
s.someOtherInstanceMethod()
I'm not going to fight any battles on this: PEP folks will jump up and down about it -but it is more readable to me and others in my team. Is there any such way to do a shortcut in swift? I noticed typealias and tried to use it:
fileprivate let tp = U.tprint // Any non-critical logging statements will happen with this
But then it is necessary to do this:
self.tp("Loaded synthesizer settings")
Without the reference to self the following error occurs:
(162, 25) reference to property 'tp' in closure requires explicit 'self.' to make capture semantics explicit
I would prefer just
tp("Loaded synthesizer settings")
but that is not apparently possible. Can we get closer to that - along the lines of s.<method> instead of self.<method> ?
It's a little unclear what the question is, or what you think is the purpose of passing self around, so here's a quick summary of the key facts:
There are instance members and type members (type members are marked static or class).
If a method is an instance method, it does not need to say self to access instance members.
If a method is a type method, it does not need to say self to access type members.
If a method is an instance method, it can say Self to access type members.
If a method is a type method, there is no instance so instance members cannot be accessed.

Why do we need a weakSelf for functions/methods within closures?

Reading my own answer.
I fully understand why we need a weakSelf for members/properties. They could create memory cycles. But properties have a memory location.
Do functions also have memory locations?! I mean isn't a function something just happens on the go? If so is the memory location type any different from a property location?
If I don't refer using self I get this error.
Call to method 'alertFunc' in closure requires explicit 'self.' to
make capture semantics explicit
which is slightly different from:
Reference to property 'window' in closure requires explicit 'self.' to
make capture semantics explicit
My code is as follows:
let another = UIAlertAction(title: "Log", style:UIAlertActionStyle.Default){action in
logAction ()
}
private func logAction () {
print("health")
}
credit to iOS nerds I know from a meetup
tl;dr you need to use self for instance methods, but don't need it for class methods. A class may have many instances, but it can only have one declaration of itself (which also contains its type/class/static functions).
Why error occurs 1: Bare in mind the alertFunc could have had a reference to a property.
It could have been :
private func logAction () {
print("someProperty = \(self.someProperty)")
}
So, in this case it's obvious that you are eventually referencing a property.
Why error occurs 2: Even if you don't have a reference to self within your function, still because you wrote it as an instance method, the self is implicitly passed on. But, we don't see!
An instance method is really just syntactic sugar for a function that takes an instance for the first parameter, which is self passed automatically.
Under the hood it may look something like this :
private func alertFunc (_ instance: MyType) {
print("someProperty = \(instance.someProperty)")
}
// and actually the call to it *may* look something like this:
MyType.someFunc(self)
We never see the self being passed! It's a syntactic sugar that deceives us.
So, if your method does not use self internally (i.e. doesn't rely on the state of the instance in any way) then it's actually probably best to make it a static/type/class method or free function.
Alternative1: use a free function.
class someClass {
...
}
func freeFunc {
print("Hi this is a free function, written outside the scope of any class...")
}
And then within your closure you call it using freeFunc()
Alternative2: Use a class function.
class someClass {
...
class private func alertFunc() {
print("Hi this was a class function, see the class at the beginning of the func definition")
}
}
And then within your closure you call it using yourClassName.alertFunc()
But, why is it that class functions don't create memory cycles but instance functions do?
I'm glad you asked:
For instance mehtods, for each instance that you reach out to, there is a new memory location and generate a new memory cycle which would persist deallocations.
For class methods, for each time you reach out to the class/type methods you reach out to the same class/type method, and while you persist that class method, you won't be creating it over and over, it is only created once and done!
In objective-C (and C++) type methods:
When the app starts up, the system can fairly safely just pre-allocate ALL the instructions
for those type methods into memory along with their class pointers
so there’s little to no overhead calling those over and over and over again.
I imagine swift is doing the same thing
When you write logAction(), it implicitly means self.logAction(). (Methods are called on some instance; when you don't specify, it defaults to self.) So you are using self inside the closure, which means the closure captures self, and whether it captures a strong or weak reference has memory management implications.

swift method_exchangeImplementations not work

swift code is below:
func swizzleMethod()
{
let method:Method = class_getInstanceMethod(object_getClass(self), Selector("function1"))
self.function1()
let swizzledMethod:Method = class_getInstanceMethod(object_getClass(self), Selector("function2"))
method_exchangeImplementations(method, swizzledMethod)
self.function1()
}
func function1()
{
print("function1 log")
}
func function2()
{
print("function2 log")
}
it logs:
function1 log
function1 log
/////
my environment is swift based project, xcode7.2
This always run into the funtion1 method body, so I think it exchanged failed, this two method is in the same class, anyone know why?
I get the answer, add "dynamic" keyword in front of method name!!!
like this:
dynamic func function1()
{
print("function1 log")
}
dynamic func function2()
{
print("function2 log")
}
Reason:
Swift optimizes code to call direct memory addresses instead of looking up the method location at runtime as in Objective-C. so we need tell the code run treat it as Objective-C code.
Answer Detail:
Method swizzling is a technique that substitutes one method implementation for another. If you're not familiar with swizzling, check out this blog post. Swift optimizes code to call direct memory addresses instead of looking up the method location at runtime as in Objective-C. So by default swizzling doesn’t work in Swift classes unless we:
1. Disable this optimization with the dynamic keyword. This is the preferred choice, and the choice that makes the most sense if the codebase is entirely in Swift.
2. Extend NSObject. Never do this only for method swizzling (use dynamic instead). It’s useful to know that method swizzling will work in already existing classes that have NSObject as their base class, but we're better off selectively choosing methods with dynamic .
3. Use the #objc annotation on the method being swizzled. This is appropriate if the method we would like to swizzle also needs to be exposed to Objective-C code at the same time.
thanks to the article: 15 Tips to Become a Better Swift Developer

Benefits of using class func vs func vs no class declaration

Ok so I have a a bunch of helper functions in my project that I originally had in a class called Animate. I was wonder what are the benefits of declaring func vc class func.
Lets use this as an example class:
class Animate{
func moveView(...){
...
}
}
So I believe if I have a class func I don't have to instantiate the class as so.
Animate.moveView(...)
And if I just declare the function with func it would be:
Animate().moveView(...)
However if I don't declare the file as a class at all as so:
func moveView(...){
...
}
When I call the function it is just:
moveView(...)
With no indication where the code came from and it can be just used like this anywhere in the project.
What are the pros and cons of these three ways? Is not declaring a class bad practice? Or, is there some edge case that this is very useful? For example in my situation I have no need for a class since I am just creating helper functions and not an object.
Thanks in advance for any insight on this!
Ok. Instance methods vs class methods vs global methods.
(The term method and function are interchangeable. Method implies a function implemented by an object, so I tend to prefer the term method to the term function.)
An instance method is a method that is performed by instances of a class. You must have an instance of that class to talk to in order to invoke an instance method.
Instance methods have access to the instance variables of the object they belong to, so the object can save state information between calls. (In a networking class you could create multiple download objects, each of which manages an individual file download of a different file from a different URL, and each might have a different delegate it notifies when it's download is complete)
Class methods are invoked by the class itself, not by an instance. This can make it simple to invoke helper functions without having to manage an object to do that work for you. Since class methods don't talk to an instance of the class, they can't preserve different state information for each object. You might have a utilities class that performs localization functions on strings for example. The localization process is self-contained. You call a class function and pass in a string and the language you want it localized to, and it hands you back a result. No need to keep state between calls. Such a call might look like
let frenchString =
LocalizationUtils.localizeString("English String",
toLanguage: "French")
Global functions do not belong to any particular class. They are global to the entire module in which they are defined. They are similar to class functions, except that they are not specific to a particular class.
I agree with (and upvoted) #Duncan C's answer, but just thought I'd throw in a couple of other pros/cons.
I tend to like global functions over class methods because global functions don't clutter up my classes. I like to keep my classes lean and thin. The global functions can be kept in a separate file that I can copy and paste, or import, into a given project as I need them. So I might have a file in my project called AnimateHelperFunctions that is just global functions related to that class. A given project may only need a couple of them, or most of them, or those plus a couple more that I discover I need. I can delete the ones I don't use in a given project from the file so as to keep that file neat and trim.
I just think that global functions are more modular and encourage me to factor out single tasks for a single function - a good global helper function that does exactly one thing and does it perfectly can also sometimes be abstracted or made generic and used in other contexts as well. You might have a project sometime where you realize you don't need the class - you just need its helper function, and there it is.
I would prefer a hundred simple global functions that I can pick and choose from over a giant bloated class.
You can accomplish much the same thing with extensions, of course, and to some degree it is a matter of taste, as there is very little difference (any?) between class methods and global functions except that to use the class method you have to drag along the entire class.
Unlike global state, there isn't any danger in a global function. Sure, anyone can call it, but the same is true of class methods, and the global function can only operate on the arguments you pass to it.
For me, I use static or class methods to control class level properties or if I have to return customised instances of that particular class or struct. Like for example consider I have below struct.
struct Person {
let firstName: String
let lastName: String
}
Now if I am writing some test cases, where I need Person's instance initialized with a particular name John in many of my test classes, I can create a helper static method.
extension Person {
static func john() -> Person {
return Person(firstName: "John", lastName: "Appleseed")
}
}
let john = Person.john() // I could also create a static property instead, but it's a matter of personal choice and situation.
In above case, I could have made john as global function as well but for me, it will be very vague and not readable.
Another place I can think of where I prefer static method is returning count of cases for an enum.
enum Mood {
case happy
case angry
case lazy
case high
static func count() -> Int {
return 4
}
}
There are places, where I use global functions. I use global functions for logging.
func log(screenEvent name: String) {
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: screenName)
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
Internally, the method is using a sharedInstance, creating a global method makes it easily accessible everywhere in the project just like a print function which logs output in console, but this is logging in some custom service.
Some other global functions which I usually include in my projects are GCD helpers.
func delay(delay:Double, closure: dispatch_block_t) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
func backgroundTask(closure: dispatch_block_t) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), closure)
}
func mainThreadTask(closure: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), closure)
}
These function don't need any information about a class so it makes sense to make them global instead of wrapping them inside a class.
Regarding instance methods, as answered by #Duncan C, they are called on instances, when you want to maintain a state. Below example shows usage of both static and instance methods.
enum TapType {
case water
case beer
}
struct Tap {
let tapType: TapType
//static method
static func unlimitedBeer() -> Tap {
let beer = Tap(tapType: .beer)
beer.turnOn(forDuration: Float.greatestFiniteMagnitude)
return beer
}
//instance method: will do operation on a particular instance of `Tap`.
func turnOn(forDuration duration: Float) {
//implementation
}
}
let unlimitedBeer = Tap.unlimitedBeer()
You can always use convenience initializer to initialize an object with custom behaviour, but again, it's a matter of choice. In above example, I couldn't think of any convenience initializer which would give me unlimited beer.

What is the usecase for ignored parameters in Swift

In Swift, you can write the following:
func foo(_:Int) -> { return 1 }
Where the underscore is an ignored parameter. I only know this because of the documentation, but cannot think of ANY usecase on why you would even do this. Am I missing something?
Ignoring parameters (or members of a tuple, which are pretty close to the same thing) makes sense when:
You're overriding a superclass function or implementing a function defined by a protocol, but your implementation of that function doesn't need one of the parameters. For example, if you hook app launching but don't need a reference to the shared UIApplication instance in that method:
override func application(_: UIApplication!, didFinishLaunchingWithOptions _: NSDictionary!) -> Bool { /* ... */ }
You're providing a closure (aka block in ObjC) as a parameter to some API, but your use of that API doesn't care about one of the parameters to the closure. For example, if you're submitting changes to the Photos library and want to throw caution to the wind, you can ignore the success and error parameters in the completion handler:
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
// change requests
}, completionHandler: { _, _ in
NSLog("Changes complete. Did they succeed? Who knows!")
})
You're calling a function/method that provides multiple return values, but don't care about one of them. For example, assuming a hypothetical NSColor method that returned components as a tuple, you could ignore alpha:
let (r, g, b, _) = color.getComponents()
The reasoning behind this is that it makes your code more readable. If you declare a local name for a parameter (or tuple member) that you don't end up using, someone else reading your code (who could well be just the several-months-later version of yourself) might see that name and wonder where or how it gets used in the function body. If you declare upfront that you're ignoring that parameter (or tuple member), it makes it clear that there's no need to worry about it in that scope. (In theory, this could also provide an optimization hint to the complier, which might make your code run faster, too.)
Perhaps you're overriding a method and your override ignores one of the parameters? Making it clear that you're ignoring the parameter saves future coders from having to look through your code to work out that it's not using the parameter and makes it clear that this was intentional. Or maybe it's to create some sort of Adapter pattern where you make it clear that one of the parameters is being ignored.