When using Swift, up to now, I am always dealing with classes and their methods.
Is it also possible to have plain functions outside of any class, and group them together in a file MyFunctions.swift?
I would be surprised if the answer was not YES.
But since what I tried failed, I would like to know how I can refer to this file and its functions when I need it.
import MyFunctions.swift did not work.
Related
I would like to Verify that an expected method is called with the correct parameters in Swift in unit-testing. This was very easily done in Objective-C using the OCMock framework. You could do a combination of partialMocking and running OCMExpect/Verify to assert code paths with the right parameters were being called. Any idea how to do something like this in Swift?
Swift doesn't support reflection, so traditional mocking libraries aren't feasible. Instead, you need to create your own mock. There are at least two approaches to do this.
Create a testing subclass of the class under test. This is partial mocking. Avoid this if possible.
Use an interface instead of a class. Create a testing implementation of the interface.
Hand-crafted mocks aren't hard. You want to
Count the number of calls to a method
Capture its arguments
Simulate its return value
It is a lot of boilerplate. There are libraries out there that can auto-generate this code.
I have a few ViewControllers in my storyboard. Lets call them:
SB_VC1
SB_VC2
SB_VC3
I have one ViewController.swift file. Within that file, I have multiple ViewController classes, let's call them:
VC_Class_1
VC_Class_2
VC_Class_3
Each VC_Class is used as its corresponding SB_VC's class. Each VC_Class has different code, tailored to what I want the SB_VC to do.
These are all on the same hierarchy level, none is a subview of another. They each inherit from UIViewController and import UIKit and CoreData.
Question:
Part 1
Is keeping the code for all three classes in one file wrong? Should I be creating a new file for each VC_Class? Or is this just a matter of personal preference? If it is not preference and is clearly wrong, what is the problem it causes?
Part 2
If all three do have a little bit of overlap, in terms of each having a few functions that are the same, should I create a fourth class and call it something like "ToolBox.swift" and use it to call those functions? Or would it be better to have VC_Class_1 house those functions and make VC_Class_2 and VC_Class_3 inherit from VC_Class_1?
Generally, it is a matter of preference. Though I'd highly advise against it. Large files are harder to maintain, and it will take you longer and longer to find pieces of code you need. It will also be easier for other people to read and undestand your code.
As for the common code, it depends on its nature. You can either create a Toolbox class or a superclass from which you will inherit.
It's possible to add extensions to existing Swift object types using extensions, as described in the language specification.
As a result, it's possible to create extensions such as:
extension String {
var utf8data:NSData {
return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
}
However, what's the best naming practice for Swift source files containing such extensions?
In the past, the convention was to use extendedtype+categoryname.m for the Objective-C
type as discussed in the Objective-C guide. But the Swift example doesn't have a category name, and calling it String.swift doesn't seem appropriate.
So the question is: given the above String extension, what should the swift source file be called?
Most examples I have seen mimic the Objective-C approach. The example extension above would be:
String+UTF8Data.swift
The advantages are that the naming convention makes it easy to understand that it is an extension, and which Class is being extended.
The problem with using Extensions.swift or even StringExtensions.swift is that it's not possible to infer the purpose of the file by its name without looking at its contents.
Using xxxable.swift approach as used by Java works okay for protocols or extensions that only define methods. But again, the example above defines an attribute so that UTF8Dataable.swift doesn't make much grammatical sense.
I prefer having a + to underline the fact it contains extensions :
String+Extensions.swift
And if the file gets too big, you can then split it for each purpose :
String+UTF8Data.swift
String+Encrypt.swift
There is no Swift convention. Keep it simple:
StringExtensions.swift
I create one file for each class I'm extending. If you use a single file for all extensions, it will quickly become a jungle.
I prefer StringExtensions.swift until I added too much things to split the file into something like String+utf8Data.swift and String+Encrypt.swift.
One more thing, to combine similar files into one will make your building more faster. Refer to Optimizing-Swift-Build-Times
Rather than adding my comments all over the place, I'm surfacing them all here in one answer.
Personally, I take a hybrid approach that gives both good usability and clarity, while also not cluttering up the API surface area for the object that I'm extending.
For instance, anything that makes sense to be available to any string would go in StringExtensions.swift such as trimRight() and removeBlankLines().
However, if I had an extension function such as formatAsAccountNumber() it would not go in that file because 'Account Number' is not something that would naturally apply to any/all strings and only makes sense in the context of accounts. In that case, I would create a file called Strings+AccountFormatting.swift or maybe even Strings+CustomFormatting.swift with a formatAsAccountNumber() function if there are several types/ways to actually format it.
Actually, in that last example, I actively dissuade my team from using extensions like that in the first place, and would instead encourage something like AccountNumberFormatter.format(String) instead as that doesn't touch the String API surface area at all, as it shouldn't. The exception would be if you defined that extension in the same file where it's used, but then it wouldn't have it's own filename anyway.
If you have a team-agreed set of common and miscellaneous enhancements, lumping them together as an Extensions.swift works as Keep-It-Simple first level solution. However, as your complexity grows, or the extensions become more involved, a hierarchy is needed to encapsulate the complexity. In such circumstances I recommend the following practice with an example.
I had a class which talks to my back-end, called Server. It started to grow bigger to cover two different target apps. Some people like a large file but just logically split up with extensions. My preference is to keep each file relatively short so I chose the following solution. Server originally conformed to CloudAdapterProtocol and implemented all its methods. What I did was to turn the protocol into a hierarchy, by making it refer to subordinate protocols:
protocol CloudAdapterProtocol: ReggyCloudProtocol, ProReggyCloudProtocol {
var server: CloudServer {
get set
}
func getServerApiVersion(handler: #escaping (String?, Error?) -> Swift.Void)
}
In Server.swift I have
import Foundation
import UIKit
import Alamofire
import AlamofireImage
class Server: CloudAdapterProtocol {
.
.
func getServerApiVersion(handler: #escaping (String?, Error?) -> Swift.Void) {
.
.
}
Server.swift then just implements the core server API for setting the server and getting the API version. The real work is split into two files:
Server_ReggyCloudProtocol.swift
Server_ProReggyCloudProtocol.swift
These implement the respective protocols.
It means you need to have import declarations in the other files (for Alamofire in this example) but its a clean solution in terms of segregating interfaces in my view.
I think this approach works equally well with externally specified classes as well as your own.
Why is this even a debate? Should I put all my sub classes into a file called _Subclasses.swift. I think not. Swift has module based name spacing. To extend a well known Swift class needs a file that is specific to its purpose. I could have a large team that creates a file that is UIViewExtensions.swift that express no purpose and will confuse developers and could be easily duplicated in the project which would not build. The Objective-C naming convention works fine and until Swift has real name spacing, it is the best way to go.
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:).
I have some functions that work on strings for some business logic.
Should I put them as normal functions in helper files and access them as:
custom_function(my_var)
Or is it better to extend the string class and access them as:
my_var.custom_function
I find extending built-in objects like that confusing. You move from project to project and wonder why you cannot do my_var.foo only to realize that foo was a function that your colleague wrote.
Just imagine you added extension methods indiscriminately. Now you have to copy a block of code from one project to another and spend time scratching your head about the extension methods.