Difficulties to assign default value to a parameter of a function

前端 未结 3 627
攒了一身酷
攒了一身酷 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:03

    A somewhat complicated, but workable, solution, for hiding the default value you want within your class is to use a protocol and a conforming struct whose intimate details are known only by the file declaring Foo:

    // enabling custom stuff
    public protocol IntLike {
        var intValue: Int { get }
    }
    
    // allowing to pass Int's
    extension Int: IntLike {
        public var intValue: Int { return self }
    }
    
    public class Foo {
        // the placeholder
        public struct FooIntLike: IntLike {
            // what we really want to hide
            fileprivate let realInt = 10
    
            public init() { }
    
            public var intValue: Int = Int.max // or 0, or whatever
        }
    
        public func doTask(amount: IntLike = FooIntLike()) {
            // default value will expand to a non-nil value for `realInt`
            let amount = (amount as? FooIntLike)?.realInt ?? amount.intValue
            // do your stuff with the amount
        }
    }
    

    Callers of doTask are able to pass Int's, while not knowing what the default value provides.

    0 讨论(0)
  • 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
            // ...
        }
    }
    
    0 讨论(0)
  • How about a top-level variable?

    fileprivate let DefaultValue = 10
    
    class Foo {
        public func doTask(amount: Int = DefaultValue) {
            ...
        }
    }
    
    0 讨论(0)
提交回复
热议问题