[swift-users] Decoding dates with dateDecodingStrategy

2017-10-22 Thread Ray Fix via swift-users

I had a question about date deserialization.  If a container (or its 
sub-containers) has dates in multiple formats, is the best way to go about it 
to decode a string and then run each one through a custom date formatter?

 It seems strange to me that dateDecodingStrategy is a top-level decoder 
concern rather than being part of an individual date decode method.  In my 
custom init(from decoder: Decoder) methods, I want to put the knowledge in 
there instead of relying on something from outside to set it correctly.  Maybe 
I am missing something?

Thanks as always for any insights you can share with me.

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


Re: [swift-users] Constraining the conforming type of a protocol

2017-07-30 Thread Ray Fix via swift-users
Cool.  Thanks for your comment.  Done.  

https://bugs.swift.org/browse/SR-5581 <https://bugs.swift.org/browse/SR-5581>

Ray


> On Jul 29, 2017, at 5:55 PM, Slava Pestov <spes...@apple.com> wrote:
> 
> What you’re trying to do should be equivalent to this:
> 
> protocol Toggling : Equatable {
>   …
> }
> 
> It’s a bug that placing the constraint on ‘Self’ does not have the same 
> effect though; do you mind filing a JIRA?
> 
> Slava
> 
>> On Jul 29, 2017, at 12:24 PM, Ray Fix via swift-users <swift-users@swift.org 
>> <mailto:swift-users@swift.org>> wrote:
>> 
>> Hi,
>> 
>> I had a question about defining protocols. Originally I wrote:
>> 
>> protocol Toggling where Self: Equatable {
>>   static var all: [Self] { get }
>>   func toggled() -> Self
>>   mutating func toggle()
>> }
>> 
>> extension Toggling {
>> 
>>   func toggled() -> Self {
>> let current = Self.all.index(of: self) ?? 0
>> let next = (current + 1) % Self.all.count
>> return Self.all[next]
>>   }
>> 
>>   mutating func toggle() {
>> self = toggled()
>>   }
>> }
>> 
>> This resulted in a bunch of errors.  
>> 
>> Playground execution failed:
>>  ^
>> error: Toggler.playground:7:28: error: cannot invoke 'index' with an 
>> argument list of type '(of: Self)'
>> let current = Self.all.index(of: self) ?? 0
>>^
>> 
>> Toggler.playground:7:28: note: expected an argument list of type '(of: 
>> Self.Element)'
>> let current = Self.all.index(of: self) ?? 0
>> 
>> This approach worked:
>> 
>> 
>> protocol Toggling {
>>   static var all: [Self] { get }
>>   func toggled() -> Self
>>   mutating func toggle()
>> }
>> 
>> extension Toggling where Self: Equatable {
>> 
>>   func toggled() -> Self {
>> let current = Self.all.index(of: self) ?? 0
>> let next = (current + 1) % Self.all.count
>> return Self.all[next]
>>   }
>> 
>>   mutating func toggle() {
>> self = toggled()
>>   }
>> }
>> 
>> This version is probably better anyway but I am wondering if the first 
>> approach should have shown an error at the point of trying to attach the 
>> constraint to the protocol declaration.  Any insights on this?
>> 
>> Thank you,
>> Ray  Fix
>> 
>> 
>> 
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org <mailto: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] Constraining the conforming type of a protocol

2017-07-29 Thread Ray Fix via swift-users
Hi,

I had a question about defining protocols. Originally I wrote:

protocol Toggling where Self: Equatable {
  static var all: [Self] { get }
  func toggled() -> Self
  mutating func toggle()
}

extension Toggling {

  func toggled() -> Self {
let current = Self.all.index(of: self) ?? 0
let next = (current + 1) % Self.all.count
return Self.all[next]
  }

  mutating func toggle() {
self = toggled()
  }
}

This resulted in a bunch of errors.  

Playground execution failed:
 ^
