Title: "Why coding like This--optional secret"
Date:2015-08-12 00:21:16
Categories: "Why coding like this"
Tags: [Swift advanced]
Optional Secret
Topic 1:
Please simply write out the declaration of the optional type, as well as several unpacking forms.
Example:
/// Several ways of declaringvarOptionalvalue:optional<int>//Full declaration note <> are all typesvarOptionalvalue2:int?//Display statementvaroptionalvalue3:int!//Implicit declaration/// several unpacking/// Demo valuevarSomeoptional:int? =3 //Initial value is 3/// 1. By judging whether or not it is equal to nil, the package can only guarantee security.ifSomeoptional! = nil{println ("value is \ (someoptional!)")}// 2.if-let bindingif Let value= someoptional{println ("value is \ (value)")}/// 3.?? Unpackingprintln"value is \ (someoptional?? 2) ")/// 4.swift2.0 new matching mode but in Xcode7 environment//New use enumeration match is the enumeration matching methodif Case. Some ( Letx) = Someoptional{println ("someoptional value is \ (x)")//If the nil condition does not output anything because the match is some!}//New use optional pattern matchif Case LetX? = Someoptional{println ("someoptional value is \ (x)")//Do not need to unpack X and stuff like that}
The fourth method is supported only under the XCODE7 environment and swift2.0 syntax. For more syntax changes, click here. For optional type unpacking please click here. For more basic syntax, see the official documentation.
Why coding?Proposition One
Given a variable, there are two cases when the program is running: There is no value, there is a value, equals X. Design a type to encapsulate this situation.
Ideas
In fact, there are no ideas, but the proposition that there are two situations, let me think of the enumeration (of course, more affected by Swift itself), Swift enumeration is very powerful, if you are novice, it is recommended to read the Official document enumerate chapter. Ok, the next step is to start designing the enumeration type in the Code section.
Code
Disclaimer: Step by step, you will find it very interesting.
enum MyOptional{ case None case Some}
According to the idea we have written the enumeration type, None
indicating that there is no value, there is a value, it is Some
not difficult to find the type of the definition there are some drawbacks, first of all our variables may be int,string,double, and this is not explicitly covered, followed by the value of the case is not associated with the actual value. Modify the custom enumeration according to the above points, as follows:
enum MyOptional<T>{ case None case Some(T)}//特别申明 这种方式在swift1.2下是不支持的 由于和本节无关 就不扯了 但是我们自定义一个类来包裹//貌似swift2.0是支持的....enum Result<T>{ case Success(T) case Failure(NSError)}
We cleverly used generics to match any type, and the presence value x is associated with the associated values of the enumeration. For better use we will add the initialization method declaration, the code is as follows:
Enum Myoptional<T>{ Case None CaseSome (T)//Generate an optional type with valueInit (_ Value:t) { Self = .Some (Value)}//nilInit (_ Nilliteral: ()) { Self = .None}}//my Optional ValuevarMyvalue:myoptional<Int> =Myoptional (2)varMynil:myoptional<Int> =Myoptional ()//Test Our crappy optional typeSwitch myvalue{ Case .None: println ("nil") Case .Some ( Letx): println ("value is \ (x)")}switch mynil{ Case .None: println ("nil") Case .Some ( Letx): println ("value is \ (x)")}
It looks good, but there is a gap between the optional types in swift and the above just lets you understand the optional types from the other side.
Proposition Two
Unpacking operators in optional types can ??
you do it yourself? Customize a -->
unpack operator!
Ideas
The unpacking behavior is nothing more than a few, we just overloaded the operator.
Code
infix operator- -> {associativity Right precedence 110 } func?? <t> (optional:t?,defaultvalue:t) -> t{// I chose if -let unpacking if let x = optional{return x}else {return DefaultValue}}// test var oo:int? = Nillet r = oo--> 5 //Output 5
First we still use generics to declare, then pass in an optional type optional, which may have a value =x
, may not have a value ( nil
), and will be used without a value defaultValue
.
But considering that defaultValue
sometimes it's not a value, maybe a closure, and feedback a T
value. Therefore, the function is modified slightly.
// code two func --> <t> ( Optional:t?,defaultvalue: ()->t) -> t{// I chose if -let unpacking if let x = optional{return x} else {return defaultvalue ()}}var rr = OO--> {7 } // return 7
We can see that the defaultValue
closure must be clearly expressed in the use of the package {}
. However, with a single value case, the feeling of the {}
package is twisted, so we also need a little change, the use of autoclosure
features to solve the problem, the final code is as follows:
Infix operator- -{associativity Right precedence the}//This is very important func- -<T> (optional:t,@autoclosure defaultvalue: ()->t)t{//I chose it.if- LetUnpackif Letx = optional{returnX}Else{returnDefaultValue ()}}varRRR = oo- - 5+4can see the automatic5+4As a closure to dry.
Summary: The optional type is not very difficult, but for beginners is still a barrier, after all, there is no such concept, multi-code code is naturally familiar. Unconsciously written late into the night, wash and sleep.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Why Coding like this-------optional the secret of writing an optional type class