[swift-users] Swift and Threads

2016-09-12 Thread Gerriet M. Denkmann via swift-users
This function works flawlessly in Release build:

func markAndTell( talk: Bool, number: Int)
{
let nbrOfThreads = 8
let step = 2
let itemsPerThread = number * step
let bitLimit = nbrOfThreads * itemsPerThread
var bitfield = [Bool](count: bitLimit, repeatedValue: false)

let queue = dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0 
);
dispatch_apply( Int(nbrOfThreads), queue,
{ ( idx: size_t) -> Void in

let startIndex = itemsPerThread * Int(idx)
let endIndex = min( startIndex + itemsPerThread, 
bitLimit )
if talk { print("Thread[\(idx)] does \(startIndex) ..< 
\(endIndex)")}

var currIndex = startIndex
while( currIndex < endIndex )
{
bitfield[currIndex] = true  //  this 
might crash
currIndex += step
}
}
)
}

But it does not work in Debug builds.

“does not work” means: for !talk and any number > 0 or: talk and number ≥ 110:

malloc: *** error for object 0x101007808: incorrect checksum for freed object 
- object was probably modified after being freed. *** set a breakpoint in 
malloc_error_break to debug

Or:
fatal error: UnsafeMutablePointer.initializeFrom non-following overlapping range

Or:
just plain wrong data in bitfield.

So: is the code ok and the compiler broken in Debug mode?
Or is the code fundamentally wrong and that it works in Release is just a fluke?
If so: how could it be fixed?

Btw.: no problems with bitfield malloced into some UnsafeMutablePointer.

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


Re: [swift-users] Stored Property on Protocol Extension

2016-09-12 Thread Dan Stenmark via swift-users
There's no good way of using extensions to expand the storage of an external 
module's type unless you're using Associated Objects underneath, but that has 
heavy performance implications (especially in threaded cases, which would 
require global locks on the associated object store).  At most, I'd support a 
proposal for stored properties in extensions that reside in the same module  as 
the class declaration, but it sounds like the team has bigger fish to fry right 
now.

If possible, consider subclassing to extend a type's storage instead.

Dan

Sent from my iPhone

> On Sep 12, 2016, at 3:50 PM, Zhao Xin via swift-users  
> wrote:
> 
> ​I don't know why the limit exists. Technical or on purpose. I hope someone 
> inside can answer this.
> 
> Zhaoxin​
> 
>> On Mon, Sep 12, 2016 at 11:55 PM, Daniel Dunbar via swift-users 
>>  wrote:
>> 
>> > On Sep 11, 2016, at 6:12 PM, Tanner Nelson via swift-users 
>> >  wrote:
>> >
>> > Hey Swift Users,
>> >
>> > I was wondering how you all work around not being able to add stored 
>> > properties in extensions (especially protocol extensions).
>> >
>> > I ran into an issue recently where I needed an internal stored variable 
>> > for a protocol, but I didn't want the conformer to worry about 
>> > implementing the variable.
>> >
>> > I ended up using something like this to achieve the effect.
>> >
>> >extension MyProtocol {
>> >private var address: String {
>> >mutating get {
>> >var id = ""
>> >withUnsafePointer(to: ) { id = "\($0)"}
>> >return id
>> 
>> BTW, you can write `return withUnsafePointer(to: ) { "\($0)" }` instead.
>> 
>> >}
>> >}
>> >
>> >var myStoredVar: Bool {
>> >mutating get {
>> >return _storage[address] ?? false
>> >}
>> >set {
>> >_storage[address] = newValue
>> >}
>> >}
>> >}
>> >
>> > Obviously not ideal, but I don't see another way to achieve this besides 
>> > subclassing (which has its own problems for my situation).
>> >
>> > Wondering if anyone has run into this and come up with a better solution 
>> > or other type of work around.
>> 
>> I don't have a better answer to this part.
>> 
>> This particular solution only works if it is ok for `_storage[address]` to 
>> potentially be reused by a new instance, though (if the old instance is 
>> deallocated and the new one is allocated in its place).
>> 
>>  - Daniel
>> 
>> >
>> > Thanks!
>> > Tanner
>> > ___
>> > 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] Stored Property on Protocol Extension

2016-09-12 Thread Zhao Xin via swift-users
​I don't know why the limit exists. Technical or on purpose. I hope someone
inside can answer this.

Zhaoxin​

On Mon, Sep 12, 2016 at 11:55 PM, Daniel Dunbar via swift-users <
swift-users@swift.org> wrote:

>
> > On Sep 11, 2016, at 6:12 PM, Tanner Nelson via swift-users <
> swift-users@swift.org> wrote:
> >
> > Hey Swift Users,
> >
> > I was wondering how you all work around not being able to add stored
> properties in extensions (especially protocol extensions).
> >
> > I ran into an issue recently where I needed an internal stored variable
> for a protocol, but I didn't want the conformer to worry about implementing
> the variable.
> >
> > I ended up using something like this to achieve the effect.
> >
> >extension MyProtocol {
> >private var address: String {
> >mutating get {
> >var id = ""
> >withUnsafePointer(to: ) { id = "\($0)"}
> >return id
>
> BTW, you can write `return withUnsafePointer(to: ) { "\($0)" }`
> instead.
>
> >}
> >}
> >
> >var myStoredVar: Bool {
> >mutating get {
> >return _storage[address] ?? false
> >}
> >set {
> >_storage[address] = newValue
> >}
> >}
> >}
> >
> > Obviously not ideal, but I don't see another way to achieve this besides
> subclassing (which has its own problems for my situation).
> >
> > Wondering if anyone has run into this and come up with a better solution
> or other type of work around.
>
> I don't have a better answer to this part.
>
> This particular solution only works if it is ok for `_storage[address]` to
> potentially be reused by a new instance, though (if the old instance is
> deallocated and the new one is allocated in its place).
>
>  - Daniel
>
> >
> > Thanks!
> > Tanner
> > ___
> > 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] Issues with UITableView*

2016-09-12 Thread Jon Shier via swift-users
UITableView already has the notion of “selected rows” built in, so I’d suggest 
starting there.


Jon