error: Toggler.playground:7:28: error: cannot invoke 'index' with an argument 
list of type '(of: Self)'
let current = Self.all.index(of: self) ?? 0
   ^

Toggler.playground:7:28: note: expected an argument list of type '(of: 
Self.Element)'
let current = Self.all.index(of: self) ?? 0

This approach worked:


protocol Toggling {
  static var all: [Self] { get }
  func toggled() -> Self
  mutating func toggle()
}

extension Toggling where Self: Equatable {

  func toggled() -> Self {
let current = Self.all.index(of: self) ?? 0
let next = (current + 1) % Self.all.count
return Self.all[next]
  }

  mutating func toggle() {
self = toggled()
  }
}

This version is probably better anyway but I am wondering if the first approach 
should have shown an error at the point of trying to attach the constraint to 
the protocol declaration.  Any insights on this?

Thank you,
Ray  Fix




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


Re: [swift-users] withoutActuallyEscaping example question

2017-03-26 Thread Ray Fix via swift-users
Wow.  Thanks for the explanation! I didn’t realize I was toggling between 
different overloads but that makes sense now.

Thanks again,
Ray

PS: It is sort of a strange example in the first place (being lazy and then 
immediately eager.)  I don’t think it is a use case that is compelling enough 
to consider overload resolution rules over.

> On Mar 26, 2017, at 1:21 AM, Slava Pestov <spes...@apple.com> wrote:
> 
> Here’s another fun one: the following type checks despite the literal 
> closure; we’ve constrained the return type of filter() to [Int], and not 
> LazyFilterCollection, so again the type checker picks the overload that 
> takes the non-escaping closure:
> 
> func myFilter(array: [Int], predicate: (Int) -> Bool) -> [Int] {
>   return array.lazy.filter { predicate($0) }
> }
> 
> Slava
> 
>> On Mar 26, 2017, at 1:14 AM, Slava Pestov via swift-users 
>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>> 
>> Hi Ray,
>> 
>> There are two overloads of filter() available on ‘array.lazy’; the version 
>> that takes an escaping closure and returns a LazyFilterCollection, and the 
>> version that takes a non-escaping closure and returns [Int].
>> 
>> In the first example, we pick the LazyFilterCollection-returning overload, 
>> because the literal closure { predicate($0) } can be coerced to both an 
>> escaping or a non-escaping closure type, and in the absence of additional 
>> constraints we go with the overload from a concrete type over an overload in 
>> a protocol extension. After the overload has been picked we validate the 
>> body of the closure, and notice that it is invalid because whole the closure 
>> is already known to be @escaping, it references the non-@escaping 
>> ‘predicate’.
>> 
>> In the second example, ‘predicate’ is known to be non-@escaping, which rules 
>> out the first overload completely, so we go with the second overload and 
>> perform a non-lazy filter.
>> 
>> I would argue this is somewhat confusing, but it might be difficult to 
>> change the overload resolution rules in a way where the first overload is 
>> always chosen.
>> 
>> Slava
>> 
>>> On Mar 26, 2017, at 12:13 AM, Ray Fix via swift-users 
>>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>>> 
>>> 
>>> Hi,
>>> 
>>> One of the motivating examples for withoutActuallyEscaping looks like the 
>>> following.  This predictably  doesn’t work because "use of non-escaping 
>>> parameter 'predicate' may allow it to escape"
>>> 
>>> func myFilter(array: [Int], predicate: (Int) -> Bool) -> [Int] {
>>>   return Array(array.lazy.filter { predicate($0) })
>>> }
>>> 
>>> The solution is to use withoutActuallyEscaping.  This works and produces 
>>> the expected results.
>>> 
>>> func myFilter(array: [Int], predicate: (Int) -> Bool) -> [Int] {
>>>   return withoutActuallyEscaping(predicate) { predicate in
>>> Array(array.lazy.filter({predicate($0)}))
>>>   }
>>> }
>>> 
>>> What I find puzzling is the below example compiles and runs correctly. It 
>>> seems like it should be the same compiler error as in the first example.
>>> 
>>> func myFilter(array: [Int], predicate: (Int) -> Bool) -> [Int] {
>>>   return Array(array.lazy.filter(predicate))
>>> }
>>> 
>>> If you understand why this is so, it would be very helpful.
>>> 
>>> Thank you and best wishes,
>>> Ray
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org <mailto:swift-users@swift.org>
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> <https://lists.swift.org/mailman/listinfo/swift-users>
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org <mailto: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] unowned self in closure in a playground

