3 ms·
I think that you are right on this, when looking at one of the examples (server.swift) it seems that people are paid by characters typed and they forget (or nev
by mingodad 11y ago
I think that you are right on this, when looking at one of the examples (server.swift) it seems that people are paid by characters typed and they forget (or never heard of) the mantra DRY (Don't Repeat Yourself):
func fdSet(fd: Int32, inout set: fd_set) {
let intOffset = Int(fd / 16)
let bitOffset: Int = Int(fd % 16)
let mask: Int = 1 << bitOffset
switch intOffset {
case 0: set.__fds_bits.0 = set.__fds_bits.0 | mask
case 1: set.__fds_bits.1 = set.__fds_bits.1 | mask
case 2: set.__fds_bits.2 = set.__fds_bits.2 | mask
case 3: set.__fds_bits.3 = set.__fds_bits.3 | mask
case 4: set.__fds_bits.4 = set.__fds_bits.4 | mask
case 5: set.__fds_bits.5 = set.__fds_bits.5 | mask
case 6: set.__fds_bits.6 = set.__fds_bits.6 | mask
case 7: set.__fds_bits.7 = set.__fds_bits.7 | mask
case 8: set.__fds_bits.8 = set.__fds_bits.8 | mask
case 9: set.__fds_bits.9 = set.__fds_bits.9 | mask
case 10: set.__fds_bits.10 = set.__fds_bits.10 | mask
case 11: set.__fds_bits.11 = set.__fds_bits.11 | mask
case 12: set.__fds_bits.12 = set.__fds_bits.12 | mask
case 13: set.__fds_bits.13 = set.__fds_bits.13 | mask
case 14: set.__fds_bits.14 = set.__fds_bits.14 | mask
case 15: set.__fds_bits.15 = set.__fds_bits.15 | mask
default: break
}
}
- mikeash 11y agoGiven the unfortunate way fd_set apparently got imported, how else would you do this? The only alternative I see is to throw UnsafeMutablePointer at it, but that brings in the ugly specter of undefined behavior. Note that in Swift you cannot use a variable to address a tuple, so there's no way to use intOffset to access the corresponding field of set.__fds_bits.
- mingodad 11y agoFor me is hard to understand how a language with a behavior/constraints like you describe get so much noise about "been easy to use/learn". I do not like it but at least be DRY as much as possible: case 0: set.__fds_bits.0 |= mask
- mikeash 11y agoWhat you're seeing here is a result of an unfortunate interaction with bridging to C APIs. fd_set is a C struct which contains a fixed-length array. Swift doesn't have fixed-length arrays, so those get translated to tuples instead. This is not ideal, but it comes up almost never. As for your suggestion, that seems like an entirely stylistic thing. DRY is about not copy/pasting large chunks of code, not minimizing individual lines by using compound mutate/assign operators. I've never seen anyone say (before!) that something like `x = x + 1` violates DRY.
- weego 11y agoMore importantly nothing about DRY overwrites the ideal that making the intent of your code explicitly clear is more important then fixating on micro optimisations. I feel like the code as it is less easy to misunderstand while skim read.