> On Sep 12, 2016, at 6:41 PM, Ole Begemann via swift-users 
>  wrote:
> 
> > Hmm - interesting to know.  Unfortunately, if I do that, then I get
> > NO indication of selection when I click on ANY row.  Perhaps I need
> > to make some other changes to account for the change in how I get the
> > cell?
> 
> You also need to store your cells' selection state someplace outside of the 
> cells themselves. The cells should not be the "source of truth" for the 
> selection state. Otherwise, when you scroll a cell off screen and then scroll 
> it back, it will lose its state.
> 
> So you should store the selection state of each table row somewhere alongside 
> your `locationList` array. Maybe as an array of pairs like this:
> 
>var locationList: [(location: LocationObject, selected: Bool)] = [
>(
>location: LocationObject(name: "name-1", address: "addr-1", phone: 
> "phone-1", latitude: 40.0, longitude: -80.1),
>selected: false
>),
>(
>location: LocationObject(name: "name-2", address: "addr-2", phone: 
> "phone-2", latitude: 40.0, longitude: -80.1),
>selected: false
>)
>]
> 
> There may be better ways to structure your model data, but this should 
> suffice for now.
> 
> Then:
> 
> 1. In `tableView(_:cellForRowAtIndexPath:)`, use the current value of 
> `item.selected` to configure the cell's selection state:
> 
>override func tableView(tableView: UITableView, cellForRowAtIndexPath 
> indexPath: NSIndexPath) -> UITableViewCell {
>let cell = tableView.dequeueReusableCellWithIdentifier("resultCell", 
> forIndexPath: indexPath) as! ExistingLocationTableViewCell
>let item = locationList[indexPath.row]
> 
>cell.nameLabel.text = item.location.name
>cell.locationLabel.text = item.location.address
> 
>cell.accessoryType = item.selected ? .Checkmark : .None
> 
>return cell
>}
> 
> One note: on iOS, the convention for table views is that rows should 
> generally not remain selected after the user lifts their finger. Adding the 
> checkmark should be enough to show a cell's selection state. I would only set 
> the checkmark and leave `cell.selected` as is (I left it out in the code 
> above).
> 
> 2. In `didSelectRow...`, toggle the selection state in your model data:
> 
>override func tableView(tableView: UITableView, didSelectRowAtIndexPath 
> indexPath: NSIndexPath) {
> 
>// Update model
>let row = indexPath.row
>locationList[row].selected = !locationList[row].selected
> 
> To update the UI, you now have two choices. Either ask the table view for the 
> cell at the index path and modify the cell directly:
> 
>// Either do this:
>if let cell = tableView.cellForRowAtIndexPath(indexPath) {
>cell.accessoryType = locationList[row].selected ? .Checkmark : 
> .None
>}
> 
> If you do that, I don't think you need to reload the cell explicitly. 
> Alternatively, tell the table view to reload the cell as you are doing now. 
> It will then call `tableView(_:cellForRowAtIndexPath:)` again, which in turn 
> will configure the cell with your model data:
> 
>// Or this:
>tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
> 
> Finally, fade out the cell selection:
> 
>tableView.deselectRowAtIndexPath(indexPath, animated: true)
>}
> 
> 3. If you are okay with keeping the cells deselected unless the user's finger 
> is onscreen, you don't need to implement `didDeselectRow...` at all.
> 
> (I typed this mostly without help from the compiler as I don't have a Swift 
> 2.x handy, so there may be some errors in the code above.)
> 
> Ole
> ___
> 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] Issues with UITableView*

2016-09-12 Thread Ole Begemann via swift-users

> Hmm - interesting to know.  Unfortunately, if I do that, then I get
> NO indication of selection when I click on ANY row.  Perhaps I need
> to make some other changes to account for the change in how I get the
> cell?

You also need to store your cells' selection state someplace outside of 
the cells themselves. The cells should not be the "source of truth" for 
the selection state. Otherwise, when you scroll a cell off screen and 
then scroll it back, it will lose its state.


So you should store the selection state of each table row somewhere 
alongside your `locationList` array. Maybe as an array of pairs like this:


var locationList: [(location: LocationObject, selected: Bool)] = [
(
location: LocationObject(name: "name-1", address: "addr-1", 
phone: "phone-1", latitude: 40.0, longitude: -80.1),

selected: false
),
(
location: LocationObject(name: "name-2", address: "addr-2", 
phone: "phone-2", latitude: 40.0, longitude: -80.1),

selected: false
)
]

There may be better ways to structure your model data, but this should 
suffice for now.


Then:

1. In `tableView(_:cellForRowAtIndexPath:)`, use the current value of 
`item.selected` to configure the cell's selection state:


override func tableView(tableView: UITableView, 
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = 
tableView.dequeueReusableCellWithIdentifier("resultCell", forIndexPath: 
indexPath) as! ExistingLocationTableViewCell

let item = locationList[indexPath.row]

cell.nameLabel.text = item.location.name
cell.locationLabel.text = item.location.address

cell.accessoryType = item.selected ? .Checkmark : .None

return cell
}

One note: on iOS, the convention for table views is that rows should 
generally not remain selected after the user lifts their finger. Adding 
the checkmark should be enough to show a cell's selection state. I would 
only set the checkmark and leave `cell.selected` as is (I left it out in 
the code above).


2. In `didSelectRow...`, toggle the selection state in your model data:

override func tableView(tableView: UITableView, 
didSelectRowAtIndexPath indexPath: NSIndexPath) {


// Update model
let row = indexPath.row
locationList[row].selected = !locationList[row].selected

To update the UI, you now have two choices. Either ask the table view 
for the cell at the index path and modify the cell directly:


// Either do this:
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.accessoryType = locationList[row].selected ? 
.Checkmark : .None

}

If you do that, I don't think you need to reload the cell explicitly. 
Alternatively, tell the table view to reload the cell as you are doing 
now. It will then call `tableView(_:cellForRowAtIndexPath:)` again, 
which in turn will configure the cell with your model data:


// Or this:
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: 
.None)


Finally, fade out the cell selection:

tableView.deselectRowAtIndexPath(indexPath, animated: true)
}

3. If you are okay with keeping the cells deselected unless the user's 
finger is onscreen, you don't need to implement `didDeselectRow...` at all.


(I typed this mostly without help from the compiler as I don't have a 
Swift 2.x handy, so there may be some errors in the code above.)


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


Re: [swift-users] Swift and Xcode along with Playgrounds is full of bugs

2016-09-12 Thread Shyamal Chandra via swift-users
Hi Jens and mailing list members,

I hope that Chris Lattner and the Swift team can move to that goal very
quickly by following the trend of Go and Rust that have already gone
through that process.  Most of the documentation from different publishers
is going to be outdated very quickly if the syntax and semantics change
significantly.  I hope that the Swift open source team, even outside of
Apple Inc., can come up with an actively added documentation that has
recipes for all the function calls for all the libraries that is constantly
evolving as the language changes with testing done by Jenkins-like server.
  That would be very helpful for developers who need an ever-changing
technical documentation resource for an ever-changing and evolving language.

Thanks!

Best,

Shyamal Chandra
shyam...@gmail.com
Linkedin: http://www.linkedin.com/in/shyamalc
Phone: 620-719-9064