2017-02-21 Thread Ray Fix via swift-users

> On Feb 21, 2017, at 7:32 PM, rintaro ishizaki  wrote:
> 
> lifetime guaranteed to be around until the method call completes
> 
> AFAIK, this is true.
> However, in this case, it's not a method call. The lifetime is only 
> guaranteed until getter:increment completes.
> 
> Demo().increment(3)
> |--| lifetime
> 

Thanks!  This is an interesting explanation.  

It is curious that naming the variable cases different behavior.
IOW, this doesn’t have a problem:

let demo = Demo()
demo.increment(3)

Lifetime seems to last the entire expression. 

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


Re: [swift-users] unowned self in closure in a playground

2017-02-21 Thread Ray Fix via swift-users
Thanks. My comment below.

> 
> On Feb 21, 2017, at 11:18 AM, Marco S Hyman  wrote:
> 
>> The following code crashes:
>> 
>> class Demo {
>>  var value = 0
>>  lazy var increment: (Int) -> Void = { [unowned self] by in
>>self.value += by
>>print(self.value)
>>  }
>> }
>> 
>> Demo().increment(3)
>> error: Playground execution aborted: error: Execution was interrupted, 
>> reason: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0).
> 
> value is not a static/class variable.   Without an instance of Demo it does 
> not exist.  This seems to work.
> 
> class Demo {
>  static var value = 0
>  lazy var increment: (Int) -> Void = { [unowned self] by in
>value += by
>print(value)
>  }
> }
> 

The problem with this solution is that this changes the semantics.  I want a 
value for every Demo instance.

Ray

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


[swift-users] unowned self in closure in a playground

2017-02-21 Thread Ray Fix via swift-users
Hi,

The following code crashes:

class Demo {
  var value = 0
  lazy var increment: (Int) -> Void = { [unowned self] by in
self.value += by
print(self.value)
  }
 }

Demo().increment(3)
error: Playground execution aborted: error: Execution was interrupted, reason: 
EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0).

However if I call it this way:

do {
  let demo = Demo()
  demo.increment(3)
}

All is well.  This breaks my mental model of lifetime guaranteed to be around 
until the method call completes.
Is it me that is wrong or the playground.  Is the second way working just by 
luck?___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Initializer accessing self

2017-02-01 Thread Ray Fix via swift-users

In the working version, I think the timer is first set to nil and then changed 
to the scheduled timer.  In the non-working case time can only be set exactly 
once and self access is not legal until after it is set.

Ray


> On Feb 1, 2017, at 8:06 PM, Brandon Knope via swift-users 
>  wrote:
> 
> class Test {
> let timer: Timer!
> 
> init() {
> timer = Timer.scheduledTimer(timeInterval: 20, target: self, 
> selector: #selector(test(_:)), userInfo: nil, repeats: true)
> }
> 
> @objc func test(_ timer: Timer) {
> 
> }
> }

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


Re: [swift-users] Array elements assign to variables

2017-01-27 Thread Ray Fix via swift-users
How about:

typealias PixelTuple = (red: UInt8, green: UInt8, blue: UInt8, brightness: 
UInt8)

let pixelCount = 10

let pointer = UnsafeMutableRawPointer.allocate(bytes: 4*pixelCount, alignedTo: 
16)
defer {
  pointer.deallocate(bytes: 4*pixelCount, alignedTo: 16)
}

let tuplesPointer = pointer.bindMemory(to: PixelTuple.self, capacity: 
pixelCount)
let tuples = UnsafeMutableBufferPointer(start: tuplesPointer, count: pixelCount)


for tuple in tuples {
  print(tuple.red, tuple.green, tuple.blue, tuple.brightness)
}




> On Jan 27, 2017, at 3:27 AM, TUNG CK via swift-users  
> wrote:
> 
> Python, we have this
>for pixel in pixels:
>r, g, b, brightness = pixel
>.
> 
> I wonder how to do it in swift? is there a more swifty way to do something 
> like this below?
>for pixel in pixels {
>var r = pixel[0]
>var g = pixel[1]
>var b = pixel[2]
>var brightness = pixel[3]
> .
> }
> ___
> 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] Avoiding an extra copy withUnsafeBytes

