Re: [swift-users] Protocol conformance error

2018-01-17 Thread Nevin Brackett-Rozinsky via swift-users
Because it would break this:

func foo (c: T, a: U) { c.test(a) }

Nevin


On Wed, Jan 17, 2018 at 2:29 AM, Roshan via swift-users <
swift-users@swift.org> wrote:

> Hi,
>
> Here is some sample code that gives a protocol conformance error in a
> playground:
>
> protocol A {}
> protocol B: A {}
>
> protocol C {
> func test(x: A)
> }
>
> class M: C {
> func test(x: B) {}
> }
>
> Is there a reason why the compiler doesn't infer that ((B) -> ())
> matches ((A) -> ()) because of inheritance?
>
> --
> Warm regards
> Roshan
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] appending packed bytes to [UInt8]

2018-01-10 Thread Nevin Brackett-Rozinsky via swift-users
Conversely, since I’m pretty sure the memory layout of a *tuple* is
guaranteed to be as it appears, I would probably start with something like
this:

typealias Vec3rgba = (x: Float, y: Float, z: Float, r: Int8, g: Int8, b:
Int8, a: Int8)

Nevin


On Wed, Jan 10, 2018 at 4:27 PM, Jens Persson via swift-users <
swift-users@swift.org> wrote:

> I'm not sure what you mean by "I need the buffer to be a vector /.../" but
> perhaps this may be of some help:
>
> struct S {
> var x: Float
> var y: Float
> var z: Float
> var r: UInt8
> var g: UInt8
> var b: UInt8
> var a: UInt8
> }
> var buf = S(x: 0.1, y: 1.2, z: 2.3, r: 11, g: 22, b: 33, a: 44)
> print(MemoryLayout.stride) // 16
> withUnsafeMutableBytes(of: ) { ptr in
> print("x:", ptr.load(fromByteOffset: 0, as: Float.self)) // 0.1
> print("y:", ptr.load(fromByteOffset: 4, as: Float.self)) // 1.2
> print("z:", ptr.load(fromByteOffset: 8, as: Float.self)) // 2.3
> print("r:", ptr.load(fromByteOffset: 12, as: UInt8.self)) // 11
> print("g:", ptr.load(fromByteOffset: 13, as: UInt8.self)) // 22
> print("b:", ptr.load(fromByteOffset: 14, as: UInt8.self)) // 33
> print("a:", ptr.load(fromByteOffset: 15, as: UInt8.self)) // 44
> }
>
> NOTE however that the memory layout of Swift-structs is not guaranteed to
> remain like this and is thus not future-proof, although I think that
> if/when things changes, there will be some way to tell the compiler that
> you want the memory to be this "expected" "C-like" layout.
>
> /Jens
>
>
> On Wed, Jan 10, 2018 at 10:03 PM, Kelvin Ma via swift-users <
> swift-users@swift.org> wrote:
>
>> I want to create a buffer with the layout
>>
>> 0   4   8   12  13  14  15  16
>> [   x:Float   |   y:Float   |   z:Float   | r:UInt8 | g:UInt8 | b:UInt8
>> | _:UInt8 ]
>>
>> Normally, I’d use UnsafeRawBufferPointer for this, but I need the buffer
>> to be a vector (i.e. with append(_:)), and for it to return a
>> Swift-managed Array. How should I do this? The project does not
>> use Foundation.
>>
>> ___
>> swift-users mailing list
>> swift-users@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
>>
>>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Rethrows issue

2017-12-30 Thread Nevin Brackett-Rozinsky via swift-users
So, I know this doesn’t actually address your issue, but I think it is
important to clarify that “rethrows” does not guarantee anything about the
*type* of error thrown by a function. What “rethrows” implies is that the
function *will not throw* unless at least one of its arguments throws.

In particular, if the argument throws, the outer function can throw *any
error or none at all*. For example,

enum CatError: Error { case hairball }
enum DogError: Error { case chasedSkunk }

func foo(_ f: () throws -> Void) rethrows -> Void {
do{ try f() }
catch { throw CatError.hairball }
}

do {
try foo{ throw DogError.chasedSkunk }
} catch {
print(error)// hairball
}

Inside foo’s catch block, it is legal to throw any error, or not throw an
error at all. But *outside* that catch block foo cannot throw, which is
causing you consternation.

• • •

I don’t have a good solution for you, but in attempting to find one I *did*
uncover something which compiles that probably shouldn’t. It seems that a
“rethrows” function is currently allowed to throw if a *local* function
throws:

func rethrowing(_ f: () throws -> Void) rethrows -> Void {
func localThrowing() throws -> Void { throw CatError.hairball }
return try localThrowing()
}

do {
try rethrowing{ throw DogError.chasedSkunk }
} catch {
print(error)// hairball
}

I wouldn’t count on this functionality as it is most likely a bug. Indeed,
if we pass in a non-throwing argument then we get a runtime error:

rethrowing{ return }  // EXC_BAD_ACCESS (code=1, address=0x0)

Although, if we change “localThrowing” to use do/catch on a call to “f” and
throw only in the catch block, or even use your “var caught: Error?” trick,
then it appears to work as intended with no problems at runtime.

• • •

In the unlikely scenario that the above local-function behavior is valid
and intended, the following function will, technically speaking, let you
work around the issue you’re having:

func withPredicateErrors 
(_ predicate: (Element) throws -> Bool,
 do body: @escaping ((Element) -> Bool) -> Return
) rethrows -> Return
{
func bodyWrapper(_ f: (Element) throws -> Bool) throws -> Return {
var caught: Error?
let value = body{ elem in
do {
return try f(elem)
} catch {
caught = error
return true
}
}
if let caught = caught { throw caught }
return value
}

return try bodyWrapper(predicate)
}

It is not pretty, and it probably relies on a compiler bug, but at the
present time, against all odds, it look like this operates as you intend.

Nevin



On Sat, Dec 30, 2017 at 11:15 PM, Brent Royal-Gordon via swift-users <
swift-users@swift.org> wrote:

> I need to do something like this:
>
> func withPredicateErrors(_ predicate: (Element)
> throws -> Bool, do body: ((Element) -> Bool) -> Return) rethrows -> Return {
>   var caught: Error?
>   let value = body { elem in
> do {
>   return try predicate(elem)
> }
> catch {
>   caught = error
>   return true // Terminate search
> }
>   }
>
>   if let caught = caught {
> throw caught
>   }
>   else {
> return value
>   }
> }
>
> The problem is, the Swift compiler doesn't allow the explicit `throw`
> statement; even though it can only throw errors originally thrown by
> `predicate`, the compiler is not smart enough to prove that to itself. I
> cannot make `body` a `throws` function.
>
> Is there any way to do this? Either to override the compiler's safety
> check, or to rewrite this function to avoid it?
>
> --
> Brent Royal-Gordon
> Architechies
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Incorrect Fisher-Yates shuffle in example code

2017-12-17 Thread Nevin Brackett-Rozinsky via swift-users
…well that was more complicated than I anticipated.

The “random” function was (Int) -> Int, so when I removed the
“IndexDistance == Int” constraint on “shuffle” I either had to add several
“numericCast” calls or make “random” generic.

So I made “random” generic. And also fixed the modulo bias issue in the
Glibc version that Saagar mentioned. Or at least I hope I did. I haven’t
tested that part (nor any of the non-Swift-4 / non-macOS parts). Also, I am
not sure why “random” had been a closure value stored in a “let” constant,
but I changed it to a function.

While I was at it, I removed the random-access constraint I had placed on
“shuffle”. It will now shuffle any MutableCollection, with complexity O(n)
for a RandomAccessCollection and O(n²) otherwise. (The constraint was
different in different Swift versions, so the entire extension had to be
duplicated. Without the constraint the implementation is much sleeker.)

Nevin


On Sun, Dec 17, 2017 at 9:26 PM, Nevin Brackett-Rozinsky <
nevin.brackettrozin...@gmail.com> wrote:

> On Sun, Dec 17, 2017 at 7:37 PM, Dave Abrahams <dabrah...@apple.com>
> wrote:
>
>>
>> On Dec 16, 2017, at 4:34 PM, Nevin Brackett-Rozinsky via swift-users <
>> swift-users@swift.org> wrote:
>>
>> public extension MutableCollection where Self: RandomAccessCollection,
>> IndexDistance == Int {
>>
>>
>> IndexDistance == Int is an over-constraint, FWIW.  Adding it is generally
>> a mistake.  Not a serious one, but it does limit utility somewhat.
>>
>> HTH,
>> Dave
>>
>
> You are correct, however there is an accepted-and-implemented proposal (
> SE–0191
> <https://github.com/apple/swift-evolution/blob/master/proposals/0191-eliminate-indexdistance.md>)
> to eliminate IndexDistance and replace it with Int, so the constraint will
> always be satisfied starting in Swift 4.1.
>
> I wrote a version of shuffle() without that constraint, but it is less
> elegant: the line “for n in 0 ..< count - 1” no longer compiles, and
> writing “0 as IndexDistance” doesn’t fix it because the resulting Range is
> not a Sequence, since IndexDistance.Stride does not conform to
> SignedInteger (at least in Swift 4.0 according to Xcode 9.2).
>
> A while loop works of course, though a direct conversion requires writing
> “var n = 0 as IndexDistance” before the loop. Luckily, with a bit of
> cleverness we can eliminate all mention of IndexDistance, and this time we
> really and truly don’t need the “guard !isEmpty” line:
>
> extension MutableCollection where Self: RandomAccessCollection {
> mutating func shuffle() {
> var n = count
> while n > 1 {
> let i = index(startIndex, offsetBy: count - n)
> let j = index(i, offsetBy: random(n))
> n -= 1
> swapAt(i, j)
> }
> }
> }
>
> Essentially, the constraint is there to make the code nicer on pre-4.1
> versions of Swift, though I’m happy to remove it if you think that’s
> better. If nothing else, removing the constraint means people reading the
> example code in the future won’t be misled into thinking they need to use
> it themselves, so perhaps it should go just on that account.
>
> Okay, you’ve convinced me, I’ll update the PR. :-)
>
> Nevin
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Incorrect Fisher-Yates shuffle in example code

2017-12-17 Thread Nevin Brackett-Rozinsky via swift-users
On Sun, Dec 17, 2017 at 7:37 PM, Dave Abrahams <dabrah...@apple.com> wrote:

>
> On Dec 16, 2017, at 4:34 PM, Nevin Brackett-Rozinsky via swift-users <
> swift-users@swift.org> wrote:
>
> public extension MutableCollection where Self: RandomAccessCollection,
> IndexDistance == Int {
>
>
> IndexDistance == Int is an over-constraint, FWIW.  Adding it is generally
> a mistake.  Not a serious one, but it does limit utility somewhat.
>
> HTH,
> Dave
>

You are correct, however there is an accepted-and-implemented proposal (
SE–0191
<https://github.com/apple/swift-evolution/blob/master/proposals/0191-eliminate-indexdistance.md>)
to eliminate IndexDistance and replace it with Int, so the constraint will
always be satisfied starting in Swift 4.1.

I wrote a version of shuffle() without that constraint, but it is less
elegant: the line “for n in 0 ..< count - 1” no longer compiles, and
writing “0 as IndexDistance” doesn’t fix it because the resulting Range is
not a Sequence, since IndexDistance.Stride does not conform to
SignedInteger (at least in Swift 4.0 according to Xcode 9.2).

A while loop works of course, though a direct conversion requires writing
“var n = 0 as IndexDistance” before the loop. Luckily, with a bit of
cleverness we can eliminate all mention of IndexDistance, and this time we
really and truly don’t need the “guard !isEmpty” line:

extension MutableCollection where Self: RandomAccessCollection {
mutating func shuffle() {
var n = count
while n > 1 {
let i = index(startIndex, offsetBy: count - n)
let j = index(i, offsetBy: random(n))
n -= 1
swapAt(i, j)
}
}
}

Essentially, the constraint is there to make the code nicer on pre-4.1
versions of Swift, though I’m happy to remove it if you think that’s
better. If nothing else, removing the constraint means people reading the
example code in the future won’t be misled into thinking they need to use
it themselves, so perhaps it should go just on that account.

Okay, you’ve convinced me, I’ll update the PR. :-)

Nevin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Incorrect Fisher-Yates shuffle in example code

2017-12-16 Thread Nevin Brackett-Rozinsky via swift-users
On Sat, Dec 16, 2017 at 7:37 PM, Daniel Dunbar 
 wrote:

> Would you like to post a PR to fix these issues?
>
>  - Daniel
>

All right, I’ve submitted a PR that I think should work, though I’m not too
confident in the pre-Swift-4 parts (credit to swiftdoc.org if the code for
old versions is valid).


On Sat, Dec 16, 2017 at 8:03 PM, Saagar Jha  wrote:

>
> Both of the original guard statements would be superfluous here (notably,
> “swapAt” is documented to have no effect when i and j are the same) so I
> removed them.
>
>
> Actually, I believe the first guard is still necessary–if the collection
> is empty, you’d end up with trying to construct the range 0..<-1, which
> traps. Alternatively, stride(from:to) is more lenient.
>

Right you are, not sure how I missed that. Muphry’s law
 strikes again!

Nevin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Incorrect Fisher-Yates shuffle in example code

2017-12-16 Thread Nevin Brackett-Rozinsky via swift-users
The example implementation of the Fisher-Yates shuffle found here

on
Apple’s GitHub (and linked from swift.org/package-manager) has some
problems. Stripping it down to just the Swift 4 version, the code is:

public extension MutableCollection where Index == Int, IndexDistance == Int
{
mutating func shuffle() {
guard count > 1 else { return }

for i in 0..___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Comprehensive documentation for Collection?

2017-12-15 Thread Nevin Brackett-Rozinsky via swift-users
In Xcode if I write,

extension Collection {
var secondIndex: Index { return index(after: startIndex) }
}

and then option-click on “Index”, it shows “associatedtype Index :
Comparable” followed by a description. Is this documented somewhere?

When I look at the documentation for Collection
 on
developer.apple.com there is no mention of an Index associated type. I also
don’t see it in The Swift Programming Language.

If someone didn’t already know Collection.Index exists, how would they be
expected to learn of it? And if they didn’t know it must be Comparable how
would they learn that?

Also, are there any semantic requirements on Collection.Index, for example
is it required that “idx < index(after: idx)” must evaluate to true for any
valid index “idx”?

• • •

On a somewhat related note, the “indices” property of Collection has a
discussion section visible by option-clicking in Xcode or by looking
at the documentation
for it

on developer.apple.com.

And that discussion recommends against iterating over “indices” when
mutating a collection, because “indices” could hold a strong reference to
the collection and thus create an unexpected copy. Instead one should
manually advance from startIndex to endIndex in a while loop.

Now, this is at least documented, but perhaps it should be made more
prominent? It seems to me that if “for i in c.indices” represents a
performance pitfall then it should be regarded as an attractive nuisance.

Nevin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Is SwiftDoc.org still being updated?

2017-10-17 Thread Nevin Brackett-Rozinsky via swift-users
This might be out of scope for Swift Users, but I was wondering if anyone
knows whether SwiftDoc.org  is still being maintained.
As far as I can tell, it has not been updated for Swift 4 (even under
“nightly build” it doesn’t show, eg. the Numeric protocol).

I have found SwiftDoc to be a highly useful resource, and would love to see
it continue.

Nevin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] difference between two Ranges

2017-09-20 Thread Nevin Brackett-Rozinsky via swift-users
I think you’ll have to write this functionality yourself.

If you start with one range and remove from it everything in another range,
you will end up with either:

i) An empty range, if the first is entirely within the second.
ii) A single range, which might be closed, open, or half-open on either end.
iii) Two ranges, if the second is entirely within the first.