On Mon, Sep 12, 2016 at 5:21 PM, Jens Alfke  wrote:

>
> On Sep 12, 2016, at 3:03 PM, Shyamal Chandra via swift-users <
> swift-users@swift.org> wrote:
>
> Instead of moving onto Swift 3, 4, and 5 (with different syntax), why
> don't you standardize the library and language operations and functions for
> the different package and frameworks included with Xcode
>
>
> That is the goal, and apparently it will happen with Swift 4. It’s a very
> large goal, and if you wanted the Swift designers to hold off on releases
> until it was complete, there’d be no updates to the language for some time.
> Moreover, outside developers would have no input into the changes going on,
> unlike the current development process where anyone can suggest and discuss
> proposals.
>
> Other new languages like Go and Rust have also gone through years of early
> evolution where syntax and APIs changed incompatibly. (In the case of Go,
> it happened prior to 1.0 when hardly anyone was paying attention to it.)
>
> —Jens
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Swift and Xcode along with Playgrounds is full of bugs

2016-09-12 Thread Jens Alfke via swift-users

> On Sep 12, 2016, at 3:03 PM, Shyamal Chandra via swift-users 
>  wrote:
> 
> Instead of moving onto Swift 3, 4, and 5 (with different syntax), why don't 
> you standardize the library and language operations and functions for the 
> different package and frameworks included with Xcode

That is the goal, and apparently it will happen with Swift 4. It’s a very large 
goal, and if you wanted the Swift designers to hold off on releases until it 
was complete, there’d be no updates to the language for some time. Moreover, 
outside developers would have no input into the changes going on, unlike the 
current development process where anyone can suggest and discuss proposals.

Other new languages like Go and Rust have also gone through years of early 
evolution where syntax and APIs changed incompatibly. (In the case of Go, it 
happened prior to 1.0 when hardly anyone was paying attention to it.)

—Jens___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Issues with UITableView*

2016-09-12 Thread Adam Stoller via swift-users
Hmm - interesting to know.  Unfortunately, if I do that, then I get NO 
indication of selection when I click on ANY row.  Perhaps I need to make some 
other changes to account for the change in how I get the cell?

—fish
(Adam Stoller)

> On Sep 12, 2016, at 18:08, Ole Begemann  wrote:
> 
> > The current version of my code seems to satisfy points #1-3, but crashes
> > when attempting to deal with #4 - and I’m not sure that what I’ve done
> > is “good” or “correct” in terms of satisfying the first three points.
> 
> I haven't looked at all of your code, but one thing that could definitely 
> cause problems is that you're calling `dequeueReusableCellWithIdentifier` 
> from `tableView(_:didDeselectRowAtIndexPath:)` and 
> `tableView(_:didSelectRowAtIndexPath`). Don't do that.
> 
> `dequeueReusableCellWithIdentifier` creates a new cell (or fetches an unused 
> one from the table view's reuse pool). You should only ever call it from 
> inside `tableView(_:cellForRowAtIndexPath:)`.
> 
> In `didSelectRow...` and `didDeselectRow...`, you want to ask the table view 
> for the _existing_ cell at the specified index path. Do this with something 
> like:
> 
>if let cell = tableView.cellForRowAtIndexPath(indexPath) {
>// cell found, do something with it
>...
>} else {
>// No cell exists at this index path.
>// This probably doesn't happen in these callbacks,
>// but you never know.
>}
> 
> Note that while `tableView.cellForRowAtIndexPath(indexPath)` looks very much 
> like the data source method you implemented above, it is a different method. 
> This one is a method on `UITableView`, not `UITableViewDataSource`.
> 
> Hope this helps,
> Ole
> 

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


[swift-users] Swift and Xcode along with Playgrounds is full of bugs

2016-09-12 Thread Shyamal Chandra via swift-users
Hi all,

Hope you are doing well!

Swift is very volatile language that keeps on changing with every new
version of Xcode.  When you are trying to run old code with different
syntax, you run into problems because the code is no longer compatible.
Instead of moving onto Swift 3, 4, and 5 (with different syntax), why don't
you standardize the library and language operations and functions for the
different package and frameworks included with Xcode because I have already
submitted multiple bugs to the bug report that are with the official
release of Xcode and I am very disappointed with the software quality.

I hope everyone on the mailing list can chime into this ever-growing
problem with Swift, Playgrounds, and Xcode.

Thanks!

Best,

Shyamal Chandra
shyam...@gmail.com
Linkedin: http://www.linkedin.com/in/shyamalc
Phone: 620-719-9064
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Closure typing changed in Swift 3

2016-09-12 Thread Greg Parker via swift-users

> On Sep 9, 2016, at 8:05 PM, Rick Mann via swift-users  
> wrote:
> 
> I figured it out. The real problem is that .json accepts AnyObject, and the 
> Dictionary is not AnyObject (not sure what this change is, since it worked in 
> Swift 2). Anyway, that confused the type inference, which resulted in the red 
> herring error message about the closure assignment.

What changed is Objective-C bridging. Previously the compiler could convert 
Dictionary to NSDictionary to AnyObject. Now that path is no longer implicitly 
available.


-- 
Greg Parker gpar...@apple.com  Runtime 
Wrangler


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


Re: [swift-users] Canonical way to cast C structs

2016-09-12 Thread Quinn "The Eskimo!" via swift-users

On 12 Sep 2016, at 20:39, Bouke Haarsma via swift-users  
wrote:

> So the question remains on how to perform the casts using Swift?

In general it’s best to avoid special casing your network protocols.  The best 
option for doing that is  and 
 calls.  Specifically, with `getnameinfo`, if you 
specify `NI_NUMERICHOST` it’ll give you back an string representation of the 
address without hitting the DNS.  Better yet, it starts with a (const sockaddr 
*), so you don’t need to extract the IP address from your CFData, you just need 
the base address of that data as the right type, and the `Data` type makes that 
easy.

So, assuming `addrCF` is your CFData, here’s how to get a string representation.

let addr = addrCF as NSData as Data
let saLen = socklen_t(addr.count)
let addrStr = addr.withUnsafeBytes { (sa: UnsafePointer) -> String in
var addrStrC = [CChar](repeating: 0, count: Int(NI_MAXHOST))
let err = getnameinfo(sa, saLen, , saLen, nil, 0, NI_NUMERICHOST | 
NI_NUMERICSERV)
guard err == 0 else { fatalError() }
return String(utf8String: addrStrC)!
}

Share and Enjoy
--
Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware


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


Re: [swift-users] Canonical way to cast C structs

2016-09-12 Thread Bouke Haarsma via swift-users
Sorry for all the pings, but it appears that the code below doesn’t work after 
all;

> fatal error: can't unsafeBitCast between types of different sizes

So the question remains on how to perform the casts using Swift?

—
Bouke

> On 12 sep. 2016, at 21:37, Bouke Haarsma  wrote:
> 
> 
> Sorry, missed the first line when copying:
> 
> let generic = unsafeBitCast(CFDataGetBytePtr(data), to: sockaddr.self)
> switch generic.sa_family {
> case sa_family_t(AF_INET):
> let ipv4 = unsafeBitCast(generic, to: sockaddr_in.self)
> //...
> case sa_family_t(AF_INET6):
> let ipv6 = unsafeBitCast(generic, to: sockaddr_in6.self)
> //...
> default:
> //...
> }
> 
> —
> Bouke
> 
>> On 12 sep. 2016, at 21:35, Bouke Haarsma > > wrote:
>> 
>> Ah the missing part of the puzzle appears to be unsafeBitCast(:to:), so the 
>> Swift version becomes this:
>> 
>> switch generic.sa_family {
>> case sa_family_t(AF_INET):
>> let ipv4 = unsafeBitCast(generic, to: sockaddr_in.self)
>> //...
>> case sa_family_t(AF_INET6):
>> let ipv6 = unsafeBitCast(generic, to: sockaddr_in6.self)
>> //...
>> default:
>> //...
>> }
>> 
>> —
>> Bouke
>> 
>>> On 12 sep. 2016, at 21:25, Bouke Haarsma >> > wrote:
>>> 
>>> Hi all,
>>> 
>>> Inside my CFSocketCallBack a pointer to a sockaddr is provided wrapped in a 
>>> CFData structure. The sockaddr could be either a sockaddr_in (IPv4) or 
>>> sockaddr_in6 (IPv6) struct. In order to discover which struct you’re 
>>> dealing with, the attribute sa_family can be inspected. In C this would 
>>> look something like this:
>>> 
>>> struct sockaddr_storage sa;
>>> 
>>> switch (((sockaddr*))->sa_family)
>>> {
>>> case AF_INET:
>>> inet_ntop(AF_INET, &(((sockaddr_in*))->sin_addr), ...);
>>> break;
>>> case AF_INET6:
>>> inet_ntop(AF_INET6, &(((sockaddr_in6*))->sin6_addr), ...);
>>> break;
>>> }
>>> (from: http://stackoverflow.com/a/13167913 
>>> )
>>> 
>>> Wheras to do this in Swift 3, the only way I found thus far is this:
>>> 
>>> var generic = CFDataGetBytePtr(data).withMemoryRebound(to: sockaddr.self, 
>>> capacity: 1) {
>>> return $0.pointee
>>> }
>>> switch generic.sa_family {
>>> case sa_family_t(AF_INET):
>>> let ipv4 = withUnsafePointer(to: ) {
>>> $0.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
>>> $0.pointee
>>> }
>>> }
>>> //...
>>> case sa_family_t(AF_INET6):
>>> let ipv6 = withUnsafePointer(to: ) {
>>> $0.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) {
>>> $0.pointee
>>> }
>>> }
>>> //...
>>> default:
>>> //…
>>> }
>>> 
>>> This looks very ugly with all the closures and ``withMemoryRebound``. Is 
>>> there a better way to do this? I think there should be something more 
>>> “Swifty”.
>>> 
>>> —
>>> Bouke
>> 
> 

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