2017-01-26 Thread Ray Fix via swift-users
To compute a hash, I want to loop through bytes of a trivial type.  To get the 
bytes, I use withUnsafeBytes hands me a rawBufferPointer collection type.  
Great!

However this call also requires that the "of arg" be declared as a “var" 
instead of “let” because it is inout.  So to do it generically, it forces me to 
make a copy to some var storage.  

Since I am using withUnsafeBytes and not withUnsafeMutableBytes, though, it 
doesn’t seem like this copy should be necessary.  Is there some way to avoid 
it?  Is it something the compiler should be able to reason about and therefore 
elide? Possibly a future evolution (and something for that list)?

On a side note, wouldn’t it be cool if there where a way to enforce that a type 
was trivial?

Then one could write code like:

func consume(value: T) {
  var copy = value
  withUnsafeMutableBytes(of: ) { rawBufferPointer in
// something interesting
  }
}

Always appreciate the great insights I get here.
Thanks as always. Best wishes,
Ray___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] operators and external parameters

2017-01-24 Thread Ray Fix via swift-users

When defining an operator such as == you can implicitly specify external 
parameters:

struct Path: Equatable {
var value: String

static func ==(lhs: Path, rhs: Path) -> Bool {
return lhs.value == rhs.value
}
}

Is this considered okay, or is it bad form and it should really be defined:


struct Path: Equatable {
var value: String

static func ==(_ lhs: Path, _ rhs: Path) -> Bool {
return lhs.value == rhs.value
}
}

Both seem to work fine in practice… 樂  

Thank you!
Ray___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] are large values (not passed through a protocol) ever put on the heap?

2017-01-03 Thread Ray Fix via swift-users

There was a great talk at WWDC 2016 about internals and Swift performance.  
https://developer.apple.com/videos/play/wwdc2016/416/ 


At one point, Arnold Schwaighofer says, "Copying of large values incurs heap 
allocation.”  What isn’t clear to me here is if he is still referring to just 
existential container types or in just large values in general.

My understanding is a value can get put on the heap if:

1) it is passed through a protocol and exceeds small size (3 words of storage)
2) it is captured by an escaping closure, and needs to extend lifetime

Suppose I make a large struct, and pass it as a parameter, is there a point 
where the compiler says, “Okay wise-guy, you are going on the heap now.”  Can 
this be detected with MemoryLayout.size?  I have tried a couple 
experiments where I make beefy (1kB) structs in the playground but I never see 
the size suddenly dropping to a pointer size.

Any insights you have are greatly appreciated! ✨

Best wishes,
Ray

 ___
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 Ray Fix via swift-users

Using Optional, your enum type goes away.  (I think it is a great solution 
unless you need something more than .element and .none in real life.)  Great to 
get all that optional machinery for missing values for free!  Then you can 
constrain elements simply from the Element protocol as in as in:

protocol Element {
func compute() -> Int
}

struct ElementType1: Element {
func compute() -> Int {
return 1
}
}
struct ElementType2: Element {
func compute() -> Int {
return 2
}
}

var childElements: [Element?] = []

childElements.append(ElementType1())
childElements.append(ElementType2())
childElements.append(nil)