Of course, the built-in range types don’t cover all the possible
opennesses. So you probably want to do something like the following:

• Create your own range type (or types) to handle the various open/closed
possibilities.
• Create your own “collection of ranges” type (probably implemented with an
array of ranges).
• Write methods to handle combining and subtracting ranges and collections
thereof.

You should end up with something whereby subtracting one range from another
creates a collection of ranges, and adding a range to a collection merges
together any ranges that now overlap (keeping the ranges in the collection
disjoint means you can keep the array sorted in the natural manner).

Nevin


On Wed, Sep 20, 2017 at 4:09 PM, Седых Александр via swift-users <
swift-users@swift.org> wrote:

> Hello.
> I try to get difference between two ranges. For instance I have to know
> how many meters from me to target who have own size (or range).
>
> let range = 0...5
>
> let meFromPoint = 0...10
>
>
>
> let setRange = Set(range)
>
> let setMeFromPoint = Set(meFromPoint)
>
>
>
> let diff = setMeFromPoint.subtracting(setRange).count// result 5
>
> I found that operation Set(0...veryBigInt) may be slow.
> Is exist some native way to get difference between two Ranges?
>
>
> --
> Седых Александр
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Can you use @autoclosure in a setter?

2017-09-11 Thread Nevin Brackett-Rozinsky via swift-users
Hi, quick question here:

I have a class with a property that needs to be really *really* lazy. So
lazy, in fact, that when you assign to that property, the class actually
stores a closure of what you assigned, which is only evaluated if and when
you actually attempt to read the property.

Simplified:

class Foo {
  private var valueSource: () -> Bar
  private var valueCache: Bar?

  init(_ v: @escaping @autoclosure () -> Bar) {
valueSource = v
  }

  var value: Bar {
get {
  if let v = valueCache { return v }
  let w = valueSource()
  valueCache = w
  return w
}
set {
  /* ??? */
}
  }

  // I want this function's logic to go in the setter above
  func setValue(_ v: @escaping @autoclosure () -> Bar) {
valueSource = v
valueCache = nil
  }
}

The goal is to be able to write things like “someFoo.value = bar1 / bar2”
(or even more complex expressions) and not evaluate them until/unless the
result is actually needed.

Currently I am using “someFoo.setValue( bar1 / bar2 )”, which is not nearly
as ergonomic as the assignment syntax. So, is there a way to make this work?

Nevin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] What is up with names not being Strings any more in Swift 4?

2017-07-17 Thread Nevin Brackett-Rozinsky via swift-users
Could / should these types be ExpressibleByStringLiteral?

Nevin

On Mon, Jul 17, 2017 at 12:47 PM, Manfred Schubert via swift-users <
swift-users@swift.org> wrote:

>
> > Am 17.07.2017 um 18:08 schrieb Jon Shier :
> >
> > Making them an extension on String makes them visible everywhere String
> is used, unless you limit the visibility in some way, which impacts the
> performance of autocomplete and fills it with random constants.
>
> I see. Thanks for clarifying.
>
>
> Manfred
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] ⁨Is it possible to store a set of heterogeneous items with protocol?

2017-07-16 Thread Nevin Brackett-Rozinsky via swift-users
The standard pattern for type-erasure in Swift looks like this:

protocol Farm {
associatedtype Produce
func grow() -> Produce
}

private class _AnyFarmBase : Farm {
func grow() -> T { fatalError() }
}

private final class _AnyFarmBox: _AnyFarmBase {
var farm: U
init(_ x: U) { farm = x }
override func grow() -> U.Produce {
return farm.grow()
}
}

public final class AnyFarm : Farm {
private let wrapped: _AnyFarmBase
func grow() -> V { return wrapped.grow() }
init (_ x: W) where W.Produce == V {
wrapped = _AnyFarmBox(x)
}
}


There is one little hiccough when you need an initializer in the abstract
base class, which you can read about here

among other places.

Hope that helps,

Nevin


On Sun, Jul 16, 2017 at 12:32 AM, Glen Huang via swift-users <
swift-users@swift.org> wrote:

> This sounds like the right approach!
>
> However, as I experimented with AnyHashable more, I found out that after
> converting a concrete type to it, I could still convert back using “as”:
>
> AnyHashable(Foo()) as! Foo
>
> I guess that’s not the case with AnyNamed? I tried to imitate AnyHashable:
>
> struct AnyNamed: Named {
> let base: Any
> init(_ value: T) {
> base = value
> }
>
> var name: String {
> // How do I convert `base` to `Named` here?
> }
> }
>
> But I have no idea what to put in `var name: String`. Also, even if we
> managed to come up with a solution, would it magically allow direct casting
> with “as”? Does the complier do something special for AnyHashable?
>
>
> > On 16 Jul 2017, at 12:58 AM, Ole Begemann  wrote:
> >
> > One way to do this in Swift is a method called type erasure.
> >
> > Type erasure means you create a new type that wraps any value whose
> concrete type you want to erase. This new type also conforms to the
> protocol. By convention the type is named Any... (compare AnyIterator and
> AnySequence in the standard library, which do the same thing).
> >
> > struct AnyNamed: Named {
> >private let _name: () -> String
> >
> >init(_ value: T) {
> >_name = { value.name }
> >}
> >
> >var name: String {
> >return _name()
> >}
> > }
> >
> > AnyNamed is initialized with a generic value T: Named. Notice that the
> initializer is generic, but the type itself isn't. Because AnyNamed can't
> store value: T directly (then it would have to be generic over T), we
> create a closure over value.name and store that instead.
> >
> > Now we can create a Set and, because AnyNamed conforms to
> Named, treat the set's elements as values conforming to Named:
> >
> > var set = Set()
> > set.insert(AnyNamed(Foo()))
> > set.insert(AnyNamed(Bar()))
> >
> > for element in set {
> >print(element.name)
> >print(element.hashValue)
> > }
> >
> >
> > On 11.07.2017 12:10, Glen Huang via swift-users wrote:
> >> Hi,
> >>
> >> I want to store some heterogeneous items all conform to a protocol
> inside a set, is it something possible to do in swift?
> >>
> >> I tried this example:
> >>
> >> ```
> >> protocol Named: Hashable {
> >>var name: String { get }
> >> }
> >>
> >> extension Named {
> >>var hashValue: Int {
> >>return name.hashValue
> >>}
> >>
> >>static func ==(lhs: Self, rhs: Self) -> Bool {
> >>return lhs.name == rhs.name
> >>}
> >> }
> >>
> >> struct Foo: Named {
> >>var name = "foo"
> >> }
> >>
> >> struct Bar: Named {
> >>var name = "bar"
> >> }
> >>
> >> var item = Set()
> >> item.insert(Foo())
> >> item.insert(Bar())
> >> ```
> >>
> >> But it failed at `Set()` where it complained "Using 'Named' as a
> concrete type conforming to protocol 'Hashable' is not supported”.
> >>
> >> After watching the WWDC session "Protocol-Oriented Programming in
> Swift” by Dave Abrahams, I try to use protocols whenever possible. But I
> can’t seem to overcome this barrier. Set.Element must confirm to Hashable,
> which inherits from Equatable, which has self requirement, which ultimately
> means that Set.Element all must be of the same type. So it seems it’s
> impossible to have heterogeneous items using protocol. Is that the case?
> >>
> >> My use case is this:
> >>
> >> I have an object that can contain two sets of other objects:
> >>
> >> ```
> >> class Parent {
> >>var foos: Set
> >>var bars: Set
> >> }
> >> ```
> >>
> >> I want to define a computed property “all” that is the union of the two
> sets. Foo and Bar conform to the same protocol. I wonder what return type I
> should use for the union? Do I have to go back to OOP and define a super
> class for Foo and Bar?
> >>
> >> Thanks.
> >> ___
> >> swift-users mailing list
> >> swift-users@swift.org
> >> https://lists.swift.org/mailman/listinfo/swift-users
> >
> >
>
> ___
> swift-users mailing list
> swift-users@swift.org
> 

Re: [swift-users] Swift Documentation question

2017-07-01 Thread Nevin Brackett-Rozinsky via swift-users
On Sat, Jul 1, 2017 at 4:36 PM, Jon Shier via swift-users <
swift-users@swift.org> wrote:

> swiftdoc.org should be integrated into swift.org and be kept officially
> up to date.
>

 I agree.

Unfortunately it doesn’t have Swift 4 coverage yet, which is a shame, as I
> like that documentation format more than Apple’s official one.


Well, it does have an option for the nightly build of the master branch
, so that is something.

On a tangential note, I really like SwiftDoc’s visual hierarchy displays
(eg. this
),
though for some (eg. this
) it would be
nice to have an option to hide the concrete types and only show protocols.

Nevin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] override-like keyword for default implementations

2017-05-16 Thread Nevin Brackett-Rozinsky via swift-users
On Tue, May 16, 2017 at 4:59 PM, Vladimir.S via swift-users <
swift-users@swift.org> wrote:

> On May 16, 2017, at 12:32 PM, Nevin Brackett-Rozinsky via swift-users <
> swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>
>> There is not.
>>
>> At some point in the future, I believe the plan is to eventually allow
>> default implementations to be written in-line within the protocol
>> declaration itself. In other words, the fact that default implementations
>> currently must appear in extensions, is a temporary limitation that has not
>> yet been a priority to address.
>
>
> Very interested, why do you have this impression? I didn't see this idea
> in the list previously(probably I just missed it). I strongly believe there
> can't be such 'plan'.