Re: [swift-users] Canonical way to cast C structs

2016-09-12 Thread Bouke Haarsma via swift-users

Sorry, missed the first line when copying:

let generic = unsafeBitCast(CFDataGetBytePtr(data), to: sockaddr.self)
switch generic.sa_family {
case sa_family_t(AF_INET):
let ipv4 = unsafeBitCast(generic, to: sockaddr_in.self)
//...
case sa_family_t(AF_INET6):
let ipv6 = unsafeBitCast(generic, to: sockaddr_in6.self)
//...
default:
//...
}

—
Bouke

> On 12 sep. 2016, at 21:35, Bouke Haarsma  wrote:
> 
> Ah the missing part of the puzzle appears to be unsafeBitCast(:to:), so the 
> Swift version becomes this:
> 
> switch generic.sa_family {
> case sa_family_t(AF_INET):
> let ipv4 = unsafeBitCast(generic, to: sockaddr_in.self)
> //...
> case sa_family_t(AF_INET6):
> let ipv6 = unsafeBitCast(generic, to: sockaddr_in6.self)
> //...
> default:
> //...
> }
> 
> —
> Bouke
> 
>> On 12 sep. 2016, at 21:25, Bouke Haarsma > > wrote:
>> 
>> Hi all,
>> 
>> Inside my CFSocketCallBack a pointer to a sockaddr is provided wrapped in a 
>> CFData structure. The sockaddr could be either a sockaddr_in (IPv4) or 
>> sockaddr_in6 (IPv6) struct. In order to discover which struct you’re dealing 
>> with, the attribute sa_family can be inspected. In C this would look 
>> something like this:
>> 
>> struct sockaddr_storage sa;
>> 
>> switch (((sockaddr*))->sa_family)
>> {
>> case AF_INET:
>> inet_ntop(AF_INET, &(((sockaddr_in*))->sin_addr), ...);
>> break;
>> case AF_INET6:
>> inet_ntop(AF_INET6, &(((sockaddr_in6*))->sin6_addr), ...);
>> break;
>> }
>> (from: http://stackoverflow.com/a/13167913 
>> )
>> 
>> Wheras to do this in Swift 3, the only way I found thus far is this:
>> 
>> var generic = CFDataGetBytePtr(data).withMemoryRebound(to: sockaddr.self, 
>> capacity: 1) {
>> return $0.pointee
>> }
>> switch generic.sa_family {
>> case sa_family_t(AF_INET):
>> let ipv4 = withUnsafePointer(to: ) {
>> $0.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
>> $0.pointee
>> }
>> }
>> //...
>> case sa_family_t(AF_INET6):
>> let ipv6 = withUnsafePointer(to: ) {
>> $0.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) {
>> $0.pointee
>> }
>> }
>> //...
>> default:
>> //…
>> }
>> 
>> This looks very ugly with all the closures and ``withMemoryRebound``. Is 
>> there a better way to do this? I think there should be something more 
>> “Swifty”.
>> 
>> —
>> Bouke
> 

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


Re: [swift-users] Canonical way to cast C structs

2016-09-12 Thread Bouke Haarsma via swift-users
Ah the missing part of the puzzle appears to be unsafeBitCast(:to:), so the 
Swift version becomes this:

switch generic.sa_family {
case sa_family_t(AF_INET):
let ipv4 = unsafeBitCast(generic, to: sockaddr_in.self)
//...
case sa_family_t(AF_INET6):
let ipv6 = unsafeBitCast(generic, to: sockaddr_in6.self)
//...
default:
//...
}

—
Bouke

> On 12 sep. 2016, at 21:25, Bouke Haarsma  wrote:
> 
> Hi all,
> 
> Inside my CFSocketCallBack a pointer to a sockaddr is provided wrapped in a 
> CFData structure. The sockaddr could be either a sockaddr_in (IPv4) or 
> sockaddr_in6 (IPv6) struct. In order to discover which struct you’re dealing 
> with, the attribute sa_family can be inspected. In C this would look 
> something like this:
> 
> struct sockaddr_storage sa;
> 
> switch (((sockaddr*))->sa_family)
> {
> case AF_INET:
> inet_ntop(AF_INET, &(((sockaddr_in*))->sin_addr), ...);
> break;
> case AF_INET6:
> inet_ntop(AF_INET6, &(((sockaddr_in6*))->sin6_addr), ...);
> break;
> }
> (from: http://stackoverflow.com/a/13167913 
> )
> 
> Wheras to do this in Swift 3, the only way I found thus far is this:
> 
> var generic = CFDataGetBytePtr(data).withMemoryRebound(to: sockaddr.self, 
> capacity: 1) {
> return $0.pointee
> }
> switch generic.sa_family {
> case sa_family_t(AF_INET):
> let ipv4 = withUnsafePointer(to: ) {
> $0.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
> $0.pointee
> }
> }
> //...
> case sa_family_t(AF_INET6):
> let ipv6 = withUnsafePointer(to: ) {
> $0.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) {
> $0.pointee
> }
> }
> //...
> default:
> //…
> }
> 
> This looks very ugly with all the closures and ``withMemoryRebound``. Is 
> there a better way to do this? I think there should be something more 
> “Swifty”.
> 
> —
> Bouke

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


Re: [swift-users] Provide native Decimal data type

2016-09-12 Thread Stephen Canon via swift-users

> On Sep 12, 2016, at 1:26 PM, Jens Alfke via swift-users 
>  wrote:
> 
>> On Sep 12, 2016, at 10:10 AM, Teej . via swift-users > > wrote:
>> 
>>  …in spite of the CPU’s quirks in handling floating point numbers in a 
>> maddening inaccurate manner.
> 
> Well, in the CPU’s defense, it’s only inaccurate because the puny humans 
> insist on dividing their currency into fractions of 1/10, which has no exact 
> representation in binary. (Apparently this is an ancient tradition 
> commemorating the number of bony outgrowths on certain extremities of their 
> grotesque meat-bodies.) I could — I mean, the computers could — point out 
> that if we divided our currency units into 7 pieces, our precious decimal 
> numbers would quickly become inaccurate too. :)

Expanding a bit on what Jens wrote here: decimal (unlike friendship) is not 
magic.  All computer models of real-number arithmetic are necessarily inexact, 
because (almost all) real numbers are not computable.  There are a bunch of 
reasonable choices that one can make, however (this is not an exhaustive list, 
just a sampling of the design space):

Binary floating point
Pro: represents modest integers exactly, extremely fast hardware 
implementations, fixed memory size, and rounding errors are extremely 
uniform—they don’t vary much with the number being represented.
Con: almost no decimal fractions have exact representations.

Decimal floating point
Pro: represents modest integers and decimal fractions exactly, slower than 
binary but still faster than almost anything else, fixed memory size.
Con: at least an order of magnitude slower than binary floating-point, and 
rounding error is significantly less scale-invariant.

Fixed-size rationals
Pro: represents all modestly-sized integers and fractions exactly, fixed memory 
size, four basic operations are exact until you hit the limits of 
representation.
Con: denominators quickly grow too quickly to be used for non-trivial 
computations (this is usually a deal-breaker).

Arbitrary-precision rationals
Pro: closed under four basic operations, represents most numbers most people 
will use exactly.
Con: representations get extremely large extremely quickly, large memory 
footprint if you have more than a few numbers.

Computable real numbers
Pro: any number you can describe, you can work with.
Con: your numbers are now computer programs, and you arithmetic system is 
Turing-complete.  Testing for equality is equivalent to solving the halting 
problem.

> Teej . via swift-users > 
> wrote:
> 

> It still does not answer my question on why we can’t just provide a decimal 
> data type.

The only problem here is the “just”.  We can and will provide a decimal data 
type.  Like many other language changes, that we can and will do, it requires 
engineering time, and there are finite engineering resources available to work 
on it.

Keep in mind that decimal will not magically solve all accuracy problems, 
however.  1/3 is just as inaccurate in decimal as it is in binary 
floating-point (actually, it’s less accurate in decimal than in a comparable 
binary format due to the aforementioned non-uniformity of decimal rounding 
error).

– Steve___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Provide native Decimal data type

2016-09-12 Thread Teej . via swift-users
I agree on your point — base-10 notation is not compatible with a base-2 
infrastructure.  However, that is just exposing the reality of the floating 
point data type.  It still does not answer my question on why we can’t just 
provide a decimal data type.  

I am aware of the NSDecimalNumber class.  But that is a layer on top of the 
core language, and not very performant relatively speaking - at least I would 
presume?  Please correct me if I am wrong.

-T.J.


> On Sep 12, 2016, at 10:26, Jens Alfke  wrote:
> 
> 
>> On Sep 12, 2016, at 10:10 AM, Teej . via swift-users > > wrote:
>> 
>>  …in spite of the CPU’s quirks in handling floating point numbers in a 
>> maddening inaccurate manner.
> 
> Well, in the CPU’s defense, it’s only inaccurate because the puny humans 
> insist on dividing their currency into fractions of 1/10, which has no exact 
> representation in binary. (Apparently this is an ancient tradition 
> commemorating the number of bony outgrowths on certain extremities of their 
> grotesque meat-bodies.) I could — I mean, the computers could — point out 
> that if we divided our currency units into 7 pieces, our precious decimal 
> numbers would quickly become inaccurate too. :)
> 
>>  Is there any particular reason why we do not have a native Decimal data 
>> type for Swift?  
> 
> Cocoa’s Foundation framework has an NSDecimalNumber class that provides 
> decimal numbers and arithmetic. The class docs for that include a note that 
> "The Swift overlay to the Foundation framework provides the Decimal 
> structure, which bridges to the NSDecimalNumber class. The Decimalvalue type 
> offers the same functionality as the NSDecimalNumberreference type, and the 
> two can be used interchangeably in Swift code that interacts with Objective-C 
> APIs."
> 
> The question is whether this has been ported to the in-progress native Swift 
> foundation library yet. I haven’t checked.
> 
> —Jens

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