childElements.flatMap { $0 }.forEach { print($0.compute()) }

1
2



> On Dec 28, 2016, at 4:10 PM, Brandon Knope via swift-users 
>  wrote:
> 
> Aren’t I losing the ability to enforce what is going into this enum’s 
> associated value then?
> 
> Brandon
> 
>> On Dec 28, 2016, at 7:05 PM, Nevin Brackett-Rozinsky 
>> > 
>> wrote:
>> 
>> 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 
>> > 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

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


Re: [swift-users] Memory Leak Indicated when Derived from NSObject

2016-12-19 Thread Ray Fix via swift-users
Thanks for the update Chris.  Hmm...

So, I get memory runtime issues if I run this on an actual device iPad Air 2 
(iOS 10.2) with Version 8.2 (8C38).  Can’t get it to happen on the simulator. 
Can’t get it to happen if I make a macOS command line tool and inspect it with 
the leaks command.

(I reported this as radar 29715025 but if anyone has any insights please share! 
 )

Thank you,
Ray Fix





import UIKit


class Thing {}

class Test: NSObject
{
static let shared = Test()
var dictionary: [String: Thing] = [:]

func method() {
dictionary = ["value": Thing()]
}
}

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Test.shared.method()
print("Leaky leaky... click on the memory visualizer to see issues.")
}
}


When I click the memory visualizer it shows:

Memory Issues – (3 leaked types) Group
runtime: Memory Issues – (3 leaked types): 1 instance of 
_NativeDictionaryStorageImpl leaked
x-xcode-debug-memory-graph://7fa607cb92c0/4296: runtime: Memory Issues: 
0x1700f9f80
runtime: Memory Issues – (3 leaked types): 1 instance of 
_NativeDictionaryStorageOwner leaked
x-xcode-debug-memory-graph://7fa607cb92c0/5924: runtime: Memory Issues: 
0x170271dc0
runtime: Memory Issues – (3 leaked types): 1 instance of Thing leaked
x-xcode-debug-memory-graph://7fa607cb92c0/1891: runtime: Memory Issues: 
0x170019ca0




> On Dec 17, 2016, at 12:12 AM, Chris Chirogene  wrote:
> 
> Interesting. Thanks. I’ll have to try that.
> The latest Xcode 8.2 release version seems to have fixed this. I am no longer 
> seeing the leak.
> Take care,
> Chris
> 
>> On 17 Dec 2016, at 02:33, Ray Fix  wrote:
>> 
>> FWIW, seeing this too.  Also, when I boiled the project down to a macOS 
>> command line and run the “leaks" cli I don’t see the leak. 樂  
>> 
>> Ray
>> 
>>> On Oct 14, 2016, at 9:42 AM, Chris Chirogene via swift-users 
>>>  wrote:
>>> 
>>> Xcode8 is showing a memory leak in instruments and the memory graph. I have 
>>> narrowed it down to this: deriving from NSObject produces a leak 
>>> indication. I have no idea why.
>>> I need an NSObject to later use the @objc directive.
>>> The Test instance stored in the mDict Dictionary is indicated as a leak in 
>>> Xcode.
>>> This is running as an iOS Single-View-Application project in the iPhone5s 
>>> Simulator running iOS10.0
>>> Here is the sample code:
>>> 
>>>  import Foundation
>>> 
>>>  class Test: NSObject  // <-- derived from NSObject produces leak 
>>> indication below
>>>  {
>>>  static var cTest: Test! = nil
>>>  var mDict: [String : Test] = Dictionary()
>>> 
>>>  static func test() -> Void {
>>>  cTest = Test()
>>>  cTest.mDict["test"] = Test() // <-- alleged leak
>>>  }
>>>  }
>>> 
>>>  class Test  // <-- NOT derived from NSObject, NO leak indication
>>>  {
>>>  static var cTest: Test! = nil
>>>  var mDict: [String : Test] = Dictionary()
>>> 
>>>  static func test() -> Void {
>>>  cTest = Test()
>>>  cTest.mDict["test"] = Test() // <-- NO leak
>>>  }
>>>  }
>>> 
>>>  // from AppDelegate didFinishLaunchingWithOptions
>>>  // ...
>>>  Test.test()
>>>  // ...
>>> 
>>> ___
>>> 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] Memory Leak Indicated when Derived from NSObject