It has come up sporadically over the years, dating back I think to the old
Dev Forums before Swift was open-sourced. Best I can find with a quick
search of the Evolution list is this message
<https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160125/008509.html>
from
early 2016 where Chris Lattner wrote, “This is a desired feature, but a
surprising amount of implementation effort blocks “just doing it”.”

So my understanding is that, while it may not be plan-of-record *per se*,
it is certainly on the radar.

Nevin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] override-like keyword for default implementations

2017-05-16 Thread Nevin Brackett-Rozinsky via swift-users
There is not.

At some point in the future, I believe the plan is to eventually allow
default implementations to be written in-line within the protocol
declaration itself. In other words, the fact that default implementations
currently must appear in extensions, is a temporary limitation that has not
yet been a priority to address.

Once we gain the ability to define default implementations within protocols
themselves, rather than extensions, then your use-case will “just work” (at
least as long as you control the protocol anyway). I wouldn’t hold my
breath though, as that behavior will not appear this year, and the plans
for next year have not been hashed out yet.

Nevin


On Tue, May 16, 2017 at 11:53 AM, Johannes Weiss via swift-users <
swift-users@swift.org> wrote:

> Hi swift-users,
>
> Is there anything like the `override` keyword for making sure that default
> implementations in protocols are not adding a new function?
>
> An example would be the following:
>
> protocol FooProto {
> func foo()
> }
>
> extension FooProto {
> func foo() { /* <-- can I mark this as being a default
> implementation */
> print("foo default")
> }
> }
>
> Right now, there's a `func foo()` default implementation for `FooProto`
> but if later of `foo` gets refactored to `bar`, we lose the default
> implementation which can lead to problems.
>
> Is there anything in Swift (like the `override` keyword) that allows me to
> say this is a default implementation and not a new method?
>
> Thanks,
>   Johannes
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] How to reference a generic function when a concrete version also exists?

2017-05-02 Thread Nevin Brackett-Rozinsky via swift-users
If I write a generic function like this:

func f(_ x: T) { print("Generic: \(x)") }

I can pass it to another function like this:

func g(_ fn: (Int) -> Void) { fn(0) }
g(f)// Prints “Generic: 0”

However if I *also* write a non-generic function like this:

func f(_ x: Int) { print("Int: \(x)") }

Then when I make the same call as before:

g(f)// Prints “Int: 0”

It passes in the new, non-generic version.

Is there something I can do, with both versions of f defined, to pass the
generic f into g?

Nevin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Error creating empty array of chained associated type

2017-04-29 Thread Nevin Brackett-Rozinsky via swift-users
I’ve stumbled upon an odd situation where Swift gives a compiler error if I
do things directly, but works properly with no error if I first create a
typealias. Here is a stripped-down example:

protocol P {
associatedtype C: Collection
}

extension P {
func emptyArray() -> [C.Iterator.Element] {
return [C.Iterator.Element]()   // Error
}
}

The “return” line gives the error “Cannot call value of non-function type
'[Self.C.Iterator.Element.Type]'” in Xcode 8.3.2. However, if we replace
that function with a seemingly-equivalent version that uses a typealias,
there is no error:

extension P {
func emptyArray() -> [C.Iterator.Element] {
typealias E = C.Iterator.Element
return [E]()// Works
}
}

Is this a known bug?

Nevin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] How do I turn an array into a bitmap image?

2017-03-16 Thread Nevin Brackett-Rozinsky via swift-users
Thanks Brent, that helps a lot.

I eventually found a site (here 
if anyone’s interested) that describes (albeit in Objective-C) how to make
a CGImage from a byte buffer through the use of CGDataProvider. Hopefully
I’ll be able to put the pieces together in Swift now.

Thanks again,

Nevin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] How do I turn an array into a bitmap image?

2017-03-15 Thread Nevin Brackett-Rozinsky via swift-users
I think I might not be explaining this very well.

I want to create a bitmap image where each pixel is RGBA with 8 bits
(UInt8) per channel, and I want to specify the exact color for every pixel.
I do not know how to do that.

Also, for my specific application, I need to take an array of floating
point numbers and say, “Hey, the underlying bits that make up the IEEE-754
representation of these numbers are exactly the bits that I want to use for
the colors of the pixels.” I do not know how to do that in Swift.

In C I would malloc a buffer, write to it as (float*), then pass it to a
function which takes (char*) and saves a PNG. Thus there is only one
allocation, the buffer is filled with float values, and the exact
bit-pattern is interpreted as RGBA pixels.

How can I do the equivalent in Swift?

Nevin


On Wed, Mar 15, 2017 at 2:43 PM, Jens Alfke <j...@mooseyard.com> wrote:

>
> On Mar 15, 2017, at 11:07 AM, Nevin Brackett-Rozinsky via swift-users <
> swift-users@swift.org> wrote:
>
> Ideally I’d like to create the bitmap image without having to allocate a
> second buffer. The sole purpose of the Float array is for creating this
> image, so I’d like to directly use its bytes as the pixels data. I expect
> this will involve some Unsafe[…] APIs in Swift, though I don’t know exactly
> how.
>
>
> AFAIK there aren’t any pixmap formats that use floats. If you want to
> produce ARGB pixels, then emit your data in that format, i.e. as a [UInt8].
> No unsafe stuff needed.
>
> And yes, I am on an Apple platform. Despite reading boatloads of Core
> Graphics documentation, I still can’t make heads or tails out of how to
> turn a pre-existing array into the backing data for a bitmap image. This
> part is only Swift-related in the sense that I am trying to do it in Swift,
> so if there’s a better place to ask/learn about it I’d appreciate being
> pointed there.
>
>
> Either Apple’s developer forums, or the cocoa-dev mailing list hosted at
> http://lists.apple.com.
>
> —Jens
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] How do I turn an array into a bitmap image?

2017-03-15 Thread Nevin Brackett-Rozinsky via swift-users
Right, I understand conceptually what needs to happen. It is the actual
implementation where I’m getting stuck.

Ideally I’d like to create the bitmap image without having to allocate a
second buffer. The sole purpose of the Float array is for creating this
image, so I’d like to directly use its bytes as the pixels data. I expect
this will involve some Unsafe[…] APIs in Swift, though I don’t know exactly
how.

