Swift type creation customization a type of detail _swift

Source: Internet
Author: User

Friends, the Bool type in Swift has very important grammatical functions and supports the logical judgment system in the entire Swift system. After the research and learning of the old code, the Bool type itself actually encapsulates the basic Boolean type. We may bite our fingers and ask the old code, why is the Bool type, and the Boolean type, the difference is that the former is a combination type based on enumeration, and the latter is the basic type, there are only two types of true and false.

#### Custom prototype

Then take the old code to create an OCBool type based on Bool's ideas, to let the little friends understand how to play in Swift.

Let us first look at the definition of OCBool.

##### The code example is as follows:
Copy the code The code is as follows:

enum OCBool {
case ocTrue
case ocFalse
}

#####note:
The second and third lines in the code can be combined into one line and written, as written by Apple's official Blog
Note that the naming in the code: OCBool is the type name, so the first letter must be capitalized, and the ocTrue and ocFalse in the case are small types, so the first letter is lowercase.

#### Realize the default value

Yes, we gave a beautiful definition, but according to the experience of traditional languages, the Bool value is false by default, so our OCBool should be the same. We use type extension technology to add this default feature:
Copy the code The code is as follows:

extension OCBool {
     init () {
             self = .ocFalse
     }
}
#####note:

● Line 1 in the code: The extension keyword is very powerful, and friends can create many interesting things through this. I suggest you go to Github to see a project called "Swiftz", which will use the extension to the extreme.

● The third line in the code: self = .ocFalse syntax, the newcomers are very confused, why there is a strange dot syntax, because Daniel added type intelligent inference function in Swift, in the Apple Blog, mention When it comes to the concept of "Context", this is what it means, because this line of statement is enumerated in OCBool, and its context is the definition body of OCBool. Of course, the compiler knows that .ocFalse is OCBool.ocFalse. .

Now we can use this Bool type using the following method.

##### The code example is as follows:
Copy the code The code is as follows:

var result: OCBool = OCBool ()
var result1: OCBool = .ocTrue
#### Support basic Boolean initialization

As mentioned in the above code, we can only assign values by type or enumeration item, which is the use of combined types, but in the days of coding, we always want to directly deal with true and false, that is, we want to do this

The code example is as follows:
Copy the code The code is as follows:

var isSuccess: OCBool = true

If the friends use this directly, the following error will appear:
Copy the code The code is as follows:

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

The reason for the compiler roar is that our type does not comply with the "Boolean literal conversion protocol", and then fix this problem,
##### The code example is as follows:
Copy the code The code is 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
#####note:

The 11th line in the code is the key point. My type OCBool supports the BooleanLiteralConvertible protocol. What does this association do? The friends in the Xcode code editor, hold down the Command key, and then click the BooleanLiteralConvertible protocol name in the 11th line , It will enter its definition,

##### The definition is as follows:
Copy the code The code is as follows:

protocol BooleanLiteralConvertible {
    typealias BooleanLiteralType
    class func convertFromBooleanLiteral (value: BooleanLiteralType)-> Self
}

There is a class method convertFromBooleanLiteral in this definition. Its parameter is of type BooleanLiteralType, which is the type of Bool that I pass in, and the return value is the type itself that implements this protocol. In our OCBool type, the return value is OCBool itself. After this definition, we can directly initialize the Boolean literal of the OCBool type.
#### Support Bool type judgment

Friends are restless, I must be thinking about how I can use it to achieve logical judgment, so if you write like this,
##### The code example is as follows:
Copy the code The code is as follows:

var isSuccess: OCBool = true
if isSuccess {
    println ("Old code invites you to eat hot pot!")
}

You can never eat the hot pot of old code, because here the compiler will roar:
Copy the code The code is as follows:

/Users/tyrion-OldCoder/Documents/Learning/BoolType/BoolType/main.swift:27:4: Type 'OCBool' does not conform to protocol 'LogicValue'
OCBool can only be initialized with bool type now, and can not directly return to bool type. Little torches still remember in "The Old Code Says Programming Vernacular Swift Rivers and Lakes", the old code mentioned many times, mother no longer worried about us if a = 1 {} is written, because the equal sign does not support the return of value, so the if condition is judged that the following condition must have a return value, OCBool does not, so the compiler cried. We solve this problem.
##### The code example is as follows:
Copy the code The code is 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 invites you to eat hot pot!")
}
#### The results are as follows:
Copy the code The code is as follows:

Hello, World!
Old code invites you to eat hot pot!
Program ended with exit code: 0
#####note:

● If the friends are using the Beta version of Xcode, please note that in the official Apple blog, if the line 17 of the code is wrong under Xcode Beta4, the protocol here is LogicValue instead of BooleanVue, so remember to read the error prompt. Is a good habit.

● Note that the 34th line of the code perfectly supports if judgment, and the output result is "old code please eat hot pot". The old code is also just talk, please don't take it seriously.

#### Support compatibility with all types of schools

Little friends, there are many risks in the rivers and lakes, and there are many schools. The old code has its own OCBool type. Perhaps Songshan Shaolin has its own SSBool type. Even Guo Meimei may have its own MMBool type. The types of each school should be identifiable as long as they support the LogicValue protocol.

##### The code example is as follows:
Copy the code The code is 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 invites you to eat hot pot!")
}
##### The results of the code run are as follows:
Copy the code The code is as follows:

Hello, World!
The old code has no money, Guo Meimei invites you to eat hot pot!
Program ended with exit code: 0
Pretty! Our OCBool type now supports all logical variable initialization.

#####note:

● The second line in the code: the use of the horizontal bar under "_", this is a powerful Xiaoqiang, the purpose here is to shield the external parameter name, so the friends can directly: var ocResult: OCBool = OCBool (mmResult) Instead of: var ocResult: OCBool = OCBool (v: mmResult), the friends are stunned! There is no external parameter name in this init function. Remember that the old code said in the book. The Swift initialization function will use the internal parameter name as the external parameter name by default.

#### Perfect OCBool's Boolean gene system:
Friends, the value of the bool type lies in various judgments, such as ==,! =, &, |, ^,!, And various combinational logic operations. Our OCBool must also have these functions, otherwise it will be genetic defects, And see how the old code is implemented:
Copy the code The code is as follows:

extension OCBool: Equatable {
}
// Support equivalent 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 bitwise 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)
}
// Supports negation operator
@prefix func! (a: OCBool)-> OCBool {
    return a ^ true
}
// Support combination and 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 is that the money is not spent when people die. The hardest thing in life is that people are alive and the money is gone!")
}

Okay, here you are. The thunder outside the window awakened the old code. It ’s time to eat. The above old code shows you that if you make your own type, remember that the example of the old code is under Xcode6 Beta4 Tested, as for the change of Beta5 has not been involved, the little friends should practice well, and various custom types are based on this idea in the future. Also, this chapter is not the original of the old code. The old code carefully read the official blog of Apple, and its own practice summary. If the friends have struggled to eat milk and still do not understand, please find Du Niang Google

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.