Re: [swift-users] Provide native Decimal data type

2016-09-12 Thread Jens Alfke via swift-users

> On Sep 12, 2016, at 10:10 AM, Teej . via swift-users  
> wrote:
> 
>   …in spite of the CPU’s quirks in handling floating point numbers in a 
> maddening inaccurate manner.

Well, in the CPU’s defense, it’s only inaccurate because the puny humans insist 
on dividing their currency into fractions of 1/10, which has no exact 
representation in binary. (Apparently this is an ancient tradition 
commemorating the number of bony outgrowths on certain extremities of their 
grotesque meat-bodies.) I could — I mean, the computers could — point out that 
if we divided our currency units into 7 pieces, our precious decimal numbers 
would quickly become inaccurate too. :)

>   Is there any particular reason why we do not have a native Decimal data 
> type for Swift?  

Cocoa’s Foundation framework has an NSDecimalNumber class that provides decimal 
numbers and arithmetic. The class docs for that include a note that "The Swift 
overlay to the Foundation framework provides the Decimal structure, which 
bridges to the NSDecimalNumber class. The Decimalvalue type offers the same 
functionality as the NSDecimalNumberreference type, and the two can be used 
interchangeably in Swift code that interacts with Objective-C APIs."

The question is whether this has been ported to the in-progress native Swift 
foundation library yet. I haven’t checked.

—Jens___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Provide native Decimal data type

2016-09-12 Thread Teej . via swift-users
Please forgive me if this have already been hashed out.  Google and 
DuckDuckGo have not been helpful in my research, and the archives do not have a 
search functionality.

I am new to Swift, and starting from 3.0 beta.  I am aware that the 
language is not stabilized, so I feel this is an opportunity to introduce a 
native data type.

Over history, data types typically follows what the CPU supports, so 
hence the int/float datatypes.  char/String is technically an integer/array of 
integers under the hood (and unicode-supported Strings are a bit more 
complicated than that).  Among customers I work with, data accuracy is very 
important.  So when the only option for a value with a fractional portion does 
not guarantee data accuracy, such as:

return 3.0 * sideLength - 9.3001

It gives us pause, as floating point numbers are always understood to 
be inaccurate, and the whole song and dance required to truncate/round the 
number to ensure accurate results make our financial customers very nervous.  
They want accuracy from the start and whenever they audit the results in the 
middle of the process, they expect to see a 9.3 on the dot.  

Having a native Decimal datatype would ensure that we have a consistent 
handling option for pulling and putting data to databases.  Having worked with 
APT_Decimal within Orchestrate/PX Engine, I know we can do a better job if we 
could leverage the speed of float, but somehow ensure that even with that 
speed, we preserve the accuracy of the actual data in spite of the CPU’s quirks 
in handling floating point numbers in a maddening inaccurate manner.

Is there any particular reason why we do not have a native Decimal data 
type for Swift?  

-T.J.

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


Re: [swift-users] Stored Property on Protocol Extension

2016-09-12 Thread Daniel Dunbar via swift-users

> On Sep 11, 2016, at 6:12 PM, Tanner Nelson via swift-users 
>  wrote:
> 
> Hey Swift Users,
> 
> I was wondering how you all work around not being able to add stored 
> properties in extensions (especially protocol extensions).
> 
> I ran into an issue recently where I needed an internal stored variable for a 
> protocol, but I didn't want the conformer to worry about implementing the 
> variable.
> 
> I ended up using something like this to achieve the effect.
> 
>extension MyProtocol {
>private var address: String {
>mutating get {
>var id = ""
>withUnsafePointer(to: ) { id = "\($0)"}
>return id

BTW, you can write `return withUnsafePointer(to: ) { "\($0)" }` instead.

>}
>}
> 
>var myStoredVar: Bool {
>mutating get {
>return _storage[address] ?? false
>}
>set {
>_storage[address] = newValue
>}
>}
>}
> 
> Obviously not ideal, but I don't see another way to achieve this besides 
> subclassing (which has its own problems for my situation).
> 
> Wondering if anyone has run into this and come up with a better solution or 
> other type of work around.

I don't have a better answer to this part.

This particular solution only works if it is ok for `_storage[address]` to 
potentially be reused by a new instance, though (if the old instance is 
deallocated and the new one is allocated in its place).

 - Daniel

> 
> Thanks!
> Tanner
> ___
> 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] Stored Property on Protocol Extension

2016-09-12 Thread Tanner Nelson via swift-users
Hey Swift Users,

I was wondering how you all work around not being able to add stored properties 
in extensions (especially protocol extensions).

I ran into an issue recently where I needed an internal stored variable for a 
protocol, but I didn't want the conformer to worry about implementing the 
variable.

I ended up using something like this to achieve the effect.

extension MyProtocol {
private var address: String {
mutating get {
var id = ""
withUnsafePointer(to: ) { id = "\($0)"}
return id
}
}

var myStoredVar: Bool {
mutating get {
return _storage[address] ?? false
}
set {
_storage[address] = newValue
}
}
}

Obviously not ideal, but I don't see another way to achieve this besides 
subclassing (which has its own problems for my situation).

Wondering if anyone has run into this and come up with a better solution or 
other type of work around.

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


Re: [swift-users] UnsafeMutablePointer Swift 3 conversion

2016-09-12 Thread Patrice Kouame via swift-users
Andy - yes thanks for the guidance and great job on your guide. 
There's a lot to absorb there. I think the metal samples are another great use 
case for your new apis. I have a small side project in mind to
analyze its impact on performance, comparing the swift 3 compliant "safe" 
implementation versus straight objective-c.

P.