And yes, I am on an Apple platform. Despite reading boatloads of Core
Graphics documentation, I still can’t make heads or tails out of how to
turn a pre-existing array into the backing data for a bitmap image. This
part is only Swift-related in the sense that I am trying to do it in Swift,
so if there’s a better place to ask/learn about it I’d appreciate being
pointed there.

Thanks again,
Nevin


On Wed, Mar 15, 2017 at 1:44 PM, Jens Alfke <j...@mooseyard.com> wrote:

>
> On Mar 15, 2017, at 9:56 AM, Nevin Brackett-Rozinsky via swift-users <
> swift-users@swift.org> wrote:
>
> For one of my programs, I need to take an array of Floats and use the
> underlying bytes as the RGBA data for a bitmap image. In particular, the 32
> bits of each Float must be treated as the color of the corresponding pixel.
> So the result is an image of height 1 and width the length of the array.
>
>
> Make a pixmap, an array of UInt8 that’s 4x longer than your original
> array, where the elements are interpreted as R, G, B, A, R, G, B, A… Then
> fill it in based on the original float values.
>
> In particular, I need to be able to save the image as a PNG file, then
> later load it from disk and reconstruct each Float from its pixel, with no
> loss or change to the value of the Floats. So, how do I go from [Float] to
> a bitmap image suitable for saving to disk, without altering the underlying
> bytes?
>
>
> You’ll need to call some external image-encoding library, passing it your
> pixmap. If you’re on an Apple platform try ImageIO. If not, or if you want
> to be cross-platform, try libpng.
>
> —Jens
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] How do I turn an array into a bitmap image?

2017-03-15 Thread Nevin Brackett-Rozinsky via swift-users
For one of my programs, I need to take an array of Floats and use the
underlying bytes as the RGBA data for a bitmap image. In particular, the 32
bits of each Float must be treated as the color of the corresponding pixel.
So the result is an image of height 1 and width the length of the array.

In particular, I need to be able to save the image as a PNG file, then
later load it from disk and reconstruct each Float from its pixel, with no
loss or change to the value of the Floats. So, how do I go from [Float] to
a bitmap image suitable for saving to disk, without altering the underlying
bytes?

(Yes, I understand this is an odd sort of thing to do. I can explain the
purpose if anyone is interested.)

Thanks,
Nevin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Using 'SomeProtocol' as a concrete type conforming to protocol 'SomeProtocol' is not supported

2016-12-28 Thread Nevin Brackett-Rozinsky via swift-users
It will work if you change the enum declaration to:

enum ElementNode

In other words, let the enum hold arbitrary unconstrained associated types,
and then make your APIs utilize instances of the enum with the associated
type constrained to a protocol.

The specific example you provide is essentially equivalent to:

var childElements = [Element?]()

Nevin


On Wed, Dec 28, 2016 at 6:41 PM, Brandon Knope via swift-users <
swift-users@swift.org> wrote:

> I don’t understand why this is a problem
>
> protocol Element {
>
>
> }
>
> enum ElementNode {
> case element(T)
> case empty
> }
>
> var childElements = [ElementNode]()
>
> I need to represent an array of my nodes that could be multiple kinds of
> elements
>
> Is there a workaround?
>
> Brandon
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Decimal to Double?

2016-11-28 Thread Nevin Brackett-Rozinsky via swift-users
On Mon, Nov 28, 2016 at 2:21 PM, Joe Groff via swift-users <
swift-users@swift.org> wrote:

> ExpressibleByFloatLiteral uses a binary float initial value and so doesn't
> guarantee decimal accuracy


That seems like a flaw in ExpressibleByFloatLiteral that should be fixed.

Did anyone ever submit a proposal following the discussion in
“[swift-evolution] Allow FloatLiteralType in FloatLiteralConvertible to be
aliased to String” where somebody—*runs to check*…oh it was you!—described
the proper solution?

Nevin


On Mon, Nov 28, 2016 at 2:21 PM, Joe Groff via swift-users <
swift-users@swift.org> wrote:

>
> > On Nov 28, 2016, at 9:22 AM, Alex Blewitt via swift-users <
> swift-users@swift.org> wrote:
> >
> > NSDecimal conforms to the ExpressibleBy(Float|Integer)Literal, but that
> just means it can be created from a literal value, not the other way around:
> >
> > https://github.com/apple/swift-corelibs-foundation/blob/
> 108a5b0006912c6cf6b59e4954255237bf01b67a/Foundation/
> NSDecimal.swift#L319-L329
> >
> >
> >
> > extension Decimal : ExpressibleByFloatLiteral {
> > public init(floatLiteral value: Double) {
> > self.init(value)
> > }
> > }
> >
> > extension Decimal : ExpressibleByIntegerLiteral {
> > public init(integerLiteral value: Int) {
> > self.init(value)
> > }
> > }
>
> It really shouldn't be, since ExpressibleByFloatLiteral uses a binary
> float initial value and so doesn't guarantee decimal accuracy. I'd
> recommend using init(mantissa:exponent:isNegative:) instead, and
> minimizing any conversions between Double and Decimal.
>
> -Joe
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Bool to Int

2016-11-21 Thread Nevin Brackett-Rozinsky via swift-users
I don’t see what there is to be confused about.

A “literal” is literally a bunch of characters in source code. The compiler
interprets those characters as representing whatever type is appropriate to
the context.

For the case at hand, a boolean literal can be interpreted as any type
which conforms to the ExpressibleByBooleanLiteral protocol. If the context
provides no information, the compiler defaults to interpreting a boolean
literal as representing a Bool.

The situation is similar for every other kind of literal. For example, “2”
defaults to being interpreted as an Int, but if the context requires a
Double then it will be interpreted as a Double. The text “2” does not have
a type of its own.

Nevin


On Mon, Nov 21, 2016 at 3:55 PM, Rick Mann via swift-users <
swift-users@swift.org> wrote:

>
> > On Nov 21, 2016, at 09:46 , Kenny Leung via swift-users <
> swift-users@swift.org> wrote:
> >
> > This is so confusing. "Literals are untyped", but there’s a
> “BooleanLiteral”, which is obviously of type Boolean.
>
> Agreed.
>
> --
> Rick Mann
> rm...@latencyzero.com
>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Decimal imported as NSDecimal not NSDecimalNumber in Swift 3 to Objective C

2016-11-14 Thread Nevin Brackett-Rozinsky via swift-users
Literals in Swift do not inherently have a type (at least conceptually).
They are simply literals.

