Default argument not permitted in a tuple type when defining function type

前端 未结 2 923
无人及你
无人及你 2020-12-11 15:45

I’ve got a function like this:

func next(step: Int = 1){
    //....
}

And now I would like to define a type alias so that I can easily pass

相关标签:
2条回答
  • 2020-12-11 16:29

    No, that is not possible

    Explanation:

    A type alias declaration introduces a named alias of an existing type into your program.

    (step: Int = 1) -> () is not a proper type. A type is for example (step: Int) -> (), a default value is not allowed there.

    If you write

    typealias ActionNext = (Int) -> ()
    
    var nextFunc: ActionNext = next
    

    It works. Or even when you write (step: Int) -> ()

    But I assume what you want to achieve is being able to call nextFunc() omitting the parameter and using its default value. That is not possible. To understand why, you can follow the Type Alias Declaration grammar - in the type you can not specify default values.

    0 讨论(0)
  • 2020-12-11 16:40

    The problem is exactly what it says. You cannot provide a default argument in a type alias.

    it must be like this:

     typealias ActionNext = (step: Int) -> ()
    

    Your expectation to be able to set a default value is futile and doesn't make sense. (You showed disappointment with Swift in the comments, but fortunately Swift is doing just fine regarding this.)

    First thing first, the action is a closure, which itself is also a type. A type itself CANNOT have some kind of value. Type is never a concrete value, it is a dimensionless trait of a variable, it's qualitative description.

    You need to properly understand the relationship between the three terms: Variable - type - value

    A variable is an entity. It has three things - a name, a Type, and Value.

    The value is a realisation of the type trait.

    EXAMPLE

    you could have a variable called myDayOfRest that would be of type DayOfWeek and can have values of SU MO TU WE TH FR SA.

    Notice this -> let myDayOfRest be of type DayOfWeek and have a value of SA.

    in Swift it would be

    let myDayOfRest : DayOfWeek = SA
    

    Now when you create a type alias for the DayOfWeek type.. basically you are just giving an alternative name to the TYPE. Never to the concrete variable. Always to the TYPE. But it's not the TYPE that has some value, it is variables who have values.

    Hopefully now you can see why expecting to be able to provide a default value in a type alias does't make any sense.

    0 讨论(0)
提交回复
热议问题