> On Sep 8, 2016, at 1:35 PM, Andrew Trick via swift-users 
>  wrote:
> 
> 
>> On Sep 8, 2016, at 4:04 AM, Gerard Iglesias  wrote:
>> 
>> Andrew,
>> 
>> Thank you for the compliment ;)
>> 
>> And thank you for the 2 advices
>> 
>> And the question about use of size or stride ? I understand that the 
>> underlaying float data are aligned in this specific case, but I wonder in 
>> fact if the shader compiler align memory the same way the swift compiler do, 
>> I suppose yes unless it would be a nightmare, but murphy’s principle says me 
>> … take care ;)
> 
> Always use stride for contiguous in-memory values.
> 
> -Andy
> 
>> 
>> Thanks in advance
>> 
>> Gerard
>> 
 On 8 Sep 2016, at 07:21, Andrew Trick  wrote:
 
 
 On Sep 3, 2016, at 6:03 PM, Gerard Iglesias via swift-users 
  wrote:
 
 This is my funny version… I succeeded and I didn’t come back to find an 
 other way…
 
 // Grab a pointer to the constant buffer's data store
 // Since we are using Swift, it is easier to cast the pointer to the 
 ShadowPass type to fill the constant buffer
 // We need to make a copy of these so the block captures the correct data
 
 //let shadowPtr = 
 UnsafeMutablePointer(constantBufferForFrame.contents())
 let shadowPtr = constantBufferForFrame.contents().assumingMemoryBound(to: 
 ShadowPass.self)
 shadowPtr.pointee = shadowPassData[0]

 //More Swift specific stuff - advance pointer and cast to MainPass
 
 //let mainPtr = UnsafeMutablePointer(shadowPtr.advanced(by: 1))
 let mainPtr = constantBufferForFrame.contents().advanced(by: 
 MemoryLayout.size).assumingMemoryBound(to: MainPass.self)
 mainPtr.pointee = mainPassFrameData

 //Advance and cast to ObjectData
 
 //var ptr = UnsafeMutablePointer(mainPtr.advanced(by: 1))
 var ptr = constantBufferForFrame.contents().advanced(by: 
 MemoryLayout.size + 
 MemoryLayout.size).assumingMemoryBound(to: ObjectData.self)
>>> 
>>> Gerard,
>>> 
>>> I like your code. A couple of things to consider:
>>> 
>>> 1. If the memory has never been bound to a type (i.e. it's straight from 
>>> MTLBuffer.newBuffer), then rather than “assuming” memory is bound to these 
>>> types, you should just bind it here (substitute all your 
>>> assumingMemoryBound(to: _) with bindMemory(to: _, capacity: 1). Think of it 
>>> as two-phase initialization of the memory. First declare the memory's type 
>>> (e.g. some structure that holds a bunch of floats), then write individual 
>>> float values into the memory.
>>> 
>>> 2. If you want the compiler to compute byte offsets for you like the 
>>> original code, then can be done as follows:
>>> 
>>>   let mainPtr = UnsafeMutableRawPointer(shadowPtr + 1).bindMemory(
>>> to: MainPass.self, capacity: 1)
>>>   mainPtr.pointee = mainPassFrameData
>>>   ...
>>> 
>>> However, your approach of computing byte offsets is more explicit.
>>> 
>>> My migration guide landed on swift.org today! I think it will be a big help.
>>> https://swift.org/migration-guide/se-0107-migrate.html
>>> 
>>> -Andy
>>> 
> On 3 Sep 2016, at 19:22, Patrice Kouame  wrote:
> 
> Gerard- 
> 
> Excellent!  Looking forward to seeing your fix (hoping you get your book 
> back soon ;-) )
> 
> I think Xcode/Swift gags on the last ptr advance to objectData.  I 
> recently tried another variant using withUnsafeMutablePointer like this:
> 
> var ptr : UnsafeMutablePointer  = 
> withUnsafeMutablePointer(to: ) {
> $0.withMemoryRebound(to: ObjectData.self, capacity: 
> objectsToRender) {
> $0.pointee = renderables[0].objectData
> }
> }
> 
> ..but still crashes with no hints.
> 
> My bug report also mentions that the Xcode migration/conversion tool is 
> incomplete.  
> It handles the “simpler" UnsafeMutableRawPointer to 
> UnsafeMutablePonter with bindMemory cases correctly (one still has to 
> mind the capacity value though)
> In all fairness, migrating/converting automagically in these cases is 
> always a little bit tricky - the proposed Xcode fixes should always be 
> reviewed by a human...
> 
> Patrice
> 
>> On Sep 3, 2016, at 1:05 PM, Gerard Iglesias via swift-users 
>>  wrote:
>> 
>> Ok
>> 
>> For the record I succeeded this transformation phase last week
>> 
>> I remember the 

Re: [swift-users] Lazy expression is ambiguous?

2016-09-12 Thread Quinn "The Eskimo!" via swift-users

On 12 Sep 2016, at 09:20, Rick Mann  wrote:

> I've always wondered why that was the case.

Implementing `dispatch_once` so that it’s fast on all CPU architectures, 
including those with a weak memory model, requires that ‘once token’:

* be initialised to 0 before `dispatch_once` sees it

* not modified by anything other than `dispatch_once`

That’s true for [switching to Obj-C terminology here] global variables, which 
are initialised by the linker to 0 before any instruction in the process runs, 
but it’s not true for ivars.

If you want to see how this really works, you can check out the source in 
Darwin.



Frankly, it hurts my brain )-:

Share and Enjoy
--
Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware


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


Re: [swift-users] Lazy expression is ambiguous?

2016-09-12 Thread Rick Mann via swift-users

> On Sep 12, 2016, at 00:53 , Quinn The Eskimo! via swift-users 
>  wrote:
> 
> 
> On 12 Sep 2016, at 08:46, Rick Mann  wrote:
> 
>> I had assumed lazy worked like static, which I understand uses dispatch_once 
>> under the hood.
> 
> Correct.
> 
> [I’m not sure if it actually /uses/ `dispatch_once` specifically, but it has 
> the same semantics.]
> 
>> Would that be a reasonable thing for lazy to do?
> 
> It certainly would be nice.  I suspect that this would be hard to implement 
> because the restrictions associated with `dispatch_once` are pretty tight.  
> OTOH, if you’d like to see it work this way it wouldn’t hurt to file an 
> enhancement request.

Oh, right, because it seems to need a static or global variable for the flag. 
I've always wondered why that was the case. Seems like any flag would do (like 
a member variable), and if that results in a second dispatch because it's a 
second flag, that's okay.

In any case, thanks for all the clarification.

> 
> Share and Enjoy
> --
> Quinn "The Eskimo!"
> Apple Developer Relations, Developer Technical Support, Core OS/Hardware
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users


-- 
Rick Mann
rm...@latencyzero.com


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


Re: [swift-users] Lazy expression is ambiguous?

2016-09-12 Thread Quinn "The Eskimo!" via swift-users

On 12 Sep 2016, at 08:53, Quinn The Eskimo! via swift-users 
 wrote:

> On 12 Sep 2016, at 08:46, Rick Mann  wrote:
> 
>> I had assumed lazy worked like static, which I understand uses dispatch_once 
>> under the hood.
> 
> Correct.

Re-reading the above I realise that it was ambiguous.  Let’s try that again.

   *   *   *

On 12 Sep 2016, at 08:46, Rick Mann  wrote:

> I had assumed lazy worked like static …

No, alas.

> which I understand uses dispatch_once under the hood.

Your understanding of `static` is correct.

Share and Enjoy
--
Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware


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


Re: [swift-users] Lazy expression is ambiguous?

2016-09-12 Thread Quinn "The Eskimo!" via swift-users

On 12 Sep 2016, at 08:46, Rick Mann  wrote:

> I had assumed lazy worked like static, which I understand uses dispatch_once 
> under the hood.

Correct.

[I’m not sure if it actually /uses/ `dispatch_once` specifically, but it has 
the same semantics.]

> Would that be a reasonable thing for lazy to do?

It certainly would be nice.  I suspect that this would be hard to implement 
because the restrictions associated with `dispatch_once` are pretty tight.  
OTOH, if you’d like to see it work this way it wouldn’t hurt to file an 
enhancement request.

Share and Enjoy
--
Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware


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


Re: [swift-users] Lazy expression is ambiguous?

2016-09-12 Thread Quinn "The Eskimo!" via swift-users

On 12 Sep 2016, at 08:28, Zhao Xin  wrote:

> It is not a bug. 

I disagree.

> You must explicitly specify the variable's type if you use `lazy` keyword.


No, that’s not the case in general.  For example, the following code compiles 
just fine.

  import Dispatch

  func queueMaker() -> DispatchQueue {
return DispatchQueue(label: "Op", attributes: .concurrent)
  }

  class MyClass {
lazy var myQ = queueMaker()
  }

Regardless, there’s two possibilities here:

A. this is a real restriction in the language, which makes the poor diagnostic 
bugworthy

B. this is a false restriction, which makes it bugworthy in and of itself

While I personally believe that B is the case here, that’s really besides the 
point; something, either A or B, should change, and hence my advice.

Share and Enjoy
--
Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

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


Re: [swift-users] Lazy expression is ambiguous?

2016-09-12 Thread Rick Mann via swift-users

> On Sep 12, 2016, at 00:02 , Quinn The Eskimo! via swift-users 
>  wrote:
> 
> 
> On 12 Sep 2016, at 06:40, Jacob Bandes-Storch via swift-users 
>  wrote:
> 
>> I'd recommend filing a bug at bugs.swift.org.
> 
> Agreed.

Done. https://bugs.swift.org/browse/SR-2616

> Also, you can work around this by adding a type.
> 
>  lazy var myQ: DispatchQueue = DispatchQueue(label: "Op", attributes: 
> .concurrent)

Sure, it just didn't seem to make sense.

> Also, with regards this specific example, be aware that lazy properties 
> aren’t guaranteed to be initialised only once.  To quote “The Swift 
> Programming Language”:
> 
>If a property marked with the `lazy` modified is accessed by multiple 
>threads simultaneously and the property has not yet been initialized, 
>there is no guarantee that the property will be initialized only once.
> 
> I’m struggling to think of a case where that limitation is acceptable in the 
> context of a dispatch queue (-:

Thank you for that explanation. I had assumed lazy worked like static, which I 
understand uses dispatch_once under the hood. Would that be a reasonable thing 
for lazy to do?

In the end I didn't use a property for the queue, but rather just created it at 
point of use (I'm testing to see whether or not the enqueued blocks retain the 
queue; that's all I need).

-- 
Rick Mann
rm...@latencyzero.com


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


Re: [swift-users] Lazy expression is ambiguous?

2016-09-12 Thread Rick Mann via swift-users
Done. https://bugs.swift.org/browse/SR-2616

> On Sep 11, 2016, at 22:40 , Jacob Bandes-Storch  wrote:
> 
> This problem seems to occur when using an initializer with some default 
> argument values. The following code also exhibits the issue:
> 
> struct Bar {
>   init(x: Int, y: Int? = 42) { }
> }
> 
> class Foo {
>   lazy var myQ = Bar(x: 3)
> }
> 
> 
> I'd recommend filing a bug at bugs.swift.org.
> 
> On Sun, Sep 11, 2016 at 10:19 PM, Rick Mann via swift-users 
>  wrote:
> I get this error in the following code: "Type of expression is ambiguous 
> without more context", on the DispatchQueue. But only if I mark it as "lazy", 
> and not if I don't. I'm not sure why.
> 
> class
> myClass
> {
>   lazy var myQ = DispatchQueue(label: "Op", attributes: .concurrent)// 
> <-- ERROR
>  ^Type of expression is ambiguous without more context
> }
> 
> Would someone please explain? Thank you.
> 
> --
> Rick Mann
> rm...@latencyzero.com
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
> 


-- 
Rick Mann
rm...@latencyzero.com


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


Re: [swift-users] Lazy expression is ambiguous?

2016-09-12 Thread Zhao Xin via swift-users
It is not a bug. You must explicitly specify the variable's type if you use
`lazy` keyword. `lazy` means the variable will be initialized later, but
the compiler needs its type right now.

Zhaoxin

On Mon, Sep 12, 2016 at 3:02 PM, Quinn "The Eskimo!" via swift-users <
swift-users@swift.org> wrote:

>
> On 12 Sep 2016, at 06:40, Jacob Bandes-Storch via swift-users <
> swift-users@swift.org> wrote:
>
> > I'd recommend filing a bug at bugs.swift.org.
>
> Agreed.
>
> Also, you can work around this by adding a type.
>
>   lazy var myQ: DispatchQueue = DispatchQueue(label: "Op", attributes:
> .concurrent)
>
> Also, with regards this specific example, be aware that lazy properties
> aren’t guaranteed to be initialised only once.  To quote “The Swift
> Programming Language”:
>
> If a property marked with the `lazy` modified is accessed by multiple
> threads simultaneously and the property has not yet been initialized,
> there is no guarantee that the property will be initialized only once.
>
> I’m struggling to think of a case where that limitation is acceptable in
> the context of a dispatch queue (-:
>
> Share and Enjoy
> --
> Quinn "The Eskimo!"
> Apple Developer Relations, Developer Technical Support, Core OS/Hardware
>
>
> ___
> 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] Lazy expression is ambiguous?

2016-09-12 Thread Quinn "The Eskimo!" via swift-users

On 12 Sep 2016, at 06:40, Jacob Bandes-Storch via swift-users 
 wrote:

> I'd recommend filing a bug at bugs.swift.org.

Agreed.

Also, you can work around this by adding a type.

  lazy var myQ: DispatchQueue = DispatchQueue(label: "Op", attributes: 
.concurrent)

Also, with regards this specific example, be aware that lazy properties aren’t 
guaranteed to be initialised only once.  To quote “The Swift Programming 
Language”:

If a property marked with the `lazy` modified is accessed by multiple 
threads simultaneously and the property has not yet been initialized, 
there is no guarantee that the property will be initialized only once.

I’m struggling to think of a case where that limitation is acceptable in the 
context of a dispatch queue (-:

Share and Enjoy
--
Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware


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