Making a type is not a dream-vernacular swift type creation

Source: Internet
Author: User


Translation: Old code team translation Group-tyrion proofreading: Old Code team translation Group-oberyn


This page contains content:


    • Custom Prototypes
    • Implementing default values
    • Support for Basic Boolean initialization
    • supports bool type judgment
    • Support the types of various factions that are compatible
    • Perfecting the Bhurki system of Ocbool


Small partners, the type of bool in Swift has a very important grammatical function, and support the entire SWIFT system in the logical judgment system, after the old Code of Research and learning, bool type itself is actually the base of the Boolean type encapsulation, the small partners may bite the finger to ask the old code, How can a bool type, a Boolean type, differ in that the former is an enumeration-based combination type, while the latter is the base type, with only two true and false.





Custom Prototypes


Pick up the old code according to the idea of bool to create a ocbool type, to let the small partners know how to play in Swift. Let's look at the definition of Ocbool first.


The code examples are as follows:
 
 
enum OCBool{
case ocTrue
case ocFalse
}
Attention:
    • Lines 2nd and 3rd in the code can be merged into a single line of writing, as Apple's official blog has written
    • The name in the code needs to be noted: Ocbool is a type name, so the first letter must be capitalized, and the Octrue and Ocfalse in the case are small with the first letter lowercase.




Implementing default values


OK, we gave a pretty definition, but according to the traditional language experience, the bool value is false by default, so our ocbool should do the same, we use the type extension technique to add this default feature:


extension OCBool{
     init(){ self =.ocFalse
     }
}
Attention:
    • Line 1th in the code: extension keyword, very powerful, small partners can create a lot of fun things, suggest you go to GitHub to see a project called "Swiftz", it will extend to the extreme.
    • Line 3rd in the code: Self =. Ocfalse syntax, just getting started small partners are confused, why there are strange dot syntax, because Daniel Chris in Swift added the type of intelligent inference function, in the Apple blog, referring to the "Context" concept, that is the meaning, Because this line of statements is in the enumeration Ocbool, whose context is the definition of ocbool, the compiler certainly knows. Ocfalse is Ocbool.ocfalse, so here is the direct syntax, very neat. Now we can use this type of bool using the following method.
The code examples are as follows:
 
 
var result:OCBool = OCBool()
var result1:OCBool = .ocTrue




Support for Basic Boolean initialization


As mentioned in the code above, we can only assign values by type or enumeration items, which is the use of combination types, but in the days of coding we always want to deal directly with True,false, that is, we want to do this, the code example is as follows:


var isSuccess:OCBool = true


If the small partners use this directly, the following error will occur:


/Users/tyrion-OldCoder/Documents/Learning/BoolType/BoolType/main.swift:30:24: Type ‘OCBool‘ does not conform to protocol ‘BooleanLiteralConvertible‘


The reason the compiler growled is that our type doesn't follow the "Boolean literal conversion protocol," and then it fixes the problem,


The code examples are as follows:
 
 
import Foundation

println("Hello, World!")

enum OCBool{
    case ocTrue
    case ocFalse
}

extension OCBool: BooleanLiteralConvertible{
static func convertFromBooleanLiteral( value: Bool) ->OCBool{
    return value ? ocTrue : ocFalse
    }
}

var isSuccess:OCBool = true
Attention:
    • The 11th line in the code is the focus, my type Ocbool support the Booleanliteralconvertible protocol, what the hell is the Association, the small partners in the Xcode Code Editor, hold down the command key, Then click on the booleanliteralconvertible protocol name in line 11th to enter its definition,

      It is defined as follows:
       
      
       
      
      protocol BooleanLiteralConvertible {
        typealias BooleanLiteralType
        class func convertFromBooleanLiteral(value: BooleanLiteralType) -> Self
      }
    • There is a class method in this definition, convertfrombooleanliteral, whose argument is the Booleanliteraltype type, which is the bool type I passed in, and the return value is the type itself that implements this protocol, in our Ocbool type, The return value is the Ocbool itself. With this definition, we can directly initialize the boolean literal to the Ocbool type directly.




supports bool type judgment


The Little friends are restless and must think about how I use it to make logical judgments, so if you write like this,


The code examples are as follows:
var isSuccess: OCBool = true

if isSuccess {
     println ("Old code, please eat hot pot!")
} 


You will never eat the old hot pot, because here the compiler will roar:


/Users/tyrion-OldCoder/Documents/Learning/BoolType/BoolType/main.swift:27:4: Type ‘OCBool‘ does not conform to protocol ‘LogicValue‘


Ocbool now can only be initialized with bool type, but not directly return bool type, small torches also remember in the "old code said programming of the vernacular Swift lakes and rivers," old code repeatedly mentioned, mother no longer worry about our if a = 1{} notation, because the equal sign does not support the return of the value, So the If judgment is followed by a condition that must have a return value, Ocbool No, so the compiler cries. We solve this problem.


The code examples are as follows:
import Foundation

println ("Hello, World!")

enum OCBool {
     case ocTrue
     case ocFalse
}

extension OCBool: BooleanLiteralConvertible {
static func convertFromBooleanLiteral (value: Bool)-> OCBool {
     return value? ocTrue: ocFalse
     }
}

extension OCBool: LogicValue {
     func getLogicValue ()-> Bool {
         var boolValue: Bool {
         switch self {
         case .ocTrue:
             return true
         case .ocFalse:
             return false
             }
         }
         return boolValue
     }
}

var isSuccess: OCBool = true

if isSuccess {
     println ("Old code, please eat hot pot!")
} 
The results of the operation are as follows:
with exit code: 0
Attention:
    • If the small partners are now using beta version of Xcode, note Apple official blog, in the code line 17th if it is wrong under Xcode Beta4, here is the protocol, Logicvalue instead of Booleanvue, so remember to see the error is good habit.
    • Note The code line 34th, the perfect support if judgment, and the output is "old code please eat Hot pot", old code is also said, please do not take seriously.




Support the types of various factions that are compatible


Small partners, risk, the door faction, old code has its own type of ocbool, may have their own ssbool type of Songshan Shaolin, and even Guo Meimei may have their own mmbool type, so ocbool must be able to recognize these types, these various types of different factions, As long as support Logicvalue protocol, should be able to be recognized, see old code how to do,


The code examples are as follows:
extension OCBool {
     init (_ v: LogicValue)
     {
         if v.getLogicValue () {
             self = .ocTrue
         }
         else {
             self = .ocFalse
         }
     }

}

var mmResult: Bool = true
var ocResult: OCBool = OCBool (mmResult)

if ocResult {
     println ("Old code has no money, Guo Meimei invited you to eat hot pot!")
}
The result of the code operation is as follows:
with exit code: 0


Pretty! Our Ocbool type now supports all of the logic variable initializations.


Attention:
    • The code in line 2nd: "_" under the use of the bar, this is a powerful cockroach, in order to shield the external parameter name, so the small partners can directly: var Ocresult:ocbool = Ocbool (Mmresult) instead of: Var ocresult:o CBool = Ocbool (V:mmresult), the little friends were stunned! There is no external parameter name in this init function, remember the old code in the book said no, the initialization function of Swift uses the internal parameter name by default, as the external parameter name.




Perfecting the Bhurki system of Ocbool:


Small partners, the value of bool type is in a variety of judgments, such as ==,!=, &,|,^,!, and a variety of combinatorial logic operations, we ocbool also have these functions, otherwise it will be genetic defects, and see how the old code to achieve:


extension OCBool: Equatable {
}

// Support equality judgment operator
func == (left: OCBool, right: OCBool)-> Bool {
    switch (left, right) {
    case (.ocTrue, .ocTrue):
            return true
    default:
        return false
    }
}
// Support bit and operator
func & (left: OCBool, right: OCBool)-> OCBool {

    if left {
        return right
    }
    else {
        return false
    }
}
// Support bit or operator
func | (left: OCBool, right: OCBool)-> OCBool {

    if left {
        return true
    }
    else {
        return right
    }
}

// Support bit XOR operator
func ^ (left: OCBool, right: OCBool)-> OCBool {
    return OCBool (left! = right)
}
// Support negation operator
@prefix func! (a: OCBool)-> OCBool {
    return a ^ true
}
// Support combined sum operator
func & = (inout left: OCBool, right: OCBool) {
    left = left & right
}

var isHasMoney: OCBool = true
var isHasWife: OCBool = true
var isHasHealty: OCBool = true
var isHasLover: OCBool = true

isHasMoney! = isHasHealty
isHasHealty == isHasMoney
isHasWife ^ isHasLover
isHasWife =! isHasLover

if (isHasMoney | isHasHealty) & isHasHealty {
    println ("Life winner, just like the old code!")
} else
{
    println ("The hardest thing in life, people do n’t spend money when they die, the hardest thing in life is that people live, money is gone!")
} 


Well, to here, the Thunder woke up outside the window of the old yards, should now go to dinner, the above old code to show you if you create a type of their own, remember the old code example is in Xcode6 Beta4 under test, as for the Beta5 change has not been involved, small partners to practice, Later, various custom types are based on this idea. And this chapter is not the original old code, the old code seriously read the official Apple blog, and their practice summary, if the small partners to pay the strength of the breast or do not understand, please find degrees Niang Google, or do not understand please to old code official Weibo: http://weibo.com/u/5241713117 Roar.



This article is translated from Apple Swift blog:https://developer.apple.com/swift/blog/?id=8



Making a type is not a dream-vernacular swift type creation


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.