2016-12-16 Thread Ray Fix via swift-users
FWIW, seeing this too.  Also, when I boiled the project down to a macOS command 
line and run the “leaks" cli I don’t see the leak. 樂  

Ray

> On Oct 14, 2016, at 9:42 AM, Chris Chirogene via swift-users 
>  wrote:
> 
> Xcode8 is showing a memory leak in instruments and the memory graph. I have 
> narrowed it down to this: deriving from NSObject produces a leak indication. 
> I have no idea why.
> I need an NSObject to later use the @objc directive.
> The Test instance stored in the mDict Dictionary is indicated as a leak in 
> Xcode.
> This is running as an iOS Single-View-Application project in the iPhone5s 
> Simulator running iOS10.0
> Here is the sample code:
> 
>import Foundation
> 
>class Test: NSObject  // <-- derived from NSObject produces leak 
> indication below
>{
>static var cTest: Test! = nil
>var mDict: [String : Test] = Dictionary()
> 
>static func test() -> Void {
>cTest = Test()
>cTest.mDict["test"] = Test() // <-- alleged leak
>}
>}
> 
>class Test  // <-- NOT derived from NSObject, NO leak indication
>{
>static var cTest: Test! = nil
>var mDict: [String : Test] = Dictionary()
> 
>static func test() -> Void {
>cTest = Test()
>cTest.mDict["test"] = Test() // <-- NO leak
>}
>}
> 
>// from AppDelegate didFinishLaunchingWithOptions
>// ...
>Test.test()
>// ...
> 
> ___
> 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] unsafe memory model questions

2016-12-11 Thread Ray Fix via swift-users
Hello,

So bindMemory is part of the memory model and memory can only bind to one type 
at a time to avoid aliasing. But what does binding actually do? Is it somehow 
communicating with the optimizer?

A tangentially related second question, in the following example:

  let count = 3
  let mutablePointer = UnsafeMutablePointer.allocate(capacity: count)
  defer {
mutablePointer.deallocate(capacity: count)
  }

  mutablePointer.initialize(to: 1234, count: count)
  defer {
mutablePointer.deinitialize(count: count)  // must I do this?
  }

Is it bad form if I don’t deinitialize and go straight to deallocate?  I can 
see where it is important for ref types (to update ref counts, etc).  Is it one 
of those things that the optimizer can remove for the case of value types?

Finally, if I initalize with some other means, such as with a raw buffer 
pointer subscript, is there any need to deinitialize?  Can such memory be 
considered initialized if I bind it with a type?

  // 1
  let pointer = malloc(byteCount)
  defer {
free(pointer)
  }

  let mutableRawBufferPointer = UnsafeMutableRawBufferPointer(start: pointer, 
count: byteCount)
  
  for index in mutableRawBufferPointer.indices {
mutableRawBufferPointer[index] = 42 + UInt8(index)
  }

Perhaps there is a document or proposal somewhere that talks about these 
things. Sorry if I missed it.

Thanks as always,
Ray


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


Re: [swift-users] Getting at the bytes of Data

2016-12-09 Thread Ray Fix via swift-users
Hi Philippe,

Thank you for your response!

> On Dec 9, 2016, at 8:44 AM, Philippe Hausler  wrote:
> 
> So letting the bytes escape from the closure could potentially be in that 
> territory of “bad things may happen”. If you know for certain that the Data 
> will not be mutated and it’s underlying storage will last for the duration of 
> the usage then you should be able to get away with it.
> 

So far it is looking like I am getting away with it. I believe the conditions 
that you state hold.

