Custom type details for Swift type creation

  • 2020-05-09 19:23:31
  • OfStack

Friends, Swift Bool types have very important in grammatical functions, and prop up the logic system of whole Swift system, through the research and study of the old code Bool type itself is actually based Boolean type of packaging, friends may bite fingers ask old code, how can 1 Bool type, 1 will Boolean type, the difference is that the former is based on the combination of the enumeration type, while the latter is the basic type, there are only two true and false.

Custom stereotypes

Go ahead and create an OCBool type based on Bool's ideas to let your friends know how Swift works.

Let's look at the definition of OCBool first.

The code example for ##### # is as follows:


enum OCBool{
case ocTrue
case ocFalse
}

# # # # # note:

Lines 2 and 3 in the code can be combined into line 1, as apple's official Blog wrote in line 1
Note the naming in the code: OCBool is a type name, so the first letter must be uppercase, while ocTrue and ocFalse in case are lowercase for small types.

#### implements default values

Ok, we gave a nice definition, but according to the traditional language experience, the Bool value is false by default, so our OCBool should be the same, we use the type extension technique to add this default feature:


extension OCBool{
     init(){
             self =.ocFalse
     }
}

# # # # # note:

● code line 1: extension keyword, very powerful, friends can create a lot of fun things through this, I suggest you go to Github to see a project called "Swiftz", it will be extended to the extreme.

Low code line 3: self = ocFalse syntax, beginner friends is very confused, why there will be a strange point of grammar, because Daniel Chris in Swift increased the function type intelligent inference, in apple Blog mentioned "Context" concept, is this meaning, because this line is in the enumeration OCBool, its context is the definition of OCBool body, the compiler of course. Is ocFalse OCBool. ocFalse, direct point of grammar, so here is very neat.

Now we can use the Bool type as follows.

The code example for ##### # is as follows:


var result:OCBool = OCBool()
var result1:OCBool = .ocTrue

#### supports basic Boolean initialization

As mentioned above, we can only assign by type or enumeration items, which is the use of composite types, but in coding days, we always want to deal directly with true, false, which means we want to do this,

The code example is as follows:


var isSuccess:OCBool = true

If you use it this way, you might make the following mistake:

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

The reason the compiler is howling is that our types don't conform to the "Boolean literal conversion protocol," and we're going to fix that,

The code example for ##### # 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:

My type OCBool supports the BooleanLiteralConvertible protocol. What does this protocol do? People in the Xcode code editor, hold down the Command key, and then click the BooleanLiteralConvertible protocol name in line 11 to enter its definition.

The definition of ##### # is as follows:


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

This definition has a class method convertFromBooleanLiteral that takes the BooleanLiteralType type, which is the Bool type I passed in, and returns the type itself that implements the protocol. In our OCBool type, the return value is OCBool itself. With this definition, we can directly initialize the Boolean literal of OCBool type.

#### supports Bool type determination

I'm sure you're thinking about how I'm going to use it to make logical judgments, so if you write it this way,
The code example for ##### # is as follows:


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

You'll never eat old hotpot, because here the compiler growls:

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

OCBool initialization, now can only use bool type and cannot be returned directly bool type, small fires still remember in vernacular Swift river's lake "of the old code programming, the old code mentioned many times, my mother never worry about our if a = 1 {} writing, because the equal sign does not support value is returned, so behind the if judgment is must have a return value, the conditions of OCBool no, so the compiler crying. Let's solve this problem.
The code example for ##### # 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( " Lao ma invites you to eat hot pot! ")
}

The result of running #### is as follows:


Hello, World!
Lao ma invites you to eat hot pot!
Program ended with exit code: 0

# # # # # note:

● if you are using Beta version of Xcode, note that apple's official Blog is on line 17. If it is wrong under Xcode Beta4, the protocol is LogicValue instead of BooleanVue, so it is a good practice to read the error.

● note code line 34, perfect support if judgment, and the output result is "old code please eat hot pot", old code is just saying, please don't seriously.

#### supports types that are compatible with all factions

Friends, river's lake risk and numerous factions, old code has its own OCBool type, may have their own SSBool songshan shaolin type, even guo may have their own MMBool type, so that must be able to identify OCBool type, these various types, as long as the support LogicValue agreement, should can be identified, see old code what to do,

The code example for ##### # 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 yards have no money, guo meimei please eat hot pot! ")
}

The result of running the ##### code is as follows:


Hello, World!
Old yards have no money, guo meimei please eat hot pot!
Program ended with exit code: 0

Beautiful! Our OCBool type now supports all logical variable initializations.

# # # # # note:

● code line 2: "_" the use of the next bar, this is a powerful xiaogang, here is the purpose of shielding the external parameter name, so friends can directly: var ocResult:OCBool = OCBool(mmResult) instead of: var ocResult:OCBool = OCBool(v: mmResult), friends surprised! There is no external parameter name in the init function. Remember the old code said in the book that the initialization function of Swift will use the internal parameter name as the external parameter name by default.

Improve the Boolean gene system of OCBool:
The value of the bool type, folks, is in its judgments, such as ==,! =, &, |, ^! , and various combinational logic operations, we OCBool also need to have these functions, otherwise we will have genetic defects, let's see how the old code can be implemented:


extension OCBool: Equatable{
} // Support for equivalence determination operators
func ==( left: OCBool, right: OCBool )->Bool{
    switch (left, right){
    case (.ocTrue, .ocTrue):
            return true
    default:
        return false
    }
}
// Supports bits and operators
func &( left:OCBool, right: OCBool)->OCBool{     if left{
        return right
    }
    else{
        return false
    }
}
// Supports bits or operators
func |( left:OCBool, right: OCBool)->OCBool{     if left{
        return true
    }
    else{
        return right
    }
} // Support for the bit exception or operator
func ^( left:OCBool, right: OCBool)->OCBool{
    return OCBool( left != right )
}
// Supports the anti operator
@prefix func !( a:OCBool )-> OCBool{
    return a ^ true
}
// Support for combination search and operators
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( " A winner in life, like the old yard 1 The sample! ")
}else
{
    println(" Life is the most bitter things, people died money did not spend, life is the most bitter thing, people live, money did not! ")
}

Ok, here, here the thunder woke up the old code out of the window, you should go to dinner now, more than the old code to show you if make a own types, remember the old code example is for Xcode6 Beta4 under test, as for Beta5 change has not involved, friends to practice, it would produce after all kinds of customised types are based on the idea. And original of this chapter is not the old code and old code carefully read apple's official blog, and their practice summary, if friends efforts for nursing time still don't understand, please look for baidu Google came came came here


Related articles: