[swift-evolution] Proposals: (1) Forbidding custom `==` for value types, (2) `dispatch` keyword, (3) `default`-result for methods with `Self`, and (4) Poor-Mans-Existentials

Johannes Neubauer neubauer at kingsware.de
Mon Jul 18 05:02:00 CDT 2016


> Am 18.07.2016 um 06:47 schrieb Susan Cheng <susan.doggie at gmail.com>:
> 
> so, you want to propose default == operator but not forbidding all peoples to custom == operator?
> Why don't just adding the following function to std library?
> 
> public func == <T : Equatable>(lhs: T, rhs: T) -> Bool {
>     var lhs = lhs
>     var rhs = rhs
>     return memcmp(&lhs, &rhs, sizeof(T.self)) == 0
> }

This does not work, because method parameters are statically dispatched. This function will never be executed for any type, that has a custom equality implementation. So this would not enforce this check upfront. You would need to copy this code to every custom implementation (which can be forgotten). Or you have to implement it like this

```swift
public func isSame(lhs: Any, rhs: Any) -> Bool {
  // like above in your code
}

public func ==(lhs: MyType, rhs: MyType) -> Bool {
  if isSame(lhs, rhs: rhs) {
    return true
  }
  // do custom behavior
}
```

> Thread safety can't fixed by std library. Value type only can atomic compared when additional mutex provided.

Value types are either on the stack or they are **copied** to the heap (for protocol types with large value types). So, you don’t have any thread safety issues (as they are copied before they are changed in the new thread) as long as you don’t do (or check) anything on a property of a reference type, because the latter has shared **state**.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 496 bytes
Desc: Message signed with OpenPGP using GPGMail
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160718/753bfe97/attachment.sig>


More information about the swift-evolution mailing list