The compiler will interpret them as whatever ExpressibleBy_Literal type
is required to make the expression sensible.

There are default types which literals will become if no type information
is available: a string literal becomes String, a floating point literal
becomes Double, and so forth. But the literals themselves do not have a
type, and will become whatever type makes sense in context.

Nevin


On Mon, Nov 14, 2016 at 4:59 PM, Chris Anderson via swift-users <
swift-users@swift.org> wrote:

> Thanks for that follow up, I’m still a little confused at why one
> direction works and the other does not, but I’m getting there.
>
> I’ve found another issue I’ll bug report, but it’s along the same lines
> and wanted to run it by this thread. If I have an NSDecimalNumber, in
> Swift, and perform math on a literal value, (product) the code compiles. If
> I assign that value to a variable, or use any of the other Decimal/Double
> types, I cannot compile. I would expect a Double to not work, but I would
> expect ‘Decimal’ to work, in this case, as I’m not crossing the Objective C
> border. And, I’m confused how using the literal ‘2.0’ is interpreted as an
> NSDecimalNumber, and works in the ‘product’ stop, but I would expect the
> compiler to try and make it into a Double, as it does on the ‘test’
> variable.
>
> let value = NSDecimalNumber(value: 2)
> let test = 2.0   //
> double
> let product = value.multiplying(by: 2.0)  // compiles
> let x = value.multiplying(by: Decimal(2.0)) // does not compile
> let y = value.multiplying(by: Double(2.0))   // does not compile
> let z = value.multiplying(by: test)// does not
> compile
>
> Best,
> Chris Anderson
>
> On Nov 11, 2016, at 6:07 PM, Philippe Hausler  wrote:
>
>
> NSDecimal is not toll free bridged, but it does have a bridge to
> NSDecimalNumber.
>
> So take this for example:
>
> @objc class Exam: NSObject {
> var grade: Double = 90.0
> }
>
> It would be reasonable to expect that is exposed in objc as:
>
> @interface Exam : NSObject
> @property double grade;
> @end
>
> and not:
>
> @interface Exam : NSObject
> @property NSNumber *grade;
> @end
>
> As it stands this is exposing as the structural type since that structural
> type comes from objective-c. Unlike String or Dictionary that have direct
> counterparts - NSDecimal and NSDecimalNumber both are sourced from the
> objective-c headers. That being said an API exposed in objc as returning a
> NSDecimalNumber should be exposed into swift as returning a Decimal (the
> struct NSDecimal). So if Exam was implemented in objc as such:
>
> @interface Exam : NSObject
> @property NSDecimalNumber *grade;
> @end
>
> that should be imported into swift as:
>
> class Exam : NSObject {
> var grade : Decimal
> }
>
> On Nov 11, 2016, at 2:58 PM, Adam C. Lickel via swift-users <
> swift-users@swift.org> wrote:
>
> NSDecimal has toll-free bridging with NSDecimalNumber so you can still do
> as casting when talking to an Objective-C API.
>
> On Nov 11, 2016, at 2:56 PM, Chris Anderson via swift-users <
> swift-users@swift.org> wrote:
>
> Sure thing. Yeah, ideally the bridging would be fixed, but at the least,
> correcting the documentation will be a good start. Will file, thanks.
>
> Best,
> Chris Anderson
>
> On Nov 11, 2016, at 5:55 PM, Tony Parker  wrote:
>
> Hi Chris,
>
> Can you file a radar or JIRA for us on this? It looks like something
> should be fixed in the documentation at least, or perhaps in the bridging.
>
> - Tony
>
> On Nov 11, 2016, at 1:46 PM, Chris Anderson via swift-users <
> swift-users@swift.org> wrote:
>
> I'm having problems with the type conversion between a Swift `Decimal` and
> an Objective C `NSDecimalNumber`.
>
> If I have the Swift class:
>
> @objc class Exam: NSObject {
> var grade: Decimal = 90.0
> }
>
> And try to use that Swift class in Objective C,
>
> Exam *exam = [[Exam alloc] init];
> NSDecimalNumber *result = [[NSDecimalNumber zero]
> decimalNumberByAdding:grade.value];
>
> I get the error:
>
> Sending 'NSDecimal' to parameter of incompatible type 'NSDecimalNumber *
> _Nonnull'
>
> as it seems like `grade` is being treated as an `NSDecimal` not an
> `NSDecimalNumber`. This seems incorrect as per
> https://developer.apple.com/reference/foundation/nsdecimalnumber it says
>
> "The Swift overlay to the Foundation framework provides the Decimal
> structure, which bridges to the NSDecimalNumber class. The Decimal value
> type offers the same functionality as the NSDecimalNumber reference type,
> and the two can be used interchangeably in Swift code that interacts with
> Objective-C APIs. This behavior is similar to how Swift bridges standard
> string, numeric, and collection types to their corresponding 

Re: [swift-users] The value of enums

2016-11-06 Thread Nevin Brackett-Rozinsky via swift-users
To the topic at hand, the project I’m currently working on has 2 enums,
both with String raw values. For comparison, it has 3 classes (a Formatter
subclass, the app delegate, and one more), 4 protocols, and 47 structs.

One of the enums exists to select among the handful of struct types which
conform to one of the protocols.



> There are several things we have thought of that could potentially improve
> the situation, most notably exposing each case as an optional property.


That would be very nice.


I'd also really like to see switch-expressions (as opposed to statements).


Hmm, would a syntax like this be appropriate?

switch someValue -> [String] {
case .helloWorld: return ["Hello", "world"]
default: return []
}

That way the existing switch statement could remain as-is, and the familiar
function syntax would be used to specify the return type for switch
expressions. The “return” keyword could even be elided for single-line
cases as well, much like closures.

…oh, I just realized we’re on -users not -evolution here. Perhaps I’ll
bring this up next time switch expressions are proposed.

Nevin


On Sun, Nov 6, 2016 at 4:31 PM, Dave Abrahams via swift-users <
swift-users@swift.org> wrote:

>
> on Sun Nov 06 2016, Tino Heth  wrote:
>
> > Enums are a fundamental part of Swift, so I guess they won't change
> > much — but I wonder if anyone shares my observations in real-life use…
> >
> > Afair, there are three different types of enums:
> > - Enums with raw values
> > - enums with associated objects
> > - Plain enums (no underlying value)
> >
> > I use the first type quite often (as a convenient way to create string
> > constants, or for serialization), but see no real value in plain enums
> > (they offer nothing over enums backed with a raw value).
> >
> > The second type is special:
> > It looks like a really cool concept, and and I started several designs
> > based on them — just to realize later that structs and classes are a
> > better fit.
> > My conclusion so far is that enums perform bad as soon as you want to
> > attach additional data or behavior; one or two computed properties are
> > ok, but those switch-statements quickly become a burden.
> > There are some options to work around this problem, but I guess I'll
> > just stay away from enums with associated objects by default (with the
> > exception of error-types — imho those can be modeled quite nicely).
> >
> > So, that's my current perception, and I'm curious if others had
> > similar experiences — or, even more interesting, completely different
> > observations and elegant solutions based on enums.
>
> I have personally always found that exuberant use of that kind of enum
> results in ergonomics and readability difficulties.  There are several
> things we have thought of that could potentially improve the situation,
> most notably exposing each case as an optional property.  I'd also
> really like to see switch-expressions (as opposed to statements).  I'm
> not sure if that's really all we need in order to allow enums to reach
> their potential, though.
>
> --
> -Dave
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Overload by return type optionality?

2016-10-13 Thread Nevin Brackett-Rozinsky via swift-users
It works if you specify the types of the variables:

let a: String = …
if let b: String = …

Nevin


On Thu, Oct 13, 2016 at 5:36 PM, Rick Mann via swift-users <
swift-users@swift.org> wrote:

> It seems I can write this:
>
> extension String
> {
>   public func deleting(prefix inPrefix: String) -> String
>   public func deleting(prefix inPrefix: String) -> String?
> }
>
> But I was hoping it would do the right thing:
>
> let a = s.deleting(prefix: "foo")
> if let b = s.deleting(prefix: "foo") { }
>
> But it finds these ambiguous, and I'm not sure how to specify which I want.
>
> I'm having trouble googling for an answer on this. Some answers around
> generics, but that doesn't apply in this case.
>
> --
> Rick Mann
> rm...@latencyzero.com
>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] How to be DRY on ranges and closed ranges?

2016-10-12 Thread Nevin Brackett-Rozinsky via swift-users
You could also create a “Range” protocol with “lowerBound” and “upperBound”
properties. Conform all the range types to it, and make your function take
generic over the protocol.

Nevin


On Wed, Oct 12, 2016 at 7:21 PM, Hooman Mehr via swift-users <
swift-users@swift.org> wrote:

> I recommend having explicit precondition and reducing repetition like this:
>
> import Foundation
>
> func random(from range: CountableRange) -> Int {
>
> precondition(range.count > 0,
>  "The range can't be empty.")
>
> return random(from: CountableClosedRange(range))
> }
>
> func random(from range: CountableClosedRange) -> Int {
>
> let lowerBound = range.lowerBound
> let upperBound = range.upperBound
>
> precondition(upperBound - lowerBound < Int(UInt32.max),
>  "The range \(range) is too wide. It shouldn't be wider
> than \(UInt32.max).")
>
> return lowerBound + Int(arc4random_uniform(UInt32(upperBound -
> lowerBound + 1)))
> }
>
> let r1 = random(from: 4 ..< 8)
> let r2 = random(from: 6 ... 8)
>
> Once we have the new improved Integer protocols
> 
>  in
> place, you will be able to make it generic to support all integer types.
> (It is possible now, but too messy to be worth doing.)
>
>
> On Oct 12, 2016, at 1:23 PM, Adriano Ferreira via swift-users <
> swift-users@swift.org> wrote:
>
> Hi there!
>
> Ole Begeman offers here  (take
> a look at the bottom of the page) an interesting consideration about
> converting between half-open and closed ranges.
>
> As of now, it seems the way to go is by overloading…
>
>
> import Foundation
>
> func random(from range: Range) -> Int {
> let lowerBound = range.lowerBound
> let upperBound = range.upperBound
>
> return lowerBound + Int(arc4random_uniform(UInt32(upperBound -
> lowerBound)))
> }
>
> func random(from range: ClosedRange) -> Int {
> let lowerBound = range.lowerBound
> let upperBound = range.upperBound
>
> return lowerBound + Int(arc4random_uniform(UInt32(upperBound -
> lowerBound + 1)))
> }
>
> let r1 = random(from: 4 ..< 8)
> let r2 = random(from: 6 ... 8)
>
>
> Cheers,
>
> — A
>
> On Oct 12, 2016, at 6:21 AM, Jean-Denis Muys via swift-users <
> swift-users@swift.org> wrote:
>
> Hi,
>
> I defined this:
>
> func random(from r: Range) -> Int {
> let from = r.lowerBound
> let to =  r.upperBound
>
> let rnd = arc4random_uniform(UInt32(to-from))
> return from + Int(rnd)
> }
>
> so that I can do:
>
> let testRandomValue = random(from: 4..<8)
>
> But this will not let me do:
>
> let otherTestRandomValue = random(from: 4...10)
>
> The error message is a bit cryptic:
>
> “No ‘…’ candidate produce the expected contextual result type ‘Range’”
>
> What is happening is that 4…10 is not a Range, but a ClosedRange.
>
> Of course I can overload my function above to add a version that takes a
> ClosedRange.
>
> But this is not very DRY.
>
> What would be a more idiomatic way?
>
> Thanks,
>
> Jean-Denis
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] private vs. fileprivate on global declaration in Swift3?

2016-09-28 Thread Nevin Brackett-Rozinsky via swift-users
To answer the original question: at file scope the access modifiers
`private` and `fileprivate` have exactly the same effect. It does not
matter which of them you use there.

Nevin



On Wed, Sep 28, 2016 at 12:14 PM, Marco S Hyman via swift-users <
swift-users@swift.org> wrote:

>
> > On Sep 28, 2016, at 8:04 AM, Jens Alfke via swift-users <
> swift-users@swift.org> wrote:
> >
> >
> >> On Sep 28, 2016, at 12:16 AM, Cao Jiannan via swift-users <
> swift-users@swift.org> wrote:
> >>
> >> I think the Swift team should tell us which is better.
> >
> > If one were better than the other, they wouldn’t both exist...
> >
> > It depends on whether you need to use those entities in other source
> files in the same module.
> > If you don’t, use fileprivate. If you do, use private.
>
> private is *more* restrictive than fileprivate.  If you need to use the
> entities in other source files in the same module you want internal, not
> private.
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users