In Swift, constants are indicated by let
, which means value would not be changed, while variables are indicated by var
, which will be changed later on. This is a very efficient way to optimize codes and to enhance memory management. The concept is very simple and I had no problems in most cases. I got several times by giving hints to convert variables to let when they are not changed. I like this.
Variable Parameters in Swift func
In Swiftfunc
, parameters by default are constants, even they are collection objects. I had a case that I have to make some changes after my codes converted from ObjC to Swift.- - (void) encodeObject:(id<NSCoding> object
- withKey: (NSString *) key
- toDirctionary: (NSMutableDictionary *)wrappers {
- NSFileWrapper *aWrapper;
- ...
- [wrappers setObject:aWrapper forKey:key];
- }
Note
The parameter is a type of mutable dictionary. As a result, an object can be added to the dictionary within the method.
The parameter is a type of mutable dictionary. As a result, an object can be added to the dictionary within the method.
However, the default parameter would generate a compile error in Swift codes. It complains that the parameter is a let constant! I have to change the parameter with inout attribute to make the parameter as variable, not a constant.
- func encodeObject(object : AnyObject,
- withKey key : String,
- inout toDirctionary wrappers : [String : NSFileWrapper]) {
- let aWrapper = NSFileWrapper(...)
- ...
- wrappers.updateValue(aWrapper forKey:key)
- }
Throw Errors
To convert exception/errors throw from a method in ObjC, the syntax of
func
in Swift is much more clear and simplified.For example, the following method in ObjC includes a possible error generated from the method call
- @implementation MyClass
- ...
- - (id) mapToSomethingForName:(NSString *)aName error:(NSError *__autoreleasing *)outError {
- ...
- }
- @end
The corresponding Swift codes are as follows.
- enum MyClassError : ErrorType {
- case InvalidContent
- case EmptyContent
- }
- class MyClass {
- func mapToSomethingByName(aName: String) throws {
- if (...) { // Invalid cases or use guard (...) else {...}
- throw MyClassError.InvalidContent
- }
- ...
- }
- }
Note
I added a struct for error types at the beginning and throw errors in the
I added a struct for error types at the beginning and throw errors in the
func
in case of invalid.To handle errors in Swift is much clean and simple. To ignore errors thrown, the following is an example.
- let x = try? instance.methodWithErrors()
- if x == nil {
- ...
- }
To catch errors, the following is another example.
- do {
- let x = try instance.methodWithErrors()
- ...
- }
- catch let error as NSERROR! {
- logger.debug(){
- return String(format: "error: \(error.localizedDescription)")
- }
- }
References
- StackOverFlow QA: Setting an NSManagedObject relation in Swift
- Apple Developer Site: Migration Your Objective-C Code to Swift
0 comments:
Post a Comment