Practical application of backticks in Swift - ios

From this document:
To use a reserved word as an identifier, put a backtick (`) before and after it.
I'm curious about the practical application of this. When would you actually want to name something `class`, `self`, etc.?
Or, relatedly, why did the designers of Swift allow this, rather than just forbidding us from using reserved words as identifiers?

The most important usage is the interaction with other languages that have different keywords.
From Swift you can call C and Obj-C functions.
Now, consider for example that you need to call a C function called guard. However, that's a keyword in Swift, therefore you have to tell the compiler that you don't want to use it as a keyword but as an identifier, e.g.:
`guard`()
There are multiple keywords in Swift that are widely used as method/function names, e.g. get and set. For many contexts Swift is able to figure out the difference but not always.

In some cases using guard give us nice example for this purpose.In such scenario I need check self variable life time if not exist anymore (current controller deallocated) I don't want to execute rest of code.
guard let `self` = self else {
return
}

Related

why Objective-C convert to swift wrong

why

-(void)addSimpleListener:(id<XXSimpleListener>)listener
convert to swift look like this:
func add(_ listener: XXSimpleListener?) {
}
but change the method to this

-(void)addSimpleListener:(id<XXSimpleListening>)listener

and it will convert to this
func addSimpleListener(_ listener: XXSimpleListening?){
}
Xcode (or whatever tool you are using to do the conversion) is merely following Swift API guidelines. Specifically:
Omit needless words. Every word in a name should convey salient information at the use site.
More words may be needed to clarify intent or disambiguate meaning, but those that are redundant with information the reader already possesses should be omitted. In particular, omit words that merely repeat type information.
In the first case, the words SimpleListener in addSimpleListener is repeating the type of the parameter, so they are removed from the method name. However, in the second case, SimpleListener and SimpleListening does not look the same to whatever tool you are using, so it thinks that SimpleListener should be kept.
In my (human) opinion though, I think the method should be named addListener, because:
Occasionally, repeating type information is necessary to avoid ambiguity, but in general it is better to use a word that describes a parameter’s role rather than its type.
Listener is the role of the parameter.

A better way to do Language in swift 3

i am currently doing an app that has language change feature. However,for every string that i wish to have changes made to when a different language is selected, i have to implement the following code
"Hello world".localize()
However, as the app gets bigger, the code become very messy in the way that all the strings in their respective view controllers have this .localize() append to it.
Is there a way where i can do this .localize() thing in one central place?
EDIT: I tried to create a Strings.swift file and put all the strings inside. I did something like this.
static let relevantString = "hello world".localize()
and then in the view controllers i call
let myString = relevantString
However, this does not well. The strings will only change after i terminate the app and restart it.
Your attempt to use static let fails to produce the dynamic behaviour you want simply because you used a constant. You could use a read only computed property instead, something like:
var relevantString : String { return "Hello World".localize() }
As an alternative, as you seem to be more concerned over the clutter, you could define a simple prefix or postfix unary operator which called localize() on its argument. Swift allows a number of symbols to be used as operators so the operator can just be a single character. For example you could define, say, § so that §"Hello World" produced a localised string.
HTH

Checklist for migrating to idiomatic Swift 2 (AKA where is the Swift 2 transition guide)?

I've been trying to locate a transition guide for Swift 2, in particular things developers should be aware of when migrating Swift 1/1.2 codebases over to Swift 2. Obviously you have the migration assistant in Xcode, but that only really covers the donkey work and not the stuff that requires a bit more intelligent thought.
Based on the resources I was able to find on Swift 2, I've put together the following checklist:
try/catch/throw error handling - to be used for recoverable errors; revise error handling code accordingly. In particular, check all uses of NSError and calling back to delegates to report recoverable errors.
Use enums conforming to ErrorType to define your own meaningful errors.
Use #available for accessing newer platform APIs - check API use against app Deployment Target and revise accordingly
protocol extensions - move as much code as possible into these to aid re-use. In particular refactor Global Functions into protocol extensions.
nullability annotations & generics - remove redundant optional bindings and type castings
Use do { } to control scope and free large resources early
Move old do { ... } while loops to repeat { } (to remove ambiguity and improve readability)
Use guard to return early and avoid excessive indentation
Use defer for cleanup code like closing files etc.
Use Option Sets rather than OR-ing values together (e.g. viewAnimationOptions = [.Repeat, .CurveEaseIn, .TransitionCurlUp])
Review public accessor specifiers which were previously only required to support testing. Use #testable and import MyApp instead.
Move single-case switch statements to the new if case .MyEnumCase(let value) = bar() where value != 42 { doThing(value) }
Use "for ... in" filtering to clean up for loops containing if filtering statements e.g. for value in mySequence where value != "" { }
native support for C function pointers - provide using closures or global functions (do not capture local context when doing so)
fix any new let/var warnings
fix any unused variable warnings
Failable initializers can now return nil before calling super.init - remove any previous workarounds required. Designated initializers still have to initialize all stored properties before returning nil however.
Sources:
https://developer.apple.com/swift/blog/?id=29
https://developer.apple.com/swift/
https://developer.apple.com/library/prerelease/ios/releasenotes/DeveloperTools/RN-Xcode/Chapters/xc7_release_notes.html#//apple_ref/doc/uid/TP40001051-CH5-SW1
https://developer.apple.com/videos/wwdc/2015/?id=106
http://www.raywenderlich.com/108522/whats-new-in-swift-2
What have I missed?
Part of the problem is that Swift 2 has continued to evolve past WWDC. So even this year's WWDC videos are already potentially out of date, or at least not the whole story.
Unfortunately, at this time there is no official "transition guide" from Apple as such.
The Swift Programming Language (Swift 2) is always updated by Apple whenever they release a new version of Swift and is therefore one of the best sources for up to date information about Swift 2 (or later). There is plenty of explanation and example code of the entire language, not just the changes, but this is definitely at least on of the best sources for the information you are looking for right now.

Why do all methods have the same name in delegate?

i'm starting with Swift by developing a simple application with a tableView, a request to a server and a few things more. I realized that every method inside UITableViewDelegate protocol is named in the same way (i guess it might be the same with other protocols) and the differences are made by changing the parameters passed to those methods (which are called "tableView" by the way).
I was wondering why Apple would do something like this, as it's a bit messy when i try to implement method from this protocol, as i can't start typing "didSele..." just to autocomplete with "didSelectRowAtIndexPath"; instead i have to type "tableView" to get a list of all available methods and manually search for the one whose second parameter is "didSelectRowAtIndexPath".
Everything's working fine, but just trying to know WHY could this be done this way.
Thank you so much in advice :)
PS: There's a screenshot about what i'm saying:
Swift is designed to be compatible with Objective-C. After all, almost all existing OS X and iOS APIs are in Objective-C and C (with a bit of C++ code here and there). Swift needs to be able to use those APIs and thus support most Objective-C features one way or the other. One of the most important features of Objective-C is how method calls are made.
For example, in C, a function with 3 arguments is called like this:
foo(1, "bar", 3);
You don't know what the arguments are supposed to be. So in Objective-C, the arguments are interleaved with the method name. For example, a method's name might be fooWithNumber:someString:anotherNumber: and it would be called like:
[anObject fooWithNumber:1 someString:#"bar" anotherNumber:3];
Swift now tries to be compatible with this Objective-C feature. It thus supports a form of named arguments. The call in Swift would look like:
anObject.foo(number:1, someString:#"bar", anotherNumber:3)
Often Swift method definitions are written so that you don't need to explicitly name the first argument, like:
anObject.foo(1, someString:#"bar", anotherNumber:3)
If you look up the UITableViewDelegate protocol documentation and select Objective-C you can see that all of these methods start with tableView: to designate the sender, but from then on they are very different. The list you've cited is the result of the conversion from Objective-C to Swift naming convention.
It is just naming conventions. It is the same in Objective-C. You can have a look to this page. Without these conventions it would be a complete mess.
The method name is not only the first word but also the public names of the parameters.
E.g. it the method name is not tableView() but tableView(_:didSelectRowAtIndexPath:).

Using #properties for all instance variables coding standards

My coding team has chosen implement a coding standard of using #property's for all instance ivars. For publicly facing things, we of course define them in our .h files, but for our private things, we define them in the .m file in an interface above our implementation.
Does it matter if I refer to them as self.myvar = whatever or as [self setMyvar:whatever]? It doesn't seem to matter at all to me, and there seems to be a great deal of mixing one way or the other in our code base.
self.myvar = whatever
is syntactic sugar for
[self setMyvar:whatever]
They're exactly the same thing. No difference at all.
As others have indicated, foo.bar and [foo bar] are equivalent (save for the additional type requirements on the former, but that is minor).
FWIW, our team decided to eschew the dot syntax completely. The motivation is to avoid ambiguity; a message send always looks like a message send and .s are always used to access structure members.
We also limit our use of #{} and #[] to the creation of collections only. All accesses are done via indexOfObject:, objectForKey:, etc...
As well, we use ARC everywhere save for a couple of border files that sit between ObjC and C++. And we have the static analyzer turned on for all DEBUG builds and all warnings are treated as hard errors. We've also turned on just about every compiler warning that is practical (there are some that simply aren't practical to use).
There is plenty of similar questions.
In our coding standards, we don't care about using dot notation or method to access the property. We even sometimes use dot notation for methods which are not formally declared as property because with library methods it's sometimes hard to know without checking the docs and it doesn't make a difference.
It never makes sense to forbid direct method calls (hard to enforce).
I saw coding standards forbidding the dot notation.
In general I tend to prefer dot notation because it enables me to split assignments into visually separated parts, e.g.
self.a = x;
against
[self setA:x];
The second just seems less readable to me but it's a matter of personal taste.
On the other hand, sometimes it's easier to use the method directly, e.g. when you have the object as an id and you would have to cast to use the dot notation.
I think that mixing both is a good solution. Choose the one that will increase the readibility at the given place.
self.myVar = x is actually compiled to [self setMyVar: x];. There's no run-time difference.
However; for ease of code readability, I'd advise sticking with one scheme or the other. If you've already had properties enforced, it'd be better to leave everything in the dot notation - if for no other reason than because this allows your code to be more easily searched.

Resources