buguibu / ios-notes-issues-lessons

Notes, issues and lessons about my iOS development experience
2 stars 0 forks source link

Swift 5.1 "some" _the opaque return type_ #11

Open buguibu opened 5 years ago

buguibu commented 5 years ago
public protocol EveryoneCanHandleThis { 
  func handleMeItsFree()
}
private struct SecretHandler: EveryoneCanHandleThis { 
  func handleMeItsFree() {
    // This is free by today
  }
}

func giveMeAHandler() -> some EveryoneCanHandleThis {
  return SecretHandler()
}

By returning an opaque return type we can hide the implementation and later ...

private struct EvolvedSecretHandler: EveryoneCanHandleThis { 
  func handleMeItsFree() {
    // Now we are charging users in a secret way but they still thinks that it's free
  }
}

func giveMeAHandler() -> some EveryoneCanHandleThis {
  return EvolvedSecretHandler()
}

change the implementation and callers doesn't need to change a line.