When to use inout parameters?

前端 未结 7 1579
情书的邮戳
情书的邮戳 2020-12-13 03:15

When passing a class or primitive type into a function, any change made in the function to the parameter will be reflected outside of the class. This is basically the same t

相关标签:
7条回答
  • 2020-12-13 04:14

    If you work with classes then, as you say, you can modify the class because the parameter is a reference to the class. But this won't work when your parameter is a value type (https://docs.swift.org/swift-book/LanguageGuide/Functions.html - In-Out Parameters Section)

    One good example of using inout is this one (defining math for CGPoints):

    func + (left: CGPoint, right: CGPoint) -> CGPoint {
      return CGPoint(x: left.x + right.x, y: left.y + right.y)
    }
    
    func += (left: inout CGPoint, right: CGPoint) {
      left = left + right
    }
    
    0 讨论(0)
提交回复
热议问题