Difficulties to assign default value to a parameter of a function

前端 未结 3 628
攒了一身酷
攒了一身酷 2021-01-17 19:17

In a class, I defined a private constant, I try to use the constant as a default value of parameter of a function:

class Foo {
  // instance variable
  priva         


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-17 20:04

    I don't think that is possible. The default value is inserted at the calling site, and therefore needs to be public, see also Access control in swift 4.

    A possible workaround would be to make the parameter optional, and substitute nil by the default value locally:

    class Foo {
        private static let DefaultValue = 10
    
        public func doTask(amount: Int? = nil) {
            let amount = amount ?? Foo.DefaultValue
            // ...
        }
    }
    

提交回复
热议问题