> The bytes pointer is an inner pointer return from the encapsulating object 
> backing the struct Data. Since that backing object can potentially be 
> deallocated via mutation or the buffer may be reallocated (which very often 
> can cause the base address of the pointer to change) we decided it would be 
> safer to use a closure to ensure the lifespan of the bytes over the access to 
> the bytes.
> 
> Perhaps it might be best to understand more of what you are trying to do to 
> offer a better solution.

I am trying to use the compression_stream C API in the Compression framework 
and wrap it so it is a bit more Swifty.  :]

A full gist of the playground is here: 
https://gist.github.com/rayfix/a286bb55accffef09249ba3535993782 


See line 91.

Appreciate the hints. 

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


Re: [swift-users] How to merge two dictionaries?

2016-11-11 Thread Ray Fix via swift-users
Hi Mr Bee,

The reason I don’t think it is provided is because it is difficult to know what 
to do when keys collide.  You could easily write such a thing and decide your 
own policy.  For example:

let d1 = ["Apples": 20, "Oranges": 13]
let d2 = ["Oranges": 3, "Cherries": 9]

extension Dictionary {
func merged(with another: [Key: Value]) -> [Key: Value] {
var result = self
for entry in another {
result[entry.key] = entry.value
}
return result
}
}

let result = d1.merged(with: d2)


> On Nov 11, 2016, at 12:05 AM, Mr Bee via swift-users  
> wrote:
> 
> Hi,
> 
> I'm using Swift v3 on an El Capitan machine. I want to merge a dictionary 
> into another compatible dictionary. However, I couldn't find addEntries 
> function in the dictionary instance, like it was on NSMutableDictionary 
> (https://developer.apple.com/reference/foundation/nsmutabledictionary). 
> 
> Does that mean that Swift standard library won't provide such similar 
> function for native Swift dictionary? Or is there any other way of doing that 
> natively? I mean using the built-in Swift's native dictionary function 
> (https://developer.apple.com/reference/swift/dictionary), no need to write a 
> custom function, or bridging to NSMutableDictionary.
> 
> Thank you.
> 
> Regards,
> 
> –Mr Bee
> 
> ___
> 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] tuples and metatypes

2016-08-31 Thread Ray Fix via swift-users
Hi. Asking for a friend ;]

Tuples cannot conform to protocols or be extended because they are compound 
types. Is it correct to say that this is true because there is not a unique 
metatype for  compound types?  IOW, there is no unique existential container 
thingy for a tuples?  (Not sure if I am using the proper vocabulary here or 
not.)

Thanks for your thoughts,
Ray Fix
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] remove "Example" from multiline playground markup

2016-08-31 Thread Ray Fix via swift-users
Thank you for the info and the workaround Erica!

I typically use the multiline code for things other than examples such as 
problem statements.  I have filed radar 28088652 in hope that someone on the 
Xcode team agrees that there should be a better solution.

Thank you,
Ray Fix


> On Aug 30, 2016, at 1:58 PM, Erica Sadun <er...@ericasadun.com> wrote:
> 
> To the best of my knowledge, this is a rendering choice made by the 
> playground team
> and you cannot suppress it.
> 
> Workaround: Use `whatever` code voice instead of code fencing.
> 
> Playground markup is currently out of step with commonmark 0.25, which allows 
> you to use a subset of raw HTML including and code 
> 
> -- E
> 
> 
>> On Aug 29, 2016, at 3:07 AM, Ray Fix via swift-users <swift-users@swift.org> 
>> wrote:
>> 
>> With Xcode playground markup, if I write a multiline Swift code example such 
>> as:
>> 
>> 
>> for item in collection {
>>  print(item)
>> }
>> 
>> 
>> The rendered markup it always has the header “Example”  
>> 
>> Is there any way to write multiline code, or modify a stylesheet so that the 
>> heading “Example” is supressed?
>> 
>> Thank you,
>> Ray Fix
>> ___
>> 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] remove "Example" from multiline playground markup

2016-08-29 Thread Ray Fix via swift-users
With Xcode playground markup, if I write a multiline Swift code example such as:


for item in collection {
   print(item)
}


The rendered markup it always has the header “Example”  

Is there any way to write multiline code, or modify a stylesheet so that the 
heading “Example” is supressed?

Thank you,
Ray Fix
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] generic function called recursively not compiling

2016-08-04 Thread Ray Fix via swift-users

I filed rdar://27700622  and attached a playground.  Any 
workaround magic I can do here?

func quickSort(_ input: [Element]) -> [Element] {
if input.count < 2 {
return input
}
let pivot = input.first!
let left = input.dropFirst().filter { $0 <= pivot }
let right = input.dropFirst().filter { $0 > pivot }

// Does not compile with (Swift 3pre) Xcode 8 b1,2,3,4
// Does compile with (Swift 2.2) Xcode 7.3
return quickSort(left) + [pivot] + quickSort(right)
}

quickSort([3,5,1,2])

Error:
//Playground execution failed: error: quicksort.playground:11:22: error: cannot 
convert value of type '[Element]' to expected argument type '[_]'
//return quickSort(left) + [pivot] + quickSort(right)
// ^~~~


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


[swift-users] access violation when weak variable

2016-07-09 Thread Ray Fix via swift-users

Hi!

When I make a variable weak in Xcode 8 (both beta 1 and beta 2) I get a access 
violation.  I think this is a bug, but want to make sure I am not missing 
something.

Best regards,
Ray

//: Playground - noun: a place where people can play

import UIKit

class Person: CustomStringConvertible {
var name: String
weak var parent: Person? /// If I remove weak, no crash in Xcode 8 beta 
2, but leaks
var children: [Person] = [] {
didSet {
children.forEach { $0.parent = self }
}
}

init(name: String) {
self.name = name
print("initialized \(name)")
}
deinit {
print("deinit \(name)")
}
var description: String {
return name
}
}

do {
let frank = Person(name: "Frank")
let lisa = Person(name: "Lisa")
frank.children = [lisa]   /// KABOOM!
}

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


[swift-users] Reducing the boilerplate for my ID types

2016-05-17 Thread Ray Fix via swift-users
Hello,

I have some ID types that are simple ints coming back from a database.  I 
wanted to improve type safety so I don’t accidentally assign product IDs to 
user IDs, etc.  I want to be able to print it and use it as a dictionary key.  
So it is a trivial wrapper of Int.  E.g.

struct CustomerID: Hashable, CustomStringConvertible {
init(_ value: Int) { self.value = value }
let value: Int
var hashValue: Int { return value.hashValue }
var description: String { return String(value) }
}

func ==(lhs: CustomerID, rhs: CustomerID) -> Bool {
return lhs.value == rhs.value
}

While it isn’t too much code, it seems like a lot boilerplate.  I tried to 
reduce the boilerplate with protocol extensions.  After a little bit of 
compiler fighting I came up with:

public protocol IDType: Hashable, CustomStringConvertible {
init(_ value: Int)
var value: Int { get }
}

extension IDType {
public var hashValue: Int { return value.hashValue }
public var description: String { return String(value) }
}

Notes  (1) compiler made me declare my protocol public since Hashable and 
CustomStringConvertible are public. (2) I could not implement init(_ value: 
Int) in the extension so I have to do that each time (3) Self requirement built 
into Hashable meant that I could not implement an == for all IDTypes.  So the 
final product looks like the following.  Given the additional complexity, 
doesn’t seem like it is worth it. 

public struct ProductID: IDType {
public init(_ value: Int) { self.value = value }
public let value: Int
}

public func ==(lhs: ProductID, rhs: ProductID) -> Bool {
return lhs.value == rhs.value
}

I wonder if the hive mind had any better ideas or different approaches for 
creating such types with minimal boilerplate.  [Is there a possible new 
language feature coming that will make this more trivial?]

Ray


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