Re: [swift-users] Rethrows issue

2018-01-01 Thread Howard Lovatt via swift-users
I don’t get why that type checks:

  1. rescue always throws inside sync, therefore
  2. _syncHelper inside sync always throws, therefore
  3. sync always throws, therefore
  4. Shouldn’t sync be declared throws not rethrows?

-- Howard. 

On 1 Jan 2018, at 1:10 pm, Charles Srstka via swift-users 
 wrote:

>> On Dec 31, 2017, at 1:35 AM, Nevin Brackett-Rozinsky via swift-users 
>>  wrote:
>> 
>> 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
> 
> That’s not the only exploit of that sort to exist in the frameworks, 
> actually—and if you look through the source code to the standard library, 
> you’ll see that the Swift standard library actually uses this kind of thing 
> from time to time. For example, take DispatchQueue.sync(), which is declared 
> as ‘rethrows’ despite wrapping a C function that Swift can’t reason anything 
> about. I’d always wondered how that worked, so at some point I looked it up. 
> Here’s how it's implemented:
> 
> The public function we’re all used to, sync():
> 
> public func sync(execute work: () throws -> T) rethrows -> T {
> return try self._syncHelper(fn: sync, execute: work, rescue: { throw $0 })
> }
> 
> This basically passes everything on to a private method, _syncHelper, which 
> looks like this:
> 
> private func _syncHelper(
>  fn: (() -> Void) -> Void,
>  execute work: () throws -> T,
>  rescue: ((Error) throws -> (T))) rethrows -> T
> {
> var result: T?
> var error: Error?
> withoutActuallyEscaping(work) { _work in
> fn {
> do {
> result = try _work()
> } catch let e {
> error = e
> }
> }
> }
> if let e = error {
> return try rescue(e)
> } else {
> return result!
> }
> }
> 
> So basically, since every error thrown inside _syncHelper() is rethrown from 
> one of the closures passed into it, that satisfies ‘rethrows’, and it also 
> satisfies ‘rethrows’ for sync(), since anything thrown by it 

Re: [swift-users] A confusing protocol extension behaviour/bug

2018-01-01 Thread Howard Lovatt via swift-users
Rest of message - hit send by mistake. 

The problem is that it is really easy to make the mistake you made. There have 
been a number of suggestions on Swift Evolution to add key words so that 
diagnostics can be improved. For example:

protocol P {
func m()
}
extension P {
override func m() { ... }
}

Which obviously breaks old code but does let the compiler diagnose problems. 
However none of these suggestions have gained enough support to date. 

You could put in an RFE asking for better diagnostics. 

-- Howard. 

> On 1 Jan 2018, at 11:21 pm, Howard Lovatt via swift-users 
> <swift-users@swift.org> wrote:
> 
> Unfortunately the error messages you get with protocols are limited :). The 
> compiler is doing the right thing, no bug. The problem is that it is really 
> easy to mak
> 
> -- Howard. 
> 
>> On 1 Jan 2018, at 3:40 pm, Toni Suter via swift-users 
>> <swift-users@swift.org> wrote:
>> 
>> Hi Marc,
>> 
>> There are several subtleties here, but I think the compiler is actually 
>> doing the right thing.
>> 
>> The second class defines a static property that looks like it is 
>> 'overriding' the static property from
>> the protocol extension, but since the types don't match (String vs. 
>> String?), it sort of 'overloads'
>> the property (similar to function overloading). Nevertheless, the class 
>> still fulfills the requirements
>> of the Trackable protocol, by inheriting the static property from the 
>> protocol extension.
>> 
>> When you access analyticsID like a regular static property, the Swift 
>> compiler will choose the String property,
>> because it shadows the String? property:
>> 
>> let x = Something2.analyticsID
>> print(x) // Wrong but compilers, returns 
>> wrong value
>> print(type(of: x))   // String
>> 
>> However, when the context of the expression Something2.analyticsID expects a 
>> String?, the Swift compiler will
>> choose the String? property:
>> 
>> let a: String? = Something2.analyticsID  // explicit type 
>> annotation demands a String?
>> print(a) // nil
>> print(type(of: a))   // Optional
>> 
>> let b = Something2.analyticsID as String?// type cast demands a String?
>> print(b) // nil
>> print(type(of: b))   // Optional
>> 
>> A similar thing happens, when you write Something2.analyticsID ?? "nil". The 
>> nil coalescing operator ?? demands that the first parameter
>> is an optional. Therefore, the Swift compiler will choose the String? 
>> property instead of the String property.
>> 
>> I hope this helps!
>> 
>> Best regards,
>> Toni
>> 
>>> Am 01.01.2018 um 18:29 schrieb Marc Palmer via swift-users 
>>> <swift-users@swift.org>:
>>> 
>>> Hi,
>>> 
>>> I hope everybody had a great New Year celebration.
>>> 
>>> I was tracking down a weird bug in my Swift code today. A property defined 
>>> in a class in order to conform to a protocol was not being seen. A protocol 
>>> extension provided a default value of `nil` for this property, so I knew 
>>> where it was coming from. Turned out, in my class I had defined the 
>>> property with the correct name but incorrect type - I declared it as 
>>> `String` instead of `String?`. 
>>> 
>>> I isolated this behaviour in a playground, shown below, and it is pretty 
>>> weird behaviour.
>>> 
>>> The output is:
>>> 
>>> Something1 has id: nil
>>> Something2 has id: nil
>>> Something3 has id: Correct
>>> -- Direct access--
>>> Something1 - nil
>>> Something2 - nil
>>> Something2 with String(describing:) - Wrong but compiles, returns wrong 
>>> value
>>> Something3 - Correct
>>> 
>>> The playground code:
>>> 
>>> ==
>>> 
>>> protocol Trackable {
>>>static var analyticsID: String? { get }
>>> }
>>> 
>>> extension Trackable {
>>>static var analyticsID: String? { return nil }
>>> }
>>> 
>>> class Something1: Trackable {
>>> }
>>> 
>>> class Something2: Trackable {
>>>static var analyticsID: String = "Wrong but compiles, returns wrong 
>>> value"
>>> }
>>> 
>>> class Something3: 

Re: [swift-users] A confusing protocol extension behaviour/bug

2018-01-01 Thread Howard Lovatt via swift-users
Unfortunately the error messages you get with protocols are limited :). The 
compiler is doing the right thing, no bug. The problem is that it is really 
easy to mak

-- Howard. 

> On 1 Jan 2018, at 3:40 pm, Toni Suter via swift-users  
> wrote:
> 
> Hi Marc,
> 
> There are several subtleties here, but I think the compiler is actually doing 
> the right thing.
> 
> The second class defines a static property that looks like it is 'overriding' 
> the static property from
> the protocol extension, but since the types don't match (String vs. String?), 
> it sort of 'overloads'
> the property (similar to function overloading). Nevertheless, the class still 
> fulfills the requirements
> of the Trackable protocol, by inheriting the static property from the 
> protocol extension.
> 
> When you access analyticsID like a regular static property, the Swift 
> compiler will choose the String property,
> because it shadows the String? property:
> 
> let x = Something2.analyticsID
> print(x)  // Wrong but compilers, returns 
> wrong value
> print(type(of: x))// String
> 
> However, when the context of the expression Something2.analyticsID expects a 
> String?, the Swift compiler will
> choose the String? property:
> 
> let a: String? = Something2.analyticsID   // explicit type 
> annotation demands a String?
> print(a)  // nil
> print(type(of: a))// Optional
> 
> let b = Something2.analyticsID as String? // type cast demands a String?
> print(b)  // nil
> print(type(of: b))// Optional
> 
> A similar thing happens, when you write Something2.analyticsID ?? "nil". The 
> nil coalescing operator ?? demands that the first parameter
> is an optional. Therefore, the Swift compiler will choose the String? 
> property instead of the String property.
> 
> I hope this helps!
> 
> Best regards,
> Toni
> 
>> Am 01.01.2018 um 18:29 schrieb Marc Palmer via swift-users 
>> :
>> 
>> Hi,
>> 
>> I hope everybody had a great New Year celebration.
>> 
>> I was tracking down a weird bug in my Swift code today. A property defined 
>> in a class in order to conform to a protocol was not being seen. A protocol 
>> extension provided a default value of `nil` for this property, so I knew 
>> where it was coming from. Turned out, in my class I had defined the property 
>> with the correct name but incorrect type - I declared it as `String` instead 
>> of `String?`. 
>> 
>> I isolated this behaviour in a playground, shown below, and it is pretty 
>> weird behaviour.
>> 
>> The output is:
>> 
>> Something1 has id: nil
>> Something2 has id: nil
>> Something3 has id: Correct
>> -- Direct access--
>> Something1 - nil
>> Something2 - nil
>> Something2 with String(describing:) - Wrong but compiles, returns wrong value
>> Something3 - Correct
>> 
>> The playground code:
>> 
>> ==
>> 
>> protocol Trackable {
>>static var analyticsID: String? { get }
>> }
>> 
>> extension Trackable {
>>static var analyticsID: String? { return nil }
>> }
>> 
>> class Something1: Trackable {
>> }
>> 
>> class Something2: Trackable {
>>static var analyticsID: String = "Wrong but compiles, returns wrong value"
>> }
>> 
>> class Something3: Trackable {
>>static var analyticsID: String? = "Correct"
>> }
>> 
>> func getID(_ trackable: T.Type) {
>>if let id = trackable.analyticsID {
>>print("\(trackable) has id: \(id)")
>>} else {
>>print("\(trackable) has id: nil")
>>}
>> }
>> 
>> getID(Something1.self)
>> getID(Something2.self)
>> getID(Something3.self)
>> 
>> print("-- Direct access--")
>> print("Something1 - \(Something1.self.analyticsID ?? "nil")")
>> print("Something2 A - \(Something2.self.analyticsID ?? "nil")")
>> print("Something2 with String(describing:) - \(String(describing: 
>> Something2.self.analyticsID))")
>> print("Something3 - \(Something3.self.analyticsID ?? "nil")”)
>> ==
>> 
>> Thanks in advance for any information about my misinterpretations or 
>> recommendations of what parts are actually undesirable so that I can raise 
>> the JIRAs.
>> 
>> Cheers
>> 
>> —
>> Marc Palmer
>> Montana Floss Co. Ltd.
>> 
>> Soundproof – Music Player for Practice 
>> http://getsoundproof.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
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Comprehensive documentation for Collection?

2017-12-15 Thread Howard Lovatt via swift-users
It’s a problem with Apple documentation. swiftdoc.org does list the associated 
types, but is no longer maintained :(. 

-- Howard.

> On 16 Dec 2017, at 1:17 pm, Nevin Brackett-Rozinsky via swift-users 
>  wrote:
> 
> 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 mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] FileManager.copyItem not throwing?

2017-11-11 Thread Howard Lovatt via swift-users
I don’t have any inside knowledge on this, i.e. I am not certain I am correct, 
but my understanding was that you were meant to let it throw and catch the 
error rather than test before hand. 

-- Howard.

> On 11 Nov 2017, at 12:51 pm, Marco S Hyman via swift-users 
>  wrote:
> 
> 
>> Running on macOS 10.12.6, Xcode 8.3.2, I get to the copyItem call, which 
>> shows an error on the console:
>> 
>> 2017-11-11 11:18:25.931446+1000 MyApp[32662:2408351] open on /path/to/file: 
>> Permission denied
>> 
>> But it doesn't go to either of my catch blocks, but goes to the following 
>> line, where the completion handler is to be run. What is going on?
> 
> Known (by Apple) bug.  My report was closed as a duplicate of 30350792.
> 
> My workaround is to do this in my do block after attempting to copy a file to 
> saveFileUrl:
> 
>try fileManager.copyItem(at: url, to: saveFileUrl)
>/// DANGER WILL ROBINSON -- the above call can fail to return an
>/// error when the file is not copied.  radar filed and
>/// closed as a DUPLICATE OF 30350792 which is still open.
>/// As a result I must verify that the copied file exists
>if !fileManager.fileExists(atPath: (saveFileUrl.path)) {
>unexpected(error: nil,
>   "Cannot copy \(url.path) to \(saveFileUrl.path)")
>return false
>}
> 
> which duplicates what the catch block would do.
> 
> Marc
> ___
> 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] overloading methods where only difference is optional vs. non-optional type

2017-10-10 Thread Howard Lovatt via swift-users
func funny() -> Int {
 return 1
}

func funny() -> String {
 return "2"
}

let i: Int = funny()

let s: String = funny()

Is fine. Since Swift knows the return type required. However, it can’t infer 
the type of:

let q = funny()

-- Howard. 

> On 11 Oct 2017, at 4:36 am, C. Keith Ray via swift-users 
>  wrote:
> 
> You need to know that the NAME of a method or function isn't just outside the 
> parenthesis.
> 
> The name of 
> 
> func IsTextEmpty(foo : String?) -> Bool? 
> 
> is
> 
> "IsTextEmpty(foo:)"
> 
> and the name of
> 
> 
> func IsTextEmpty(text : String?) -> Bool
> 
> is
> 
> "IsTextEmpty(text:)"
> 
> The argument labels are important.
> 
> 
> func IsTextEmpty(foo : String?) -> Bool? {
> return foo?.isEmpty
> }
> 
> func IsTextEmpty(text : String?) -> Bool {
> guard let text = text else {
> return true
> }
> 
> return text.isEmpty
> }
> 
> print(IsTextEmpty(foo: "1"), IsTextEmpty(text: "2"))
> // prints Optional(false) false
> 
> 
> --
> C. Keith Ray
> Senior Software Engineer / Trainer / Agile Coach
> * http://www.thirdfoundationsw.com/keith_ray_resume_2014_long.pdf
> 
> 
> 
>> On Oct 10, 2017, at 10:27 AM, C. Keith Ray  wrote:
>> 
>> nope. it's the same as this example:
>> 
>> func funny() -> Int {
>>  return 1
>> }
>> 
>> func funny() -> String {
>>  return "2"
>> }
>> 
>> print(funny()) // the compiler doesn't know which one you want.
>> 
>> // the above doesn't compile.
>> // error: forloop.playground:8:1: error: ambiguous use of 'funny()'
>> 
>> 
>> You have to have some difference visible in the caller:
>> 
>> 
>> func funny(useInt: Bool) -> Int {
>>  return 1
>> }
>> 
>> func funny(useString: Bool) -> String {
>>  return "2"
>> }
>> 
>> print(funny(useInt: true), funny(useString: true))
>> // prints "1 2\n"
>> 
>> 
>> --
>> C. Keith Ray
>> Senior Software Engineer / Trainer / Agile Coach
>> * http://www.thirdfoundationsw.com/keith_ray_resume_2014_long.pdf
>> * https://leanpub.com/wepntk <- buy my book?
>> 
>> 
>>> On Oct 10, 2017, at 9:06 AM, Phil Kirby via swift-users 
>>>  wrote:
>>> 
>>> 2 down vote favorite
>>> Original StackOverflow post:
>>> 
>>> https://stackoverflow.com/questions/46620311/overloading-methods-where-only-difference-is-optional-vs-non-optional-type
>>> 
>>> I was under the impression that swift can have overloaded methods that 
>>> differ only in the type of object that the methods return. I would think 
>>> that I could have two funcs with the same signature yet they differ in 
>>> return type.
>>> 
>>> import Foundation
>>> 
>>> // ambiguous use of 'IsTextEmpty(text:)'
>>> func IsTextEmpty(text : String?) -> Bool? {
>>>   return text?.isEmpty
>>> }
>>> 
>>> func IsTextEmpty(text : String?) -> Bool {
>>>guard let text = text else {
>>>  return true
>>>}
>>> 
>>>return text.isEmpty
>>> }
>>> 
>>> let text: String? = nil
>>> 
>>> if let empty = IsTextEmpty(text:"text") {
>>>print("Not Empty")
>>> }
>>> 
>>> if IsTextEmpty(text: text) {
>>>print("Empty")
>>> }
>>> Here, both functions have the same input parameters but one func returns an 
>>> optional Bool? and the other returns a Bool. In this case I get an error:
>>> 
>>> ambiguous use of 'IsTextEmpty(text:)'
>>> If I change the name of one of the input parameters I no longer get the 
>>> ambiguous error:
>>> 
>>> // Works
>>> func IsTextEmpty(foo : String?) -> Bool? {
>>>   return foo?.isEmpty
>>> }
>>> 
>>> func IsTextEmpty(text : String?) -> Bool {
>>>guard let text = text else {
>>>  return true
>>>}
>>> 
>>>return text.isEmpty
>>> }
>>> 
>>> let text: String? = nil
>>> 
>>> if let empty = IsTextEmpty(foo:"text") {
>>>print("Not Empty")
>>> }
>>> 
>>> if IsTextEmpty(text: text) {
>>>print("Empty")
>>> }
>>> Shouldn't the compiler detect that they are two distinct methods even 
>>> though their return types are different, since an optional Bool? is a 
>>> different type from a non-optional Bool?
>>> 
>>> 
>>> ___
>>> 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] Initialization Catch-22?

2017-09-26 Thread Howard Lovatt via swift-users
I know were you are coming from, but:

  1. In other languages it would be the equivalent of an force unwrapped
optional and you could get a NullPointerException (or worse - core dump).
Using a force unwrapped optional just levels the playing field!

  2. You could make it private(set) which would de-risk the var bit.

  3. See below.

class AssignOnce {
weak var value: T? = nil { // Use a weak var to avoid a retain cycle.
willSet {
guard value == nil else {
fatalError("Can only be set once.")
}
}
}
}
class InitSelfDependency {
let dependsUponSelf = AssignOnce()
init() {
dependsUponSelf.value = self
}
}
let i = InitSelfDependency()
i.dependsUponSelf


On Tue, 26 Sep 2017 at 4:44 pm, Kenny Leung via swift-users <
swift-users@swift.org> wrote:

> Hi Howard.
>
> Yes, this would make it compile, but it still would not solve the issues
> that make it wrong in my mind:
>
> 1. I would have to make it a var, but it should not be mutable.
>
> 2. It’s not optional. Without it, the PDAudioPlayer class could not
> function.
>
> Of course, this is just being stubbornly pedantic about the code,  but the
> whole point of this project is an exercise in pedantry.
>
> -Kenny
>
>
> On Sep 25, 2017, at 10:35 PM, Howard Lovatt 
> wrote:
>
> You could try making mQueue a force unwrapped optional or initialize it to
> a failed queue before overwriting on last line of `init`.
>
> On Tue, 26 Sep 2017 at 11:39 am, Kenny Leung via swift-users <
> swift-users@swift.org> wrote:
>
>> Hi Muthu.
>>
>> Thanks for the suggestion.
>>
>> I don’t want to do that because failure to create the AudioQueue should
>> mean failure to create the AudioPlayer itself.
>>
>> -Kenny
>>
>>
>> On Sep 25, 2017, at 6:33 PM, somu subscribe 
>> wrote:
>>
>> Hi Kenny,
>>
>> You could use a lazy var and initialise it with a closure.
>>
>> class PDAudioPlayer {
>>
>> //Would be created lazily when first invoked
>> lazy var mQueue : AudioQueueRef = {
>>
>> //create an audioQueue and return that instance
>> return audioQueue
>> }()
>> }
>>
>> Thanks and regards,
>> Muthu
>>
>>
>> On 26 Sep 2017, at 9:12 AM, Kenny Leung via swift-users <
>> swift-users@swift.org> wrote:
>>
>> Hi All.
>>
>> I’m trying to implement the AudioQueue example from Apple in Swift, and
>> keep it as Swifty as I can. I’ve run into a problem where I have a let ivar
>> for the AudioQueue, but the only way to initialize that let ivar is to pass
>> a block to the function that creates the AudioQueue. I get the error,
>> "Variable 'self.mQueue' used before being initialized”. Is there any way to
>> get around this catch?
>>
>> Thanks!
>>
>> -Kenny
>>
>> The code follows.
>>
>> ———8<8<
>> class PDAudioPlayer {
>> static let kNumberBuffers :Int = 3  // 1
>> //var mDataFormat:AudioStreamBasicDescription //
>> 2
>> let mQueue :AudioQueueRef  // 3
>> //var mBuffers :[AudioQueueBufferRef]// 4
>> //var mAudioFile :AudioFileID?//
>> 5
>> var bufferByteSize :UInt32? // 6
>> var mCurrentPacket :Int64?  // 7
>> var mNumPacketsToRead :UInt32?  // 8
>> var mPacketDescs :UnsafePointer?  // 9
>> var mIsRunning: Bool = false// 10
>>
>> let dispatchQueue :DispatchQueue
>> let source :PDFileAudioSource
>> var audioBuffers :[PDAudioBuffer]
>>
>> init?(source:PDFileAudioSource) {
>> self.source = source
>> self.dispatchQueue = DispatchQueue(label:"AudioPlayer", qos:.
>> default, attributes:[], autoreleaseFrequency:.workItem, target:nil)
>> self.audioBuffers = [PDAudioBuffer]()
>>
>> var tempAudioQueue :AudioQueueRef?
>> var dataFormat = source.mDataFormat
>> let status = AudioQueueNewOutputWithDispatchQueue(,
>> , 0, self.dispatchQueue) { [weak self] (queue, buffer) in
>> // ERROR on this line
>> guard let this = self else {
>> return // block
>> }
>> guard let audioBuffer = 
>> this.audioBufferForAudioQueueBuffer(aqBuffer:buffer)
>> else {
>> return // block
>> }
>> this.source.fillBuffer(audioBuffer)
>> }
>> if status != 0 {
>> return nil
>> }
>> guard let audioQueue = tempAudioQueue else {
>> return nil
>> }
>> self.mQueue = audioQueue
>> }
>>
>> private func audioBufferForAudioQueueBuffer(aqBuffer:
>> AudioQueueBufferRef) -> PDAudioBuffer? {
>> for buffer in self.audioBuffers {
>> if buffer.audioQueueBuffer == aqBuffer {
>> return buffer
>> }

Re: [swift-users] Custom operators from a module

2017-09-06 Thread Howard Lovatt via swift-users
Thanks Jordan. Turns out I had two problems:

  1. I had used ~> which is used in the library (but Xcode didn't tell me
about the redefinition).
  2. Once Xcode had decided that there was an error it wouldn't clear; but
when I quit Xcode and went back in it went away.

Thanks for your suggestion of logging a bug, reducing the problem to bug
form really helped.

  -- Howard.

On 7 September 2017 at 07:36, Howard Lovatt via swift-users <
swift-users@swift.org> wrote:

> I have a custom operator defined in a module and in my XCTest I import
> that module. In the tests the compiler says that the operator isn't
> defined. If I define the operator manually in the tests then it works.
>
> So what is going on?
>
> -- Howard.
>
> On 7 Sep 2017, at 3:45 am, Jordan Rose <jordan_r...@apple.com> wrote:
>
> It's actually the other way around: *all* operator declarations are
> exported from a module, all the time, even if the functions that implement
> them aren't. This is probably a model we should improve, but it's been that
> way since Swift 1.
>
> Jordan
>
>
> On Sep 6, 2017, at 02:08, Howard Lovatt via swift-users <
> swift-users@swift.org> wrote:
>
> Hi All,
>
> I am trying to use a custom operator imported from a module, unfortunately
> you can't add public to the operators definition and therefore it isn't
> exported from the module.
>
> I can manually redefine the operator in the module where the operator is
> used, but that isn't very satisfactory - is there a better way?
>
> Thanks in advance,
>
>   -- Howard.
> ___
> 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] Custom operators from a module

2017-09-06 Thread Howard Lovatt via swift-users
I have a custom operator defined in a module and in my XCTest I import that 
module. In the tests the compiler says that the operator isn't defined. If I 
define the operator manually in the tests then it works. 

So what is going on?

-- Howard. 

> On 7 Sep 2017, at 3:45 am, Jordan Rose <jordan_r...@apple.com> wrote:
> 
> It's actually the other way around: all operator declarations are exported 
> from a module, all the time, even if the functions that implement them 
> aren't. This is probably a model we should improve, but it's been that way 
> since Swift 1.
> 
> Jordan
> 
> 
>> On Sep 6, 2017, at 02:08, Howard Lovatt via swift-users 
>> <swift-users@swift.org> wrote:
>> 
>> Hi All,
>> 
>> I am trying to use a custom operator imported from a module, unfortunately 
>> you can't add public to the operators definition and therefore it isn't 
>> exported from the module.
>> 
>> I can manually redefine the operator in the module where the operator is 
>> used, but that isn't very satisfactory - is there a better way?
>> 
>> Thanks in advance,
>> 
>>   -- Howard.
>> ___
>> 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] Custom operators from a module

2017-09-06 Thread Howard Lovatt via swift-users
Hi All,

I am trying to use a custom operator imported from a module, unfortunately
you can't add public to the operators definition and therefore it isn't
exported from the module.

I can manually redefine the operator in the module where the operator is
used, but that isn't very satisfactory - is there a better way?

Thanks in advance,

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


Re: [swift-users] Is this a compiler bug?

2017-09-04 Thread Howard Lovatt via swift-users
Thanks for prompt reply - link is:

https://bugs.swift.org/browse/SR-5838


  -- Howard.

On 5 September 2017 at 11:58, Slava Pestov <spes...@apple.com> wrote:

> Yeah, looks like a bug. Do you mind filing a JIRA?
>
> Slava
>
> On Sep 4, 2017, at 8:55 PM, Howard Lovatt via swift-users <
> swift-users@swift.org> wrote:
>
> Hi All,
>
> Is this a compiler bug?
>
> struct Box {
> var value: T
> init(_ value: T) { self.value = value }
> /// Unboxing operator.
> static func >> (left: Box, right: inout T?) {
> right = left.value
> }
> }
>
> var u: String?
> let b = Box("Test")
> b >>  // ERROR: Cannot convert value of type 'Box' to expected
> argument type 'Box<_>'
>
> Am I missing something?
>
> Thanks in advance for any help,
>   -- Howard.
> ___
> 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] Is this a compiler bug?

2017-09-04 Thread Howard Lovatt via swift-users
Hi All,

Is this a compiler bug?

struct Box {
var value: T
init(_ value: T) { self.value = value }
/// Unboxing operator.
static func >> (left: Box, right: inout T?) {
right = left.value
}
}

var u: String?
let b = Box("Test")
b >>  // ERROR: Cannot convert value of type 'Box' to expected
argument type 'Box<_>'

Am I missing something?

Thanks in advance for any help,
  -- Howard.
___
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-19 Thread Howard Lovatt via swift-users
You are hardly alone struggling with this, it seems to come up every other
week!

You can write your own custom AnyProtocol type that includes Self, a pain
but doable, e.g.:

protocol A {
func a() -> String
}
protocol B {
func b() -> String
}
struct AB1: A, B, Hashable {
func a() -> String {
return "AB1.a"
}
func b() -> String {
return "AB1.b"
}
var hashValue: Int {
return 1
}
static func ==(lhs: AB1, rhs: AB1) -> Bool {
return true
}
}
struct AB2: A, B, Hashable {
func a() -> String {
return "AB2.a"
}
func b() -> String {
return "AB2.b"
}
var hashValue: Int {
return 2
}
static func ==(lhs: AB2, rhs: AB2) -> Bool {
return true
}
}
struct AnyABHashable: A, B, Hashable {
let equalsClosure: (_ rhs: AnyABHashable) -> Bool
let hashValueClosure: () -> Int
let bClosure: () -> String
let aClosure: () -> String
static func ==(lhs: AnyABHashable, rhs: AnyABHashable) -> Bool {
return lhs.equalsClosure(rhs)
}
var hashValue: Int {
return hashValueClosure()
}
func b() -> String {
return bClosure()
}
func a() -> String {
return aClosure()
}
}
// AB1 init
extension AnyABHashable {
init(_ ab1: AB1) {
equalsClosure = { (r) in
if let rhs = r as? AB1 {
return ab1 == rhs
}
return false
}
hashValueClosure = { return ab1.hashValue }
aClosure = { return ab1.a() }
bClosure = { return ab1.b() }
}
}
// AB2 init
extension AnyABHashable {
init(_ ab2: AB2) {
equalsClosure = { (r) in
if let rhs = r as? AB2 {
return ab2 == rhs
}
return false
}
hashValueClosure = { return ab2.hashValue }
aClosure = { return ab2.a() }
bClosure = { return ab2.b() }
}
}
let ab1Set = Set([AnyABHashable(AB1())])
let ab2Set = Set([AnyABHashable(AB2())])
let abSet = ab1Set.union(ab2Set)
for ab in abSet {
ab.a()
ab.b()
}


On Tue, 11 Jul 2017 at 8:10 pm, Glen Huang via swift-users <
swift-users@swift.org> 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
>
-- 
-- Howard.
___
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-11 Thread Howard Lovatt via swift-users
I would be tempted to use classes for this if you can use single
inheritance. If you need multiple inheritance then use an enum and hand
code the dispatch, a lot more work :(. E.G.:

protocol A {
func a() -> String
}
protocol B {
func b() -> String
}
struct AB1: A, B, Hashable {
func a() -> String {
return "AB1.a"
}
func b() -> String {
return "AB1.b"
}
var hashValue: Int {
return 1
}
static func ==(lhs: AB1, rhs: AB1) -> Bool {
return true
}
}
struct AB2: A, B, Hashable {
func a() -> String {
return "AB2.a"
}
func b() -> String {
return "AB2.b"
}
var hashValue: Int {
return 2
}
static func ==(lhs: AB2, rhs: AB2) -> Bool {
return true
}
}
enum AB1Or2: A, B, Hashable {
case ab1(AB1)
case ab2(AB2)
func a() -> String {
switch self {
case .ab1(let ab1Arg):
return ab1Arg.a()
case .ab2(let ab2Arg):
return ab2Arg.a()
}
}
func b() -> String {
switch self {
case .ab1(let ab1Arg):
return ab1Arg.b()
case .ab2(let ab2Arg):
return ab2Arg.b()
}
}
var hashValue: Int {
switch self {
case .ab1(let ab1Arg):
return ab1Arg.hashValue
case .ab2(let ab2Arg):
return ab2Arg.hashValue
}
}
static func ==(lhs: AB1Or2, rhs: AB1Or2) -> Bool {
switch lhs {
case .ab1(let lhsAB1):
switch rhs {
case .ab1(let rhsAB1):
return lhsAB1 == rhsAB1
default:
return false
}
case .ab2(let lhsAB2):
switch rhs {
case .ab2(let rhsAB2):
return lhsAB2 == rhsAB2
default:
return false
}
}
}
}
let ab1s = Set([AB1Or2.ab1(AB1())])
let ab2s = Set([AB1Or2.ab2(AB2())])
let abs = ab1s.union(ab2s)


On Tue, 11 Jul 2017 at 10:46 pm, Glen Huang  wrote:

> Thanks for bringing AnyHashable to my attention.
>
> It works, but the types are now erased. I want to have a union of the two
> sets because I want to loop over it to treat each contained item as Named,
> so I can process them as though they are of the same type. Is this type of
> use case really should be addressed using super class?
>
> On 11 Jul 2017, at 7:38 PM, Howard Lovatt  wrote:
>
> You can have a set of AnyHashable:
>
> var item = Set()
> item.insert(AnyHashable(Foo()))
> item.insert(AnyHashable(Bar()))
>
>
> Depends what you will do with the set if this is viable or not. You can
> also use classes and ObjectID.
>
> You might want this though:
>
> var item = [AnyHashable: Any]
>
> extension Dictionary where Key == AnyHashable, Value: Hashable {
> func insert(_ value: Value) {
> self[AnyHashable(value)] == value
> }
> }
>
> item.insert(Foo())
> item.insert(Bar())
>
>
> So you get at the stored value.
>
> -- Howard.
>
> On 11 Jul 2017, at 8:09 pm, Glen Huang via swift-users <
> swift-users@swift.org> 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
>
>
> --
-- Howard.
___
swift-users mailing list

Re: [swift-users] Is it possible to specify error type thrown in a protocol method

2017-07-06 Thread Howard Lovatt via swift-users
On balance I think I prefer result types. Java's fully typed throws and Swift's 
semi-typed throws are fine though. I can't see Swift supporting result types 
because they already have throws. 

-- Howard. 

> On 6 Jul 2017, at 4:27 pm, Tim Wang  wrote:
> 
> Thanks Howard, it's a good workaround. 
> 
> Do you think it would be better to be part of swift language feature? I wish 
> swift team could consider this :)
> 
>> On Thu, Jul 6, 2017 at 11:04 AM Howard Lovatt  
>> wrote:
>> You could use a result type, e.g.:
>> 
>> https://github.com/antitypical/Result
>> 
>> Or roll your own result type.
>> 
>> I think the reason that Swift doesn't support what you want is because of 
>> rethrows. When you declare a method as rethrows it can throw anything 
>> because the closure it is re-throwing can throw anything. They could have 
>> fully typed the rethrows but obviously decided that was not worth it. At 
>> present rethrows is light weight; the compiler generates two versions of the 
>> method, one that throws and one that doesn't. If it was typed then it would 
>> be like a generic method and a version of the method would be required for 
>> each type combination that was actually used.
>> 
>>   -- Howard.
>> 
>>> On 6 July 2017 at 10:38, Tim Wang via swift-users  
>>> wrote:
>> 
>>> Hi Swifters,
>>> 
>>> I am wondering if it is possible to specify error types thrown in a 
>>> protocol method. By allowing us to do it and letting the compiler check all 
>>> the implementations of the protocol to make sure only they would only throw 
>>> the specified error types, we only need to catch our error types when 
>>> calling these methods. 
>>> 
>>> For the code below:
>>> 
>>> enum MyError: Error {
>>> 
>>> case justError
>>> 
>>> }
>>> 
>>> protocol MethodWillThrow {
>>> 
>>> func testMethod() throws MyError
>>> 
>>> }
>>> 
>>> 
>>> 
>>> extension MethodThrow {
>>> 
>>> func testMethod() throws {
>>> 
>>> throw MyError.justError
>>> 
>>> }
>>> 
>>> }
>>> 
>>> class TestClass: MethodThrow {
>>> 
>>> func testMethod() throws {
>>> 
>>> throw MyError.justError
>>> 
>>> }
>>> 
>>> func anotherMethod() {
>>> 
>>> do {
>>> 
>>> try testMethod()
>>> 
>>> } catch MyError.justError {
>>> 
>>> print("my error")
>>> 
>>> } catch {
>>> 
>>> print("other error")
>>> 
>>> }
>>> 
>>> }
>>> 
>>> }
>>> 
>>> Now we need add this extra default catch to make it compile and work and I 
>>> really want to remove this catch.
>>> 
>>> Please let me know if there is a way to do it and thanks for help in 
>>> advance.
>>> 
>>> Tim Wang
>>> 
>>> 
>> 
>>> ___
>>> 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 specify error type thrown in a protocol method

2017-07-05 Thread Howard Lovatt via swift-users
You could use a result type, e.g.:

https://github.com/antitypical/Result

Or roll your own result type.

I think the reason that Swift doesn't support what you want is because of
rethrows. When you declare a method as rethrows it can throw anything
because the closure it is re-throwing can throw anything. They could have
fully typed the rethrows but obviously decided that was not worth it. At
present rethrows is light weight; the compiler generates two versions of
the method, one that throws and one that doesn't. If it was typed then it
would be like a generic method and a version of the method would be
required for each type combination that was actually used.

  -- Howard.

On 6 July 2017 at 10:38, Tim Wang via swift-users 
wrote:

> Hi Swifters,
>
> I am wondering if it is possible to specify error types thrown in a
> protocol method. By allowing us to do it and letting the compiler check all
> the implementations of the protocol to make sure only they would only throw
> the specified error types, we only need to catch our error types when
> calling these methods.
>
> For the code below:
>
> enum MyError: Error {
>
> case justError
>
> }
>
> protocol MethodWillThrow {
>
> func testMethod() throws MyError
>
> }
>
>
> extension MethodThrow {
>
> func testMethod() throws {
>
> throw MyError.justError
>
> }
>
> }
>
> class TestClass: MethodThrow {
>
> func testMethod() throws {
>
> throw MyError.justError
>
> }
>
> func anotherMethod() {
>
> do {
>
> try testMethod()
>
> } catch MyError.justError {
>
> print("my error")
>
> } *catch {*
>
> *print("other error")*
>
> *}*
>
> }
>
> }
>
> Now we need add this extra default catch to make it compile and work and I
> really want to remove this catch.
>
> Please let me know if there is a way to do it and thanks for help in
> advance.
>
> Tim Wang
>
> ___
> 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] Robust Codable coding

2017-06-23 Thread Howard Lovatt via swift-users
Hi All,

I have started to use Codable and was looking for some advice. I want to make 
the persisted data structure robust so that if I change the properties as the 
code develops the new code can deserialise an old saved file. This is what I am 
currently doing:


struct Project: Codable {
var ecsVersion = 0
var comment = ""

init() {}

init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
ecsVersion = try values.decodeIfPresent(Int.self, forKey: .ecsVersion) 
?? ecsVersion
comment = try values.decodeIfPresent(String.self, forKey: .comment) ?? 
comment
}
}

The idea is that if I add fields the deserialisation doesn’t fail provided that 
I provide a default value. However this presumably fails when you delete a 
field because CodingKeys is now incorrect. (I say presumably because the 
documentation doesn’t say what will happen.) Though not ideal, I can leave 
disused properties in Projects to prevent the deserialisation error.

Any advice? Is there a better way?

Thanks in advance,

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


Re: [swift-users] any wisdom about sharing "common" overloads/extensions in base libraries?

2017-06-21 Thread Howard Lovatt via swift-users
Jordon Rose from Apple said:

"It's tracked by SR-3908 
. (The description's a little different but it's the same underlying
issue.)"


  -- Howard.

On 21 June 2017 at 12:07, David Baraff  wrote:

>
> On Jun 20, 2017, at 6:59 PM, Howard Lovatt 
> wrote:
>
> There is a *bug* that the Swift people know about, but you are **meant**
> to be able to do this:
>
>
> Is there a plan to fix this?
> If it worked properly this would be quite wonderful.
>
>
>
> ModuleA
>
> A.swift
>
> public protocol P {
>
> func m() -> String
>
> }
>
> extension Int: P {
>
> public func m() -> String { return "AP.m" }
>
> }
>
> ModuleB
>
> B.swift
>
> public protocol P {
>
> func m() -> String
>
> }
> extension Int: P {
>
> public func m() -> String { return "BP.m" }
>
> }
>
> ModuleC
>
> A.swift
>
> import ModuleA
>
> func am(_ i: Int) -> String { return i.m() }
>
> B.swift
>
> import ModuleB
>
> func bm(_ i: Int) -> String { return i.m() }
>
> main.swift
>
> let i = 0
>
> print(am(i))
> print(bm(i))
>
>
>   -- Howard.
>
> On 21 June 2017 at 00:02, David Baraff via swift-users <
> swift-users@swift.org> wrote:
>
>> I posted this on Apple’s developer forums, and someone suggested trying
>> this here.
>> Basically, see https://forums.developer.apple.com/thread/80349
>>
>> but in a nutshell: consider that a widely used class/struct (such as
>> CGPoint) is missing some “obvious” functionality [don’t debate that part,
>> just go with it for now], such as the ability to scale a point by a scalar
>> using * as an operator: so in my awesome library “GeometryBase” I write
>>
>>   public func * (left: CGPoint, right: double) -> CGPoint {
>>   return CGPoint(x: right*left.x, y: right*left.y)
>>   }
>>
>> Why public?  Well, of course, because I want to use library GeometryBase
>> in many apps or other libraries, and now this overload exists in only one
>> place.
>>
>> But other bright people have the same idea, and now I want to use their
>> libraries.  (some of them in my company, some of them not.)
>>
>> And now we’re stuck, because everyone is trying to make up for the same
>> (perceived) lack and everyone wants them public so that they don’t have to
>> keep sticking them in each library they write.
>>
>> This is not a made up situation: many people even within one company
>> trying to share code somewhat informally are going to write the same code
>> to make using CGPoint/Size/Rect easier, and now we can’t share anything
>> safely.
>>
>> Anybody got some good ideas what to do about this?
>>
>> [Same question could apply to adding extensions.]
>>
>>
>> ___
>> 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] any wisdom about sharing "common" overloads/extensions in base libraries?

2017-06-20 Thread Howard Lovatt via swift-users
There is a *bug* that the Swift people know about, but you are **meant** to
be able to do this:

ModuleA

A.swift

public protocol P {

func m() -> String

}

extension Int: P {

public func m() -> String { return "AP.m" }

}

ModuleB

B.swift

public protocol P {

func m() -> String

}
extension Int: P {

public func m() -> String { return "BP.m" }

}

ModuleC

A.swift

import ModuleA

func am(_ i: Int) -> String { return i.m() }

B.swift

import ModuleB

func bm(_ i: Int) -> String { return i.m() }

main.swift

let i = 0

print(am(i))
print(bm(i))


  -- Howard.

On 21 June 2017 at 00:02, David Baraff via swift-users <
swift-users@swift.org> wrote:

> I posted this on Apple’s developer forums, and someone suggested trying
> this here.
> Basically, see https://forums.developer.apple.com/thread/80349
>
> but in a nutshell: consider that a widely used class/struct (such as
> CGPoint) is missing some “obvious” functionality [don’t debate that part,
> just go with it for now], such as the ability to scale a point by a scalar
> using * as an operator: so in my awesome library “GeometryBase” I write
>
>   public func * (left: CGPoint, right: double) -> CGPoint {
>   return CGPoint(x: right*left.x, y: right*left.y)
>   }
>
> Why public?  Well, of course, because I want to use library GeometryBase
> in many apps or other libraries, and now this overload exists in only one
> place.
>
> But other bright people have the same idea, and now I want to use their
> libraries.  (some of them in my company, some of them not.)
>
> And now we’re stuck, because everyone is trying to make up for the same
> (perceived) lack and everyone wants them public so that they don’t have to
> keep sticking them in each library they write.
>
> This is not a made up situation: many people even within one company
> trying to share code somewhat informally are going to write the same code
> to make using CGPoint/Size/Rect easier, and now we can’t share anything
> safely.
>
> Anybody got some good ideas what to do about this?
>
> [Same question could apply to adding extensions.]
>
>
> ___
> 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] Restricting associated values

2017-06-18 Thread Howard Lovatt via swift-users
To me Angle is a unit with two common representations: radians and degrees.
It's not an enum because it doesn't have two values, it has one value that
you can view in two ways.

Therefore I would make an Angle struct, something like:

//: Angle struct instead of angle enum


import Foundation


struct Angle  {

static let d2R = Double.pi / 180



static let r2D = 180 / Double.pi



private var degs: Double



var degrees: Double {

return degs

}



var radians: Double {

return degs * Angle.d2R

}



init(degrees: Double = 0) {

degs = degrees.truncatingRemainder(dividingBy: 180)

}



init(radians: Double) {

self.init(degrees: radians * Angle.r2D)

}

}


extension Angle: Hashable {

var hashValue: Int {

return degs.hashValue

}



static func ==(lhs: Angle, rhs: Angle) -> Bool {

return lhs.degs == rhs.degs

}

}


extension Angle/*: FloatingPoint*/ {

static func +(lhs: Angle, rhs: Angle) -> Angle {

return Angle(degrees: lhs.degs + rhs.degs)

}



static func +=(lhs: inout Angle, rhs: Angle) {

lhs.degs += rhs.degs

lhs.degs = lhs.degs.truncatingRemainder(dividingBy: 180)

}



// Rest of FloatingPoint ...

}


// Trig

extension Angle {

var sin: Double {

return Foundation.sin(radians) // Need to qualify name to stop name
clash

}



// Other trig

}


let a = Angle(degrees: 90) // 90

a.radians // pi / 2

a.sin // 1

let b = Angle(radians: 3) // Almost pi

b.degrees // 171.9

let c = a + b // Wraps over 180 degrees

c.degrees // 81.9

c == b // false

c.hashValue // 463...

let d = Angle(degrees: -90) // -90

d.radians // -pi / 2

var e = Angle(radians: -3) // Almost -pi

e.degrees // -171.9

e += d // Wraps over -180 degrees

e.degrees // -81.9

  -- Howard.

On 19 June 2017 at 13:32, David Sweeris via swift-users <
swift-users@swift.org> wrote:

>
> On Jun 18, 2017, at 19:30, Nevin Brackett-Rozinsky via swift-users <
> swift-users@swift.org> wrote:
>
> Is there a way to restrict the associated values of an enum? For example,
> suppose I have this type:
>
> enum Angle {
> case radians(Double)
> case degrees(Double)
> }
>
> I want to ensure that the radians values is always in [0, 2π) and the
> degrees values is always in [0, 360). Ideally I would like to write an
> initializer which is called when the user writes eg. “let x: Angle =
> .degrees(-45)” and contains the logic to wrap the provided value into the
> allowed range (in this case by adding a multiple of 360).
>
> I don’t see a way to do it. Is this possible?
>
> The closest I’ve found is to create auxiliary types such as
>
> struct Degree { … }
> struct Radian { … }
>
> and give them appropriate initializers, then use them for the associated
> values. However that is undesirable because it adds an extra level of depth
> to get at the actual numeric values.
>
> Is there a better way?
>
>
> Not off the top of my head, at least not without changing the syntax.
>
> You could add two inits, with different argument labels, and not directly
> set the case: “let x = Angle(degrees: -45)”
>
> You could add "public var radians: Double { get {...} set {...} }" (and
> again for "degrees") to `Angle`. The getter would need to switch on self
> to figure out if you need to convert between the two (like if someone said
> ".radians(2).degrees"): “var x = Angle.radians(0); x.degrees = -45"
>
> Alternately, you could add "subscript() -> Double" and switch on self in
> both the setter and the getter to figure out if you should be wrapping
> at 2π or 360 and to do any conversions: “var x: Angle = .radians(0); x[] =
> -45"
>
> Hope that helps
> - Dave Sweeris
>
> ___
> 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] override-like keyword for default implementations

2017-05-16 Thread Howard Lovatt via swift-users
In the proposal I just posted in reply to Jordan Rose all these examples
would work as expected, though the syntax and/or semantics would be
slightly different:

Example 1

In R.swift

protocol R { func f() } // f is abstract

In P.swift

protocol P {} // f cannot be in protocol and extension

extension P { func f() {... } } // f is implemented and declared to be in P

In S.swift

struct S: R, P {} // f is from P whether an instance of S is types as S, P,
or R
  // If there was a spelling mistake for f in
either P or R it would be detected since not all methods would be
implemented


Example 2

In P.swift

protocol P {} // f cannot be in protocol and extension
extension P where Self: AnyObject { func f() {... } } // f is implemented
and declared to be in P if Self is an Object, otherwise abstract in P

In C:.swift

class C: P {} // Picks up f's implementation since Self is an object


Would this be an acceptable solution - it is minorly source breaking, but I
feel all solutions will be.

  -- Howard.

On 17 May 2017 at 08:05, Slava Pestov via swift-users  wrote:

> It’s not clear if such a keyword can be designed in a way that covers all
> cases. For example, consider a protocol extension that provides a default
> implementation for a requirement in a different protocol:
>
> protocol R {
>   func f()
> }
>
> protocol P {}
>
> extension P {
>   func f()
> }
>
> struct S : R, P {}
>
> Or a constrained extension that provides a default that only applies in
> certain cases:
>
> protocol P {
>   func f()
> }
>
> extension P where Self : AnyObject {
>   func f()
> }
>
> class C : P {}
>
> Slava
>
> > On May 16, 2017, at 8: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 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 Howard Lovatt via swift-users
Here is a proposal I put forwards last month that addresses the issue (and
others), the original versions did not allow retroactive modeling but
following feedback it was incorporated.

PS Bitten by this problem two days ago, copied some example Swift 2 code
into a Swift 3 project and an obj-c method had changed its name. Took ages
to find the culprit! The error was a null pointer exception it a completely
different bit of code! Very frustrating!


=

# Proposal: Split extension into implementing methods and adding methods
and protocols retrospectively

## Revision history

| Version | Date   | Comment   |
|-|--|--|
| Draft 1   | 11 April 2017 | Initial version |
| Draft 2  | 13 April 2017 | Added support for post-hoc conformance to a
protocol - replaced static final extensions with final extensions |
| Draft 3 | 17 April 2017 | Added justification section |
| Draft 4 | 2 May 2017   | Allow final extensions to be public and allow
ad-hoc code reuse |

## Introduction

Currently extension methods are confusing because they have different
dispatch rules for the same calling syntax. EG:

public protocol P {
func mP() -> String
 }
extension P {
func mP() -> String { return "P.mP" }
func mE() -> String { return "P.mE" }
}
struct S: P {
func mP() -> String { return "S.mP" }
func mE() -> String { return "S.mE" }
}
let s = S()
s.mP() // S.mP as expected
s.mE() // S.mE as expected
let p: P = s // Note: s now typed as P
p.mP() // S.mP as expected
p.mE() // P.mE unexpected!

The situation with classes is even more confusing:

class C: P { /*gets the protocol extensions*/ }
let pC: P = C()
pC.mP() // P.mP as expected!
pC.mE() // P.mE as expected!
class D: C {
/*override not allowed!*/ func mP() -> String { return "D.mP" }
/*override not allowed!*/ func mE() -> String { return "D.mE" }
}
let pD: P = D()
pD.mP() // P.mP unexpected!
pD.mE() // P.mE unexpected!

This proposal cures the above two problem by separating extension methods i
nto two seperate use cases: implementations for methods and adding methods
and protocols retrospectively. The proposal still retains retroactively
adding protocol conformance and ad-hoc code reuse, however these are made
easy to understand and safe.

## Implementing methods in same file as type declaration

If the extension is in the **same** file as the type declaration then its
implemented methods are dispatched using a Vtable for protocols and classes
and statically for structs and enums. EG:

File P.swift

protocol P {
// func m() not declared in type since it is added by the extension,
under this proposal it is an error to include a declaration in a type
**and** in an extension
}
extension P {
func m() { print("P.m") } // m is added to the protocol declaration
}

Same or another file

struct S: P {
override func m() { print("S.m") } // Note override required
because m already has an implementation from the extension
}
let p: P = S() // Note typed as P
p.m() // Now prints S.m as expected

Extensions in the same file as the declaration can have any access, can be
final, and can have where clauses and provide inheritable implementations.
Ad-hoc code reuse is supported, in particular if a class/enum/strict
already had a method, m say, and a protocol, P say, required an m then an
extension that added P would not need to provide m (i.e. as at present).

In a protocol at present you can declare a method that is then implemented
in an extension without the use of the override keyword. This situation
only applies to protocols, for structs/enumerated/classes you cannot
declare in type and implement in an extension at all. This proposal unifies
the behaviour of protocol/struct/enum/class with extensions and also
prevents the error of a minor typo between the protocol and extension adding
two methods instead of generating an error, by requiring either:

  1. The method is only declared in the protocol and not in any extensions and
is therefore abstract
  2. The method is only in one extension and not in the protocol

A method can be abstract in one protocol and implemented in a second
protocol that extends the first.

The implementation needed to achieve this proposal for a protocol is that a
value instance typed as a protocol is copied onto the heap, a pointer to
its Vtable added, and its address passed/copied (i.e. it becomes a class
instance). No change is needed for a class instance typed as a protocol,
which unlike at present can now be passed/copied as a protocol directly.
Think of a protocol as like an abstract class; cannot be instantiated like
an abstract class and which possibly has abstract methods, but in different
in that it cannot have fields but can be multiply 

Re: [swift-users] Help! Slicing an array is very expensive

2017-05-09 Thread Howard Lovatt via swift-users
Try:

struct SegmentedArray {
private static let segmentCapacityPowerOf2 = 13
private static let segmentCapacity = 1 <<
SegmentedArray.segmentCapacityPowerOf2
private var offset: Int
private var firstSegments: [[UInt8]]
private var lastSegment: [UInt8]
var count: Int {
return (firstSegments.count <<
SegmentedArray.segmentCapacityPowerOf2) + lastSegment.count - offset
}
var capacity: Int {
return (firstSegments.count + 1) <<
SegmentedArray.segmentCapacityPowerOf2
}
private init(offset: Int, firstSegments: [[UInt8]], lastSegment:
[UInt8]) {
(self.offset, self.firstSegments, self.lastSegment) = (offset,
firstSegments, lastSegment)
}
private init(offset: Int) {
self.init(offset: offset, firstSegments: [[UInt8]](), lastSegment:
[UInt8]())
lastSegment.reserveCapacity(SegmentedArray.segmentCapacity)
}
init() { self.init(offset: 0) }
init(sA: SegmentedArray) {
(offset, firstSegments, lastSegment) = (sA.offset,
sA.firstSegments, sA.lastSegment)
}
mutating func append(_ x: UInt8) {
if lastSegment.count == SegmentedArray.segmentCapacity {
firstSegments.append(lastSegment)
lastSegment = [UInt8]()
lastSegment.reserveCapacity(SegmentedArray.segmentCapacity)
}
lastSegment.append(x)
}
subscript(r: Range) -> SegmentedArray {
let l = r.lowerBound + offset
let lI = l >> SegmentedArray.segmentCapacityPowerOf2
let o = l - (lI << SegmentedArray.segmentCapacityPowerOf2)
let u = r.upperBound + offset
let uI = u >> SegmentedArray.segmentCapacityPowerOf2
let fS = Array(firstSegments[lI ..< uI])
let r = 0 ..< (u - (uI << SegmentedArray.segmentCapacityPowerOf2))
let lS = Array(uI >= firstSegments.count ? lastSegment[r] :
firstSegments[uI][r])
return SegmentedArray(offset: o, firstSegments: fS, lastSegment: lS)
}
}


It has fast slicing and the slice returned is a `SegmentedArray` and hence
doesn't require wrapping. The append method is a little slower though.

  -- Howard.

On 10 May 2017 at 04:32, Michael Gottesman <mgottes...@apple.com> wrote:

> Could you file a bug report? bugs.swift.org?
>
> Michael
>
> On May 9, 2017, at 12:59 AM, Howard Lovatt via swift-users <
> swift-users@swift.org> wrote:
>
> My mistake. If I create a new array I get the problem. EG:
>
> import Foundation
>
> func elapsed(s: DispatchTime, e: DispatchTime) -> Double {
> return Double(e.uptimeNanoseconds - s.uptimeNanoseconds) /
> 1_000_000_000
> }
>
> let s = 250_000_000
> var a = [UInt8]()
> a.reserveCapacity(s)
>
> let sa = DispatchTime.now()
> for i in 1 ... s {
> a.append(0)
> }
> let ea = DispatchTime.now()
> print("Append time: \(elapsed(s: sa, e: ea)) s")
>
> let st = DispatchTime.now()
> a = Array(a[0 ..< (s >> 1)])
> let et = DispatchTime.now()
> print("Trim time: \(elapsed(s: st, e: et)) s")
> print("a count: \(a.count), capacity: \(a.capacity)")
>
>
> Prints:
>
> Append time: 2.65726525 s
> Trim time: 36.954417356 s
> a count: 12500, capacity: 125001696
>
>
>   -- Howard.
>
> On 9 May 2017 at 17:53, Howard Lovatt <howard.lov...@gmail.com> wrote:
>
>> I find trimming relative to appending OK on my 6 year old MacBook Pro. EG:
>>
>> import Foundation
>>
>> func elapsed(s: DispatchTime, e: DispatchTime) -> Double {
>> return Double(e.uptimeNanoseconds - s.uptimeNanoseconds) /
>> 1_000_000_000
>> }
>>
>> let s = 250_000_000
>> var a = [UInt8]()
>> a.reserveCapacity(s)
>>
>> let sa = DispatchTime.now()
>> for i in 1 ... s {
>> a.append(0)
>> }
>> let ea = DispatchTime.now()
>> print("Append time: \(elapsed(s: sa, e: ea)) s")
>>
>> let st = DispatchTime.now()
>> let ha = a[0 ..< (s >> 1)]
>> let et = DispatchTime.now()
>> print("Trim time: \(elapsed(s: st, e: et)) s")
>>
>> print("ha count: \(ha.count), capacity: \(ha.capacity)")
>>
>>
>> Prints:
>>
>> Append time: 2.612397389 s
>> Trim time: 0.000444132 s
>> ha count: 12500, capacity: 12500
>>
>>
>>   -- Howard.
>>
>> On 9 May 2017 at 12:56, Kelvin Ma via swift-users <swift-users@swift.org>
>> wrote:
>>
>>> Depending on what you’re trying to do with the data, you might be better
>>> off using an UnsafeBufferPointer and allocating and reallocating that,
>>> C-style.
>>>
>>> On Mon, May 8, 2017 at 7:01 PM, Philippe Hausler via swift-users <

Re: [swift-users] Help! Slicing an array is very expensive

2017-05-09 Thread Howard Lovatt via swift-users
My mistake. If I create a new array I get the problem. EG:

import Foundation

func elapsed(s: DispatchTime, e: DispatchTime) -> Double {
return Double(e.uptimeNanoseconds - s.uptimeNanoseconds) / 1_000_000_000
}

let s = 250_000_000
var a = [UInt8]()
a.reserveCapacity(s)

let sa = DispatchTime.now()
for i in 1 ... s {
a.append(0)
}
let ea = DispatchTime.now()
print("Append time: \(elapsed(s: sa, e: ea)) s")

let st = DispatchTime.now()
a = Array(a[0 ..< (s >> 1)])
let et = DispatchTime.now()
print("Trim time: \(elapsed(s: st, e: et)) s")
print("a count: \(a.count), capacity: \(a.capacity)")


Prints:

Append time: 2.65726525 s
Trim time: 36.954417356 s
a count: 12500, capacity: 125001696


  -- Howard.

On 9 May 2017 at 17:53, Howard Lovatt  wrote:

> I find trimming relative to appending OK on my 6 year old MacBook Pro. EG:
>
> import Foundation
>
> func elapsed(s: DispatchTime, e: DispatchTime) -> Double {
> return Double(e.uptimeNanoseconds - s.uptimeNanoseconds) /
> 1_000_000_000
> }
>
> let s = 250_000_000
> var a = [UInt8]()
> a.reserveCapacity(s)
>
> let sa = DispatchTime.now()
> for i in 1 ... s {
> a.append(0)
> }
> let ea = DispatchTime.now()
> print("Append time: \(elapsed(s: sa, e: ea)) s")
>
> let st = DispatchTime.now()
> let ha = a[0 ..< (s >> 1)]
> let et = DispatchTime.now()
> print("Trim time: \(elapsed(s: st, e: et)) s")
>
> print("ha count: \(ha.count), capacity: \(ha.capacity)")
>
>
> Prints:
>
> Append time: 2.612397389 s
> Trim time: 0.000444132 s
> ha count: 12500, capacity: 12500
>
>
>   -- Howard.
>
> On 9 May 2017 at 12:56, Kelvin Ma via swift-users 
> wrote:
>
>> Depending on what you’re trying to do with the data, you might be better
>> off using an UnsafeBufferPointer and allocating and reallocating that,
>> C-style.
>>
>> On Mon, May 8, 2017 at 7:01 PM, Philippe Hausler via swift-users <
>> swift-users@swift.org> wrote:
>>
>>> I wonder if Data might be a better tool for the job here since it is
>>> it’s own slice type and would avoid copying large amounts of data into
>>> temporary buffers.
>>>
>>> > On May 8, 2017, at 16:47, Rick Mann via swift-users <
>>> swift-users@swift.org> wrote:
>>> >
>>> > I have this C library that interacts with some hardware over the
>>> network that produces a ton of data. It tells me up front the maximum size
>>> the data might be so I can allocate a buffer for it, then does a bunch of
>>> network requests downloading that data into the buffer, then tells me when
>>> it's done and what the final, smaller size is.
>>> >
>>> > Thanks to previous discussions on the list, I settled on using a
>>> [UInt8] as the buffer, because it let me avoid various .withUnsafePointer{}
>>> calls (I need the unsafe buffer pointer to live outside the scope of the
>>> closures). Unfortunately, When I go to shrink the buffer to its final size
>>> with:
>>> >
>>> >self.dataBuffer = Array(self.dataBuffer![0 ..< finalBufferSize])
>>> >
>>> > This ends up taking over 2 minutes to complete (on an iPad Pro).
>>> finalBufferSize is very large, 240 MB, but I think it's doing a very naive
>>> copy.
>>> >
>>> > I've since worked around this problem, but is there any way to improve
>>> on this?
>>> >
>>> > Thanks,
>>> >
>>> > --
>>> > 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
>>>
>>
>>
>> ___
>> 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] Help! Slicing an array is very expensive

2017-05-09 Thread Howard Lovatt via swift-users
I find trimming relative to appending OK on my 6 year old MacBook Pro. EG:

import Foundation

func elapsed(s: DispatchTime, e: DispatchTime) -> Double {
return Double(e.uptimeNanoseconds - s.uptimeNanoseconds) / 1_000_000_000
}

let s = 250_000_000
var a = [UInt8]()
a.reserveCapacity(s)

let sa = DispatchTime.now()
for i in 1 ... s {
a.append(0)
}
let ea = DispatchTime.now()
print("Append time: \(elapsed(s: sa, e: ea)) s")

let st = DispatchTime.now()
let ha = a[0 ..< (s >> 1)]
let et = DispatchTime.now()
print("Trim time: \(elapsed(s: st, e: et)) s")

print("ha count: \(ha.count), capacity: \(ha.capacity)")


Prints:

Append time: 2.612397389 s
Trim time: 0.000444132 s
ha count: 12500, capacity: 12500


  -- Howard.

On 9 May 2017 at 12:56, Kelvin Ma via swift-users 
wrote:

> Depending on what you’re trying to do with the data, you might be better
> off using an UnsafeBufferPointer and allocating and reallocating that,
> C-style.
>
> On Mon, May 8, 2017 at 7:01 PM, Philippe Hausler via swift-users <
> swift-users@swift.org> wrote:
>
>> I wonder if Data might be a better tool for the job here since it is it’s
>> own slice type and would avoid copying large amounts of data into temporary
>> buffers.
>>
>> > On May 8, 2017, at 16:47, Rick Mann via swift-users <
>> swift-users@swift.org> wrote:
>> >
>> > I have this C library that interacts with some hardware over the
>> network that produces a ton of data. It tells me up front the maximum size
>> the data might be so I can allocate a buffer for it, then does a bunch of
>> network requests downloading that data into the buffer, then tells me when
>> it's done and what the final, smaller size is.
>> >
>> > Thanks to previous discussions on the list, I settled on using a
>> [UInt8] as the buffer, because it let me avoid various .withUnsafePointer{}
>> calls (I need the unsafe buffer pointer to live outside the scope of the
>> closures). Unfortunately, When I go to shrink the buffer to its final size
>> with:
>> >
>> >self.dataBuffer = Array(self.dataBuffer![0 ..< finalBufferSize])
>> >
>> > This ends up taking over 2 minutes to complete (on an iPad Pro).
>> finalBufferSize is very large, 240 MB, but I think it's doing a very naive
>> copy.
>> >
>> > I've since worked around this problem, but is there any way to improve
>> on this?
>> >
>> > Thanks,
>> >
>> > --
>> > 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
>>
>
>
> ___
> 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 use a protocol to infer a generic type with constraints

2017-05-02 Thread Howard Lovatt via swift-users
Another +1 from me, a real pain

-- Howard.

> On 3 May 2017, at 4:05 am, David Sweeris via swift-users 
>  wrote:
> 
> 
>> On May 2, 2017, at 10:16 AM, Edward Connell via swift-users 
>>  wrote:
>> 
>> Does anyone have an idea when this is going to be fixed? Or when support 
>> will be implemented?
>> My app heavily uses collections of heterogenous plug-ins, so it's a real 
>> pain in the neck to work around.
> 
> My understanding is that allowing protocols to conform to themselves would be 
> a *ton* of work. That’s not to say it’ll never happen, but the current 
> behavior isn’t considered a bug, and I don’t think the feature is likely to 
> happen without a proposal getting accepted on swift-evolution (it’s come up a 
> few times before… IIRC it’s always been shot down because something like 
> “yes, we’d all like it, but we only have so much time before the next release 
> and there’s some much lower-hanging fruit that we should work on first”).
> 
> Feel free to start another thread about it… it’d get a +1 from me. I’d almost 
> bet money though that it won’t happen until at least Swift 5 (unless it’s a 
> surprise at WWDC or something).
> 
> - Dave Sweeris
> ___
> 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] Are all extensions from all modules exported on mass?

2017-04-19 Thread Howard Lovatt via swift-users
Hi,

If I have the *same* extension in two *different* modules, ModuleA and
ModuleB, and ModuleC uses both modules, but in *seperate* files, then there
is still ambiguity about which extension to call:

ModuleA

A.swift

public protocol P {

func m() -> String

}

extension Int: P {

public func m() -> String { return "AP.m" }

}

ModuleB

B.swift

public protocol P {

func m() -> String

}
extension Int: P {

public func m() -> String { return "BP.m" }

}

ModuleC

A.swift

import ModuleA

func am(_ i: Int) -> String { return i.m() }

B.swift

import ModuleB

func bm(_ i: Int) -> String { return i.m() }

main.swift

let i = 0

print(am(i))
print(bm(i))


Gives the following errors when built:

sunzero-ln:ModuleC lov080$ swift build
Fetching /Users/lov080/Google Drive/Swift/Examples/Example Module
Clashes/ModuleA
Fetching /Users/lov080/Google Drive/Swift/Examples/Example Module
Clashes/ModuleB
Cloning /Users/lov080/Google Drive/Swift/Examples/Example Module
Clashes/ModuleA
Resolving /Users/lov080/Google Drive/Swift/Examples/Example Module
Clashes/ModuleA at 1.0.0
Cloning /Users/lov080/Google Drive/Swift/Examples/Example Module
Clashes/ModuleB
Resolving /Users/lov080/Google Drive/Swift/Examples/Example Module
Clashes/ModuleB at 1.0.0
Compile Swift Module 'ModuleB' (1 sources)
Compile Swift Module 'ModuleA' (1 sources)
Compile Swift Module 'ModuleC' (3 sources)
/Users/lov080/Google Drive/Swift/Examples/Example Module
Clashes/ModuleC/Sources/B.swift:3:38: error: ambiguous use of 'm()'
func bm(_ i: Int) -> String { return i.m() }
 ^
ModuleA.Int:2:17: note: found this candidate
public func m() -> String
^
ModuleB.Int:2:17: note: found this candidate
public func m() -> String
^
/Users/lov080/Google Drive/Swift/Examples/Example Module
Clashes/ModuleC/Sources/A.swift:3:38: error: ambiguous use of 'm()'
func am(_ i: Int) -> String { return i.m() }
 ^
ModuleA.Int:2:17: note: found this candidate
public func m() -> String
^
ModuleB.Int:2:17: note: found this candidate
public func m() -> String
^
:0: error: build had 1 command failures
error: exit(1): /Applications/Xcode.app/Contents/Developer/Toolchains/
XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/lov080/Google\
Drive/Swift/Examples/Example\ Module\ Clashes/ModuleC/.build/debug.yaml

Is this the expected behaviour or a bug?

Thanks in advance for any help,

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


Re: [swift-users] The case of broken polymorphism or "Cannot convert value of type to expected argument type"?

2017-02-20 Thread Howard Lovatt via swift-users
It is confusing in Swift what can be covariant and what is invariant,
consider:

// Covarant arrays work
class A {}
class B: A {}
let a = A() // A
let b = B() // B
var arrayA = [a] // Array
arrayA[0] = b // OK

// And arrays of arrays
var arrayArrayA = [arrayA] // Array
arrayArrayA[0][0] = b // OK
let arrayB = [b] // Array
arrayArrayA[0] = arrayB // OK, works out that an Array is a Array

// Covariant homebrew-collections work
class C {
var e: T
init(_ e: T) { self.e = e }
}
var cA = C(a) // C
cA.e = b // OK

// But not quite for homebrew-collections of homebrew-collections
var cCA = C(cA) // C
cCA.e.e = b // OK
let cB = C(b) // C
// cCA.e = cB // Error - cannot work out that a C is a C but can
do so for arrays

It is weird that the last line fails and the equivalent Array line doesn't.
I suspect that there is some special typing going on for arrays, probably
to make them play nice with Objective-C. However it would be simpler if
everything was covariant when safe to be covariant, i.e. The last line
should work.

 -- Howard.

On Mon, 20 Feb 2017 at 8:38 pm, Isaac Rivera via swift-users <
swift-users@swift.org> wrote:

> I can see it is a (counter-intuitive) language design decision for type
> safety… but then why, in the code below I can:
>
> class OtherThing: Something {
> override func start(_ completion: SomeCallback? = nil) {
> // implementation details...
> }
> }
>
> let firstThing = OtherThing(viewController: UINavigationController())
>
> OtherThing extends Something… but I can instantiate it
> with the subtype…
>
> Ok you will say, UINavigationController is a subtype of UIViewController,
> but that still does not make Something a subtype
> of Something.
>
> Fair enough, but:
>
> let c1: Something = Something(viewController:
> UINavigationController())
> // c1 is of type "Something"
>
> let c2 = Something(viewController: UINavigationController())
> // c1 is of type "Something”
>
> So it appears Something can be cast to type
> Something…
>
> Yet this is illegal?
>
> let somethings: [Something] = [c1, c2]
>
> I dont know, something seems inconsistent.
>
>
> On Feb 16, 2017, at 10:59 PM, Slava Pestov  wrote:
>
> Hi Isaac,
>
> This is not about associated types. Rather, the issue is that a ‘Thing’ is
> a ‘Something’, but you are casting it to
> ‘Something’. The two types are not related; in general,
> if A is a subtype of B, then G is not a subtype of G.
>
>
> https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)
>
> Slava
>
> On Feb 16, 2017, at 9:05 AM, Isaac Rivera via swift-users <
> swift-users@swift.org> wrote:
>
> Hello, list!
>
> I am trying to find my way around Swift’s protocol limitations. It appears
> that in general, any protocol with declared associatedtype will break
> polymorphism?
>
> Take the case below which does not compile. All "Thing” instances are
> "Something” but they can’t be passed around or
> coerced as so.
>
> How is it that I can legally write the code:
>
> class Thing: Something { }
>
> and instantiate it, but it is not the very thing it implements?
>
> All Thing instances conform to the public interfaces of
> Something so why can’t they be recognized as such and
> coerced as such?
>
> What is the work-around of this break in Polymorphism?
>
> import UIKit
>
> protocol Anything: class, NSObjectProtocol {
>
> associatedtype ViewControllerType: UIViewController
>
> var viewController: ViewControllerType { get }
>
> init(viewController: ViewControllerType)
>
> func addAnything(anything: Something) -> Bool
> }
>
> class Something: NSObject, Anything {
>
> typealias ViewControllerType = VC
>
> private(set) var viewController: ViewControllerType
>
> required init(viewController: ViewControllerType) { self.viewController =
> viewController }
>
> final private var things = [String: Something]()
>
> final internal func addAnything(anything: Something) ->
> Bool {
> // implementation details...
> return true
> }
> }
>
> class Thing: Something { }
>
> let firstThing = Thing(viewController: UINavigationController())
> let secondThing = Thing(viewController: UINavigationController())
>
> firstThing.addAnything(anything: secondThing)
>
> // Playground execution failed: error: MyPlayground.playground:48:34:
> error: cannot convert value of type 'Thing' to expected argument type
> 'Something'
>
> firstThing.addAnything(anything: secondThing as
> Something)
>
> // Playground execution failed: error: MyPlayground.playground:48:34:
> error: cannot convert value of type 'Thing' to type
> 'Something' in coercion
>
>
>
>
> ___
> 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] Associativity of && and || operator

2017-02-20 Thread Howard Lovatt via swift-users
To me it would be surprising if && grouped differently than * or &; since
it is closely associated with boolean-and, which in turn is the equivalent
operation to multiply in Boolean logic.

On Fri, 17 Feb 2017 at 7:56 pm, rintaro ishizaki via swift-users <
swift-users@swift.org> wrote:

> Hello all,
>
> Why the associativity of Logical{Conjunction,Disjunction}Precedence is "
> left"?
>
> If you write: A && B && C, it's grouped as (A && B) && C.
> This means that the && function is *always* called twice: (&&)((&&)(A,
> B), C).
> I feel "right" associativity is more natural:  (&&)(A, (&&)(B, C)),
> because the && function is called only once if A is false.
>
> I know that redundant && calls are optimized away in most cases.
> I also know C and C++ standard says: "The && operator groups
> left-to-right", and most programming languages follow that.
>
> But why not "right" associativity?
> What is the difference between logical operators and ?? operator that has
> "right" associativity?
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-- 
-- Howard.
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] [swift-evolution] for-else syntax

2017-02-05 Thread Howard Lovatt via swift-users
It is a functional style, so typically you use return for continue and
throws to accomplish break and return, e.g.:

// Continue
let a = [0, 1]
a.forEach { _ in return } // for _ in a { continue }

// Break and return
enum LoopControls: Error {
case exitLoop // Break
case returnValue(T) // Return
}
do {
do {
try a.forEach { _ in throw LoopControls.exitLoop } // for
_ in a { break }
} catch LoopControls.exitLoop {
// Process break if you need to
}
try a.forEach { _ in throw LoopControls.returnValue(42.0) }
// for _ in a { return 42.0 }
} catch LoopControls.returnValue(let value) {
return value
}



On Sun, 5 Feb 2017 at 2:32 pm, Rob Mayoff via swift-users <
swift-users@swift.org> wrote:

> On Fri, Feb 3, 2017 at 7:15 PM, Howard Lovatt via swift-users <
> swift-users@swift.org> wrote:
>
> Why not add to the library:
>
> extension Sequence {
> func forEach(_ eacher: (Iterator.Element) throws -> Void, elser: ()
> throws -> Void) rethrows {
>
>
> This doesn't work with break or continue and changes the meaning of return.
>
> It would be nice for Swift to support Tcl-like exceptional return codes so
> we can build control flow functions that work with break, continue, and
> return properly.
>
> http://www.tcl.tk/man/tcl/TclCmd/return.htm
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-- 
-- Howard.
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] [swift-evolution] for-else syntax

2017-02-03 Thread Howard Lovatt via swift-users
Why not add to the library:

extension Sequence {
func forEach(_ eacher: (Iterator.Element) throws -> Void, elser: ()
throws -> Void) rethrows {
var hasIterated = false
for element in self {
hasIterated = true
try eacher(element)
}
guard hasIterated else {
try elser()
return
}
}
}

On Fri, 3 Feb 2017 at 8:33 pm, Jeremy Pereira via swift-users <
swift-users@swift.org> wrote:

>
> > On 2 Feb 2017, at 20:12, Erica Sadun via swift-users <
> swift-users@swift.org> wrote:
> >
> > I've taken this over to Swift Users from Swift Evolution.
> >
> > I think you'd want to handle the exceptional case first,
>
> Although it is the way I would do it for an array, sometimes you don’t
> know that a sequence is empty until after you have iterated it.
>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-- 
-- Howard.
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Static type when expecting dynamic type

2017-02-02 Thread Howard Lovatt via swift-users
Thanks for your prompt responses.

Have filed a bug:

SR-3840 - Closure picks up static type not dynamic
<https://bugs.swift.org/browse/SR-3840>

  -- Howard.

On 3 February 2017 at 08:57, Slava Pestov <spes...@apple.com> wrote:

> The problem is were not marking the materializeForSet accessor
> in DefaultMutableReference.value as an override. Definitely a bug:
>
> sil_vtable DefaultMutableReference {
>   #MutableReference.init!initializer.1: 
> _TFC1d23DefaultMutableReferencecfT_GS0_x_
> // DefaultMutableReference.init() -> DefaultMutableReference
>   #MutableReference.value!getter.1: _TFC1d23DefaultMutableReferenceg5valuex
>   // DefaultMutableReference.value.getter
>   #MutableReference.value!setter.1: _TFC1d23DefaultMutableReferences5valuex
>   // DefaultMutableReference.value.setter
>   #MutableReference.value!materializeForSet.1: _
> TFC1d16MutableReferencem5valuex // MutableReference.value.
> materializeForSet
>   #DefaultMutableReference.value!materializeForSet.1: _
> TFC1d23DefaultMutableReferencem5valuex   // DefaultMutableReference.value.
> materializeForSet
>
> The last entry should not exist.
>
> I’ll have a fix shortly.
>
> Slava
>
> On Feb 2, 2017, at 9:04 AM, Jordan Rose via swift-users <
> swift-users@swift.org> wrote:
>
> Seems like a bug, and moreover it seems like a regression from Swift 3.0.
> Mind filing a report at bugs.swift.org?
>
> Thanks!
> Jordan
>
> On Feb 1, 2017, at 20:49, Howard Lovatt via swift-users <
> swift-users@swift.org> wrote:
>
> Hi All,
>
> Anyone know what is going on here:
>
> //: Closure picks up static type not dynamic
>
> class MutableReference {
> init() {
> guard type(of: self) != MutableReference.self else {
> fatalError("MutableReference is an abstract class; create
> a derrivative of MutableReference")
> }
> }
> var value: T {
> get {
> fatalError("Calculated property value getter should be
> overridden")
> }
> set {
> fatalError("Calculated property value setter should be
> overridden")
> }
> }
> }
>
> class DefaultMutableReference: MutableReference {
> private var _value: T
> override var value: T {
> get {
> return _value
> }
> set {
> _value = newValue
> }
> }
> init(_ value: T) {
> _value = value
> }
> }
>
> let e: (MutableReference<[Int]>, Int) -> Void = { $0.value.append($1) }
> let dmr = DefaultMutableReference([2])
> dmr.value // [2]
> e(dmr, 2) // fatal error: Calculated property value getter should be
> overridden
> dmr.value // Expect [2, 2]
>
> If I change `e` to:
> let e: (DefaultMutableReference<[Int]>, Int) -> Void = {
> $0.value.append($1) }
>
> It works fine.
>
> IE the closure is using the static type of its first argument and not
> dynamically dispatching.
>
> Am I doing something wrong? Is there a way round where I can still use the
> base class for `e`?
>
>
> Thanks for any help in advance,
>
> -- Howard.
> ___
> 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] Static type when expecting dynamic type

2017-02-01 Thread Howard Lovatt via swift-users
Hi All,

Anyone know what is going on here:

//: Closure picks up static type not dynamic

class MutableReference {
init() {
guard type(of: self) != MutableReference.self else {
fatalError("MutableReference is an abstract class; create a
derrivative of MutableReference")
}
}
var value: T {
get {
fatalError("Calculated property value getter should be
overridden")
}
set {
fatalError("Calculated property value setter should be
overridden")
}
}
}

class DefaultMutableReference: MutableReference {
private var _value: T
override var value: T {
get {
return _value
}
set {
_value = newValue
}
}
init(_ value: T) {
_value = value
}
}

let e: (MutableReference<[Int]>, Int) -> Void = { $0.value.append($1) }
let dmr = DefaultMutableReference([2])
dmr.value // [2]
e(dmr, 2) // fatal error: Calculated property value getter should be
overridden
dmr.value // Expect [2, 2]

If I change `e` to:
let e: (DefaultMutableReference<[Int]>, Int) -> Void = {
$0.value.append($1) }

It works fine.

IE the closure is using the static type of its first argument and not
dynamically dispatching.

Am I doing something wrong? Is there a way round where I can still use the
base class for `e`?


Thanks for any help in advance,

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


Re: [swift-users] [swift-evolution] Best way to handle escaping function that might throw

2017-01-14 Thread Howard Lovatt via swift-users
I am assuming Never is the subtype of all types, because any function
regardless of it's return type, including Void, can return Never.

On Fri, 13 Jan 2017 at 6:32 pm, Pierre Monod-Broca <
pierremonodbr...@gmail.com> wrote:

> @Howard
> I was thinking the same about the constraint.
>
> Does that mean that Never should be a subtype of Error (maybe it is
> already) ? Else you couldn't say throws(Never) or FSTore
>
> @Howard
> I'm not sure about <>, it should stay reserved for generics, IMHO.
>
> Pierre
>
> Le 13 janv. 2017 à 01:11, Howard Lovatt via swift-users <
> swift-users@swift.org> a écrit :
>
> @Anton, Yes that would work and we would get typed throws, which I like.
> As an aside, I think E would have to be constrained to be an Error, ` Error>`, and maybe `throws` reads better because you are used to types
> in angle brackets.
>
>   -- Howard.
>
>
>
> On 13 January 2017 at 08:32, Anton Zhilin <antonyzhi...@gmail.com> wrote:
>
> The best way to deal with such situations should be typed throws. Then
> rethrows should be removed and replaced with generics in throws clause. E
> == Never ⇔ function does not throw.
>
>
> struct FStore {
>
> let f: () throws(E) -> Void
>
> init(_ f: @escaping () throws(E) -> Void) { self.f = f }
>
> func call() throws(E) { try f() }
>
> }
>
>
>
> let store = FStore({ print("Hello") })
>
> store.call()
>
> [Phase2]
>
>
> ​
>
>
>
>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
> --
-- Howard.
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] [swift-evolution] Best way to handle escaping function that might throw

2017-01-12 Thread Howard Lovatt via swift-users
@Slava,

I'm imagining that the compiler does much the same as Anton suggested, e.g.
Anton's:

struct FStore {
let f: () throws -> Void
init(_ f: @escaping () throws -> Void) { self.f = f }
func call() throws { try f() }
}

Is much the same as my:

struct FStore {
let f: () throws -> Void
init(_ f: @escaping () throws -> Void) { self.f = f }
func call() throws { try f() }
}

>From a compiler point of view.

The idea is that the compiler reuses some of its existing generic's
infrastructure. The main differences between my proposal and Anton's is
that because mine doesn't use a typed throw, E can only be 'AnyError' (any
type that implements Error) or Never, and E is not explicit. The
throws/rethrows distinction just becomes a compiler optimization in both
cases.

  -- Howard.

On 13 January 2017 at 10:42, Slava Pestov  wrote:

>
> On Jan 11, 2017, at 2:02 PM, Howard Lovatt via swift-evolution <
> swift-evolut...@swift.org> wrote:
>
> Another possibility, other than generics, would be to drop rethrows all
> together and have the compiler infer if a throw is possible or not,
> including:
>
> struct FStore {
> let f: () throws -> Void
> func call() throws { try f() }
> }
>
> The compiler can make two versions, one if f can throw and one if it
> definitely doesn't.
>
>
> It seems that this approach is impractical, because you either have to
> compile two versions of every function, or make all function bodies
> available for inlining, which is a non-starter for a stable ABI.
>
> Slava
>
>
> Just a thought.
>
> On Tue, 10 Jan 2017 at 4:29 pm, Jacob Bandes-Storch 
> wrote:
>
>> Moving to swift-users list.
>>
>> No, there's no way to do this today. The point of rethrows is that within
>> one call site, "f(block)" can be treated as throwing if the block throws,
>> or not throwing if the block doesn't throw. In your example, once the
>> FStore object is constructed, the information about the original passed-in
>> function is lost, so the caller has no way to know whether call() can throw
>> or not.
>>
>> If this *were* possible, the information would somehow need to be encoded
>> in the type system when creating FStore(f: block). That would require
>> something like dependent typing, or generic-param-based-rethrows, e.g.
>>
>> struct FStore Void> {  // made-up syntax
>> let f: T
>> func call() rethrows(T) { try f() }  // throws-ness of this function
>> depends on throws-ness of T
>> }
>>
>>
>>
>> On Mon, Jan 9, 2017 at 9:21 PM, Howard Lovatt via swift-evolution > evolut...@swift.org> wrote:
>>
>> Hi,
>>
>> If I have an escaping function that I store and then call, I need to
>> declare the calling function as throwing, not rethrowing. EG:
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>> struct FStore {
>> let f: () throws -> Void
>> init(f: @escaping () throws -> Void) { self.f = f }
>> func call() throws { try f() } // Can't put rethrows here - have
>> to use throws
>> }
>> Is there a better solution?
>>
>> Thanks for any suggestions,
>>
>>   -- Howard.
>>
>>
>>
>>
>>
>> ___
>>
>>
>> swift-evolution mailing list
>>
>>
>> swift-evolut...@swift.org
>>
>>
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>
>>
>>
>>
>>
>>
>> --
> -- Howard.
> ___
> swift-evolution mailing list
> swift-evolut...@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] [swift-evolution] Best way to handle escaping function that might throw

2017-01-12 Thread Howard Lovatt via swift-users
@Anton, Yes that would work and we would get typed throws, which I like. As
an aside, I think E would have to be constrained to be an Error, ``, and maybe `throws` reads better because you are used to types
in angle brackets.

  -- Howard.

On 13 January 2017 at 08:32, Anton Zhilin  wrote:

> The best way to deal with such situations should be typed throws. Then
> rethrows should be removed and replaced with generics in throws clause. E
> == Never ⇔ function does not throw.
>
> struct FStore {
> let f: () throws(E) -> Void
> init(_ f: @escaping () throws(E) -> Void) { self.f = f }
> func call() throws(E) { try f() }
> }
>
> let store = FStore({ print("Hello") })
> store.call()
>
> [Phase2]
> ​
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] [swift-evolution] Best way to handle escaping function that might throw

2017-01-11 Thread Howard Lovatt via swift-users
Yes, I have used Result in the past.

In this case I wanted to use throws because that is what functions like map
do.

Looks like I will have to stick with throwing, not too bad since the
overhead is reasonably low.

On Wed, 11 Jan 2017 at 8:03 am, T.J. Usiyan  wrote:

> I suggest using an enum to represent success and failure. It's usually
> referred to as `Result`. It might seem weird for the closure that you
> presented as an example, since it would be Result, but it properly
> captures the possibility of having thrown.
>
> ``` swift
> enum UselessError : Swift.Error {
> case somethingBadHappened
> }
>
>
> enum Result {
> case success(T)
> case failure(Swift.Error)
>
> init(throwingClosure: (Void) throws -> T) {
> do {
> self = try .success(throwingClosure())
> } catch {
> self = .failure(error)
> }
> }
> }
>
> func burnItDown() throws -> Void {
> throw UselessError.somethingBadHappened
> }
>
> Result(throwingClosure: burnItDown)
> ```
>
>
>
> On Mon, Jan 9, 2017 at 10:28 PM, Jacob Bandes-Storch via swift-users <
> swift-users@swift.org> wrote:
>
> Moving to swift-users list.
>
> No, there's no way to do this today. The point of rethrows is that within
> one call site, "f(block)" can be treated as throwing if the block throws,
> or not throwing if the block doesn't throw. In your example, once the
> FStore object is constructed, the information about the original passed-in
> function is lost, so the caller has no way to know whether call() can throw
> or not.
>
> If this *were* possible, the information would somehow need to be encoded
> in the type system when creating FStore(f: block). That would require
> something like dependent typing, or generic-param-based-rethrows, e.g.
>
> struct FStore Void> {  // made-up syntax
> let f: T
> func call() rethrows(T) { try f() }  // throws-ness of this function
> depends on throws-ness of T
> }
>
>
>
> On Mon, Jan 9, 2017 at 9:21 PM, Howard Lovatt via swift-evolution <
> swift-evolut...@swift.org> wrote:
>
> Hi,
>
> If I have an escaping function that I store and then call, I need to
> declare the calling function as throwing, not rethrowing. EG:
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> struct FStore {
> let f: () throws -> Void
> init(f: @escaping () throws -> Void) { self.f = f }
> func call() throws { try f() } // Can't put rethrows here - have
> to use throws
> }
> Is there a better solution?
>
> Thanks for any suggestions,
>
>   -- Howard.
>
>
>
>
>
> ___
>
>
> swift-evolution mailing list
>
>
> swift-evolut...@swift.org
>
>
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
>
>
>
>
>
> ___
>
>
> swift-users mailing list
>
>
> swift-users@swift.org
>
>
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
>
>
>
>
> --
-- Howard.
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] [swift-evolution] Best way to handle escaping function that might throw

2017-01-11 Thread Howard Lovatt via swift-users
Another possibility, other than generics, would be to drop rethrows all
together and have the compiler infer if a throw is possible or not,
including:

struct FStore {
let f: () throws -> Void
func call() throws { try f() }
}

The compiler can make two versions, one if f can throw and one if it
definitely doesn't.

Just a thought.

On Tue, 10 Jan 2017 at 4:29 pm, Jacob Bandes-Storch 
wrote:

> Moving to swift-users list.
>
> No, there's no way to do this today. The point of rethrows is that within
> one call site, "f(block)" can be treated as throwing if the block throws,
> or not throwing if the block doesn't throw. In your example, once the
> FStore object is constructed, the information about the original passed-in
> function is lost, so the caller has no way to know whether call() can throw
> or not.
>
> If this *were* possible, the information would somehow need to be encoded
> in the type system when creating FStore(f: block). That would require
> something like dependent typing, or generic-param-based-rethrows, e.g.
>
> struct FStore Void> {  // made-up syntax
> let f: T
> func call() rethrows(T) { try f() }  // throws-ness of this function
> depends on throws-ness of T
> }
>
>
>
> On Mon, Jan 9, 2017 at 9:21 PM, Howard Lovatt via swift-evolution <
> swift-evolut...@swift.org> wrote:
>
> Hi,
>
> If I have an escaping function that I store and then call, I need to
> declare the calling function as throwing, not rethrowing. EG:
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> struct FStore {
> let f: () throws -> Void
> init(f: @escaping () throws -> Void) { self.f = f }
> func call() throws { try f() } // Can't put rethrows here - have
> to use throws
> }
> Is there a better solution?
>
> Thanks for any suggestions,
>
>   -- Howard.
>
>
>
>
>
> ___
>
>
> swift-evolution mailing list
>
>
> swift-evolut...@swift.org
>
>
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
>
>
>
>
> --
-- Howard.
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Weird protocol behaviour.

2016-12-22 Thread Howard Lovatt via swift-users
The following variation works:

protocol P {}


class P1:P {}


class X:P1 {}


func foo(_ x:A) {}


func bar() {

//let x = X() // this compiles

let x = X() as P1 // this does not compile. Why?

foo(x)

}

Which adds credence to the bug theory.

Note two changes: 1. two levels of inheritance and 2. change to classes. If
you do two levels using protocols it doesn't work if you use either classes
or structs.


  -- Howard.

On 23 December 2016 at 07:29, Kevin Nattinger <sw...@nattinger.net> wrote:

> I recall seeing a request on the -evolution list for something like `T :=
> X` to indicate it could be X itself or anything inheriting / implementing
> it, so it’s certainly known behavior, if not desired. IMO it’s a bug and
> `:` should be fixed to include the root type, whether or not that requires
> a discussion on -evolution.
>
> On Dec 22, 2016, at 2:17 PM, Howard Lovatt via swift-users <
> swift-users@swift.org> wrote:
>
> I suspect a compiler bug since A is a P. The equivalent in Java works:
>
> interface P {}
> class X implements P {}
>
>
>  void foo(A x) {}
>
>
> void bar() {
> final P x = new X();
> foo(x);
> }
>
> -- Howard.
>
> On 23 Dec 2016, at 3:19 am, Rien via swift-users <swift-users@swift.org>
> wrote:
>
> IMO the error message says it all:
>
> Playground execution failed: error: MyPlayground8.playground:9:5: error:
> cannot invoke 'foo' with an argument list of type '(P)'
>foo(x)
>^
>
> MyPlayground8.playground:9:5: note: expected an argument list of type '(A)'
>foo(x)
>^
>
> I.e. you are passing in a protocol while the function is specified for a
> type.
> Said other way: On which data do you expect the protocol to operate?
>
> Regards,
> Rien
>
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Swiftrien
> Project: http://swiftfire.nl
>
>
>
>
> On 22 Dec 2016, at 17:05, Mikhail Seriukov via swift-users <
> swift-users@swift.org> wrote:
>
>
> Hello community! I' wondering if somebody can explain this to me.
>
> Please take look at the snippet.
>
>
> protocol P {}
>
> struct X:P {}
>
>
> func foo(_ x:A) {}
>
>
> func bar() {
>
>//let x = X() // this compiles
>
>let x = X() as P // this does not compile. Why?
>
>foo(x)
>
> }
>
>
> I expect the both cases to work though. But only first works? And I do not
> understand why.
>
> My coworkers said that it is a compiler bug, but I'm not shure it is.
>
> Thanks for the help.
>
> ___
>
> 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] Dimensional analysis

2016-11-30 Thread Howard Lovatt via swift-users
Another feature I would like would be a dimensions wrapper for an array. So
that I can mark all values in the array as having the same units, rather
than mark each individual element as having a particular unit.

It is conceivable that wrapping each element, both performance and memory
wise, is OK depending on implementation. However my experience with
Mathematica's Quantity is that wrapping each element is a significant
overhead. Therefore I would like a dimensioned array.

As an aside. It might be a lot easier to write an array wrapper when we get
Conditional Conformance To Protocols with the improved generics slated for
Swift 4.1. Therefore it might be worth waiting until 4.1. before attempting
a dimensioned array.

  -- Howard.

On 1 December 2016 at 01:17, Maury Markowitz via swift-users <
swift-users@swift.org> wrote:

> Let me add my support for this as well. I am currently using a bridge
> version of:
>
> https://github.com/unixpickle/Expressions
>
> And it works quite well. But I think a pure Swift implementation,
> especially with dimensional analysis, would be useful to a great number of
> people.
> ___
> 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] Changing precedence of / operator for my protocol?

2016-11-29 Thread Howard Lovatt via swift-users
Why not define some other symbol so that you can get the precedence you
want?

  -- Howard.

On 30 November 2016 at 09:28, Greg Parker via swift-users <
swift-users@swift.org> wrote:

>
> > On Nov 29, 2016, at 2:55 AM, Rick Mann via swift-users <
> swift-users@swift.org> wrote:
> >
> > Working on dimensional analysis, I have some proof-of-concept code that
> seems to be working:
> >
> >let n1 = kilogram * meter / second * second
> >([(kg⋅m) / s]⋅s)
> >
> > let n2 = kilogram * meter / (second * second)
> >[(kg⋅m) / (s⋅s)]
> >
> > Note: () around unit products, [] around unit quotients.
> >
> > I'd like to adjust the precedence of operator * for my Unit protocol to
> be higher than /. Is that possible? It wasn't at all clear to me how to do
> that in Swift 3, or if can even be done at all.
>
> You can't. A Swift operator's precedence is the same for all types that
> implement that operator. Operators * and / cannot use the same precedence
> on Int but different precedence on Unit.
>
> You could try to change the precedence of * and / globally - they're
> defined like any other operator in stdlib/public/core/Policy.swift - but
> you'll break lots of other code that way.
>
>
> --
> Greg Parker gpar...@apple.com Runtime Wrangler
>
>
> ___
> 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] hello, first time poster and accelerate question

2016-11-21 Thread Howard Lovatt via swift-users
Take a look at the Surge library.

On Tue., 22 Nov. 2016 at 4:24 am, Kenny Leung via swift-users <
swift-users@swift.org> wrote:

> If only you could write this directly in Swift and have it use accelerate…
>
> -Kenny
>
>
> > On Nov 18, 2016, at 8:07 PM, Jacob Bandes-Storch via swift-users <
> swift-users@swift.org> wrote:
> >
> > I must have forgotten how matrices work—I think it's actually this
> direction. And I also lost an m :-)
> >
> > 
> >
> >
> > On Fri, Nov 18, 2016 at 7:55 PM, Jacob Bandes-Storch 
> wrote:
> > Can't you achieve this with a single vector*matrix multiplication?
> >
> > [1/n,  1/n,  ...,  1/n] * A  =  [mean(col 1); mean(col 2); ...; mean(col
> n)]
> >
> > Or in more legible form:
> >
> > 
> >
> > Jacob
> >
> > On Fri, Nov 18, 2016 at 5:36 AM, Yuma Decaux via swift-users <
> swift-users@swift.org> wrote:
> > Hello everyone,
> >
> > Nice to meet y'all, and here's my first question:
> >
> > I am currently setting a semantically easy to use accelerate operation
> extension set for my research.
> >
> > I have done all the basic operations, vector to scalar, vector to
> vector, matrix mult matrix, transpose etc, but would like to know what the
> best approach might be for getting the mean for a matrix, as I am not sure
> if the result is what I think it is. In fact, I would like an output of m
> by 1 from an n by m matrix with means of each column vector.
> >
> > The function is:
> > func vDSP_meanvD(UnsafePointer, vDSP_Stride,
> UnsafeMutablePointer, vDSP_Length)
> >
> > I assume for a vector this is fine since it is 1 dimensional, but for
> matrices here is my question:
> >
> > What is the approach to take?
> > 1-Do I slice my matrix into m copies of size n where M_i(n by m) and
> pass them all through vDSP_meanvD?
> > 2- Does the stride argument take care of this, in that if I have stride
> of n, then the ranges [0:n], [n+1: 2n], [2n+1: 3n] will have their mean and
> std computed?
> >
> >
> > Thanks for any pointer
> >
> > Best regards,
> >
> >
> >
> >
> > ___
> > 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
>
-- 
-- Howard.
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Workaround for generics not currently supporting conditional conformance to a protocol

2016-11-16 Thread Howard Lovatt via swift-users
Pity nothing else works, looks like I am stuck with multiple wrappers.

I will echo Dave's, Tim's, and Jordan's thoughts, roll on Conditional
Conformance.

Thanks for your help.

  -- Howard.

On 17 November 2016 at 09:35, Jordan Rose <jordan_r...@apple.com> wrote:

>
> On Nov 16, 2016, at 7:35, David Sweeris via swift-users <
> swift-users@swift.org> wrote:
>
>
> On Nov 15, 2016, at 11:55 PM, Howard Lovatt <howard.lov...@gmail.com>
> wrote:
>
> @Dave,
>
> How do I write that though.
>
> I can't write:
>
> extension Array: Equatable {
> static func ==(lhs: Array, rhs: Array) -> Bool {
> let size = lhs.count
> precondition(rhs.count == size, "The arrays must be the same
> length")
> for i in 0 ..< size {
> if (lhs[i] as! Equatable) != (rhs[i] as! Equatable) {
> return false
> }
> }
> return true
> }
> }
>
> Because I can't cast to an Equatable, because Equatable uses Self.
>
> Am I missing something?
>
>  -- Howard.
>
>   -- Howard.
>
> On 16 November 2016 at 16:35, David Sweeris <daveswee...@mac.com> wrote:
>
>>
>> > On Nov 15, 2016, at 21:39, Howard Lovatt via swift-users <
>> swift-users@swift.org> wrote:
>> >
>> > Hi All,
>> >
>> > Does anyone have a good workaround for generics not currently
>> supporting conditional conformance to a protocol. As stated in the Generics
>> Manifesto something like this would be nice:
>> >
>> >   extension Array: Equatable where Element: Equatable {
>> > static func ==(lhs: Array, rhs: Array) -> Bool { ... }
>> > }
>> >
>> > But I would currently write a wrapper, something like:
>> >
>> > struct ArrayE {
>> > var elements: [T]
>> > }
>> > extension ArrayE: Equatable {
>> > static func ==(lhs: ArrayE, rhs: ArrayE) -> Bool { ...  }
>> > }
>> >
>> > This can get unwieldy when there are a lot of conditional protocol
>> extensions required, i.e. wrappers round wrappers.
>> >
>> > Is there a better way?
>> >
>> > Thanks for any tips,
>> >
>> >   -- Howard.
>> > ___
>> > swift-users mailing list
>> > swift-users@swift.org
>> > https://lists.swift.org/mailman/listinfo/swift-users
>>
>> Can you make Array conform to Equatable for any T and then in the ==
>> function, if T conforms to Equatable loop the Arrays to check if they're
>> equal, and if it doesn't conform just return false?
>>
>> I mean, it's still "wrong", but at least you won't get any false
>> positives.
>>
>> - Dave Sweeris
>
>
>
> You are correct. The work-around is to use two extensions and overload the
> == operator:
>
> extension Array: Equatable {
> public static func == (lhs: Array, rhs: Array) -> Bool {
> return false
> }
> }
> extension Array where Element : Equatable {
> public static func == (lhs: Array, rhs: Array) -> Bool {
> return lhs.count == rhs.count && {
> for i in 0.. if lhs[i] != rhs[i] {
> return false
> }
> }
> return true
> }()
> }
> }
>
> It works in playgrounds (Xcode 8.1 (8B62)), but I haven’t tested it
> outside a few trivial cases.
>
>
> This does not work. The == dispatch for Arrays is static in this case, not
> dynamic. You can test this by writing something generic on Equatable.
>
> func same(_ x: T, _ y: T) -> Bool { return x == y }
> print(same([1], [2]))
>
>
> Rule of thumb: overloads are resolved statically, protocol requirements
> are invoked dynamically. You cannot get dynamic behavior out of just
> overloads, ever.
>
> I don't think there's a way to get this behavior today, unfortunately.
>
> Jordan
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Fwd: Workaround for generics not currently supporting conditional conformance to a protocol

2016-11-15 Thread Howard Lovatt via swift-users
@Dave,

How do I write that though.

I can't write:

extension Array: Equatable {
static func ==(lhs: Array, rhs: Array) -> Bool {
let size = lhs.count
precondition(rhs.count == size, "The arrays must be the same
length")
for i in 0 ..< size {
if (lhs[i] as! Equatable) != (rhs[i] as! Equatable) {
return false
}
}
return true
}
}

Because I can't cast to an Equatable, because Equatable uses Self.

Am I missing something?

 -- Howard.

  -- Howard.

On 16 November 2016 at 16:35, David Sweeris <daveswee...@mac.com> wrote:

>
> > On Nov 15, 2016, at 21:39, Howard Lovatt via swift-users <
> swift-users@swift.org> wrote:
> >
> > Hi All,
> >
> > Does anyone have a good workaround for generics not currently supporting
> conditional conformance to a protocol. As stated in the Generics Manifesto
> something like this would be nice:
> >
> >   extension Array: Equatable where Element: Equatable {
> > static func ==(lhs: Array, rhs: Array) -> Bool { ... }
> > }
> >
> > But I would currently write a wrapper, something like:
> >
> > struct ArrayE {
> > var elements: [T]
> > }
> > extension ArrayE: Equatable {
> > static func ==(lhs: ArrayE, rhs: ArrayE) -> Bool { ...  }
> > }
> >
> > This can get unwieldy when there are a lot of conditional protocol
> extensions required, i.e. wrappers round wrappers.
> >
> > Is there a better way?
> >
> > Thanks for any tips,
> >
> >   -- Howard.
> > ___
> > swift-users mailing list
> > swift-users@swift.org
> > https://lists.swift.org/mailman/listinfo/swift-users
>
> Can you make Array conform to Equatable for any T and then in the ==
> function, if T conforms to Equatable loop the Arrays to check if they're
> equal, and if it doesn't conform just return false?
>
> I mean, it's still "wrong", but at least you won't get any false positives.
>
> - Dave Sweeris
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Workaround for generics not currently supporting conditional conformance to a protocol

2016-11-15 Thread Howard Lovatt via swift-users
Hi All,

Does anyone have a good workaround for generics not currently supporting
conditional conformance to a protocol. As stated in the Generics Manifesto
something like this would be nice:

  extension Array: Equatable where Element: Equatable {
static func ==(lhs: Array, rhs: Array) -> Bool { ... }
}

But I would currently write a wrapper, something like:

struct ArrayE {
var elements: [T]
}
extension ArrayE: Equatable {
static func ==(lhs: ArrayE, rhs: ArrayE) -> Bool { ...  }
}

This can get unwieldy when there are a lot of conditional protocol
extensions required, i.e. wrappers round wrappers.

Is there a better way?

Thanks for any tips,

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


Re: [swift-users] Weak references in generic types

2016-09-01 Thread Howard Lovatt via swift-users
@Karl,

You say "In the second example, you’re creating WeakReference. P does
not conform to P or to AnyObject.", but P does conform to AnyObject.

I suspect it is a compiler limitation/ bug.

 -- Howard.

On Thursday, 1 September 2016, Karl <razie...@gmail.com> wrote:

>
> On 1 Sep 2016, at 03:23, Howard Lovatt via swift-users <
> swift-users@swift.org
> <javascript:_e(%7B%7D,'cvml','swift-users@swift.org');>> wrote:
>
> Playing around I found that if you make the protocol @objc instead of
> AnyObject then it works :). EG:
>
> struct WeakReference {
> weak var value: T?
> }
> @objc protocol P { // Note @objc, class or AnyObject does not work
> var i: Int { get }
> }
> class CP: P {
> var i: Int = 0
> }
> let weakPs: [WeakReference] = [WeakReference(value: cP)] // Note typed
> as `[WeakReference]`
> print("P: \(weakPs[0].value!.i)") // 0
>
> Not a 'pure' Swift solution :(, but OK in my case.
>
>   -- Howard.
>
> On 29 August 2016 at 16:21, Howard Lovatt <howard.lov...@gmail.com
> <javascript:_e(%7B%7D,'cvml','howard.lov...@gmail.com');>> wrote:
>
>> Hi,
>>
>> I am wanting to use weak references in generic data structures; in the
>> example below Array, but in general any generic type. I can almost get it
>> to work :(
>>
>> My experiments started off well; the following works:
>>
>> // Array of weak references OK
>> struct WeakReference {
>> weak var value: T?
>> }
>> class C {
>> var i: Int = 0
>> }
>> let c = C() // Strong reference to prevent collection
>> let weakCs = [WeakReference(value: c)] // OK
>> print("C: \(weakCs[0].value!.i)") // 0
>>
>>
>> I can add a protocol:
>>
>> // Array of weak references that implements a protocol OK
>> protocol P: AnyObject { // Note AnyObject
>> var i: Int { get }
>> }
>> class CP: P {
>> var i: Int = 0
>> }
>> let cP = CP() // Strong reference to prevent collection
>> let weakCPs = [WeakReference(value: cP)] // OK
>> print("CP: \(weakCPs[0].value!.i)") // 0
>>
>>
>> But when I want an array of weak references to the protocol I get an
>> error:
>>
>> // Array of weak references of a protocol not OK
>> let weakPs: [WeakReference] = [WeakReference(value: cP)] // Using 'P'
>> as a concrete type conforming to protocol 'AnyObject' is not supported
>> print("P: \(weakPs[0].value!.i)") // 0
>>
>>
>> Is there something I have missed?
>>
>> The error message, "Using 'P' as a concrete type conforming to protocol
>> 'AnyObject' is not supported", implies that it is a temporary limitation of
>> the compiler; is this going to be fixed? Should I lodge a bug report?
>>
>> Thanks in advance for any advice,
>>
>>   -- Howard.
>>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> <javascript:_e(%7B%7D,'cvml','swift-users@swift.org');>
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
> Your problem is protocol self-conformance. In the first example, you’re
> creating WeakReference. CP conforms to P and to AnyObject. In the
> second example, you’re creating WeakReference. P does not conform to P
> or to AnyObject.
>
> As for why @objc fixes it? … ¯\_(ツ)_/¯ all bets are off whenever @objc
> gets involved in anything.
>
> Karl
>


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


Re: [swift-users] Weak references in generic types

2016-08-31 Thread Howard Lovatt via swift-users
Playing around I found that if you make the protocol @objc instead of
AnyObject then it works :). EG:

struct WeakReference {
weak var value: T?
}
@objc protocol P { // Note @objc, class or AnyObject does not work
var i: Int { get }
}
class CP: P {
var i: Int = 0
}
let weakPs: [WeakReference] = [WeakReference(value: cP)] // Note typed
as `[WeakReference]`
print("P: \(weakPs[0].value!.i)") // 0

Not a 'pure' Swift solution :(, but OK in my case.

  -- Howard.

On 29 August 2016 at 16:21, Howard Lovatt  wrote:

> Hi,
>
> I am wanting to use weak references in generic data structures; in the
> example below Array, but in general any generic type. I can almost get it
> to work :(
>
> My experiments started off well; the following works:
>
> // Array of weak references OK
> struct WeakReference {
> weak var value: T?
> }
> class C {
> var i: Int = 0
> }
> let c = C() // Strong reference to prevent collection
> let weakCs = [WeakReference(value: c)] // OK
> print("C: \(weakCs[0].value!.i)") // 0
>
>
> I can add a protocol:
>
> // Array of weak references that implements a protocol OK
> protocol P: AnyObject { // Note AnyObject
> var i: Int { get }
> }
> class CP: P {
> var i: Int = 0
> }
> let cP = CP() // Strong reference to prevent collection
> let weakCPs = [WeakReference(value: cP)] // OK
> print("CP: \(weakCPs[0].value!.i)") // 0
>
>
> But when I want an array of weak references to the protocol I get an error:
>
> // Array of weak references of a protocol not OK
> let weakPs: [WeakReference] = [WeakReference(value: cP)] // Using 'P'
> as a concrete type conforming to protocol 'AnyObject' is not supported
> print("P: \(weakPs[0].value!.i)") // 0
>
>
> Is there something I have missed?
>
> The error message, "Using 'P' as a concrete type conforming to protocol
> 'AnyObject' is not supported", implies that it is a temporary limitation of
> the compiler; is this going to be fixed? Should I lodge a bug report?
>
> Thanks in advance for any advice,
>
>   -- Howard.
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Weak references in generic types

2016-08-29 Thread Howard Lovatt via swift-users
Hi,

I am wanting to use weak references in generic data structures; in the
example below Array, but in general any generic type. I can almost get it
to work :(

My experiments started off well; the following works:

// Array of weak references OK
struct WeakReference {
weak var value: T?
}
class C {
var i: Int = 0
}
let c = C() // Strong reference to prevent collection
let weakCs = [WeakReference(value: c)] // OK
print("C: \(weakCs[0].value!.i)") // 0


I can add a protocol:

// Array of weak references that implements a protocol OK
protocol P: AnyObject { // Note AnyObject
var i: Int { get }
}
class CP: P {
var i: Int = 0
}
let cP = CP() // Strong reference to prevent collection
let weakCPs = [WeakReference(value: cP)] // OK
print("CP: \(weakCPs[0].value!.i)") // 0


But when I want an array of weak references to the protocol I get an error:

// Array of weak references of a protocol not OK
let weakPs: [WeakReference] = [WeakReference(value: cP)] // Using 'P' as
a concrete type conforming to protocol 'AnyObject' is not supported
print("P: \(weakPs[0].value!.i)") // 0


Is there something I have missed?

The error message, "Using 'P' as a concrete type conforming to protocol
'AnyObject' is not supported", implies that it is a temporary limitation of
the compiler; is this going to be fixed? Should I lodge a bug report?

Thanks in advance for any advice,

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


Re: [swift-users] Object size on heap

2016-03-23 Thread Howard Lovatt via swift-users
Thanks, you are correct. Very helpful.

  -- Howard.

On 24 March 2016 at 11:20, Kate Stone <k8st...@apple.com> wrote:

> You’re almost certainly seeing side effects of not keeping the instance of
> TestClass alive long enough for the unsafe pointer to still refer to an
> allocated malloc block.  A quick REPL session illustrates this fact:
>
>   1> class TestClass {
>   2. let a = 0
>   3. let b: Int? = nil
>   4. }
>   5> import Foundation
>   6> malloc_size(unsafeAddressOf(TestClass()))
> $R0: Int = 0
>   7> let x = TestClass()
> x: TestClass = {
>   a = 0
>   b = nil
> }
>   8> malloc_size(unsafeAddressOf(x))
> $R1: Int = 48
>
> On line 6 the result of the TestClass() expression is being used only to
> call unsafeAddressOf, and then it’s being freed before the call to
> malloc_size.  On line 8 the variable x is retaining the instance so the
> malloc’ed region can be measured.
>
> Of course all of this relies on the implementation assumption that
> allocated objects go on malloc’s heap and is subject to implementation
> details about object layout.  So while this may be instructive now it’s
> certainly no guarantee of how things will work in the future.
>
> Kate Stone k8st...@apple.com
>  Xcode Low Level Tools
>
> On Mar 23, 2016, at 5:13 PM, Howard Lovatt <howard.lov...@gmail.com>
> wrote:
>
> @Kate,
>
> I don't seem to be able to get `malloc_...` to work. EG:
>
> class TestClass {
> let a = 0
> let b: Int? = nil
> }
> @_silgen_name("swift_class_getInstanceExtents") func
> swift_class_getInstanceExtents(theClass: AnyClass) -> (negative: UInt,
> positive: UInt)
> print("swift_class_getInstanceExtents =
> \(swift_class_getInstanceExtents(TestClass))")
> let requiredSize = malloc_size(unsafeAddressOf(TestClass()))
> print("malloc_size = \(requiredSize)")
> print("malloc_good_size = \(malloc_good_size(requiredSize))")
>
>
> Prints:
>
> swift_class_getInstanceExtents = (0, 33)
> malloc_size = 0
> malloc_good_size = 16
>
>
> The `swift_class_getInstanceExtents` seems correct to me: 16 bytes for
> class overhead + 16 bytes for `a` and `b` + 1 byte because `b` is an
> optional = 33 bytes.
>
> Not sure what `malloc_...` is giving?
>
>   -- Howard.
>
> On 24 March 2016 at 10:39, Kate Stone <k8st...@apple.com> wrote:
>
>> I definitely concur that tools like Instruments are the best way to
>> understand the impact of decisions on memory across the board.  For
>> fine-grained inquiries about memory use you can also rely on malloc family
>> functions to make inquiries:
>>
>> let required_size = malloc_size(unsafeAddressOf(*object_reference*))
>> let actual_size = malloc_good_size(required_size)
>>
>>
>> Kate Stone k8st...@apple.com
>>  Xcode Low Level Tools
>>
>> On Mar 23, 2016, at 3:59 PM, Howard Lovatt via swift-users <
>> swift-users@swift.org> wrote:
>>
>> Thanks, I will give that a try
>>
>>   -- Howard.
>>
>> On 24 March 2016 at 03:17, Jens Alfke <j...@mooseyard.com> wrote:
>>
>>>
>>> On Mar 22, 2016, at 11:04 PM, Howard Lovatt via swift-users <
>>> swift-users@swift.org> wrote:
>>>
>>> I am writing custom collection classes and trying to assess which one is
>>> better, both in terms of performance and memory usage. Won't be used in
>>> 'real' code, just to guide development.
>>>
>>>
>>> You might consider using heap profiling tools too, like (on Mac OS) the
>>> Instruments app or the `heap` command-line tool. If you use these while
>>> running a benchmark app using your API, it can show you how much total heap
>>> space gets used.
>>>
>>> Actual heap usage can differ from the raw “sizeof” a data type, since
>>> allocators will often round up block sizes or return a somewhat larger
>>> block than necessary. Heap fragmentation can also increase memory usage
>>> beyond what you’d expect, and different allocation patterns can affect
>>> fragmentation.
>>>
>>> —Jens
>>>
>>
>> ___
>> 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] Object size on heap

2016-03-23 Thread Howard Lovatt via swift-users
@Kate,

I don't seem to be able to get `malloc_...` to work. EG:

class TestClass {
let a = 0
let b: Int? = nil
}
@_silgen_name("swift_class_getInstanceExtents") func
swift_class_getInstanceExtents(theClass: AnyClass) -> (negative: UInt,
positive: UInt)
print("swift_class_getInstanceExtents =
\(swift_class_getInstanceExtents(TestClass))")
let requiredSize = malloc_size(unsafeAddressOf(TestClass()))
print("malloc_size = \(requiredSize)")
print("malloc_good_size = \(malloc_good_size(requiredSize))")


Prints:

swift_class_getInstanceExtents = (0, 33)
malloc_size = 0
malloc_good_size = 16


The `swift_class_getInstanceExtents` seems correct to me: 16 bytes for
class overhead + 16 bytes for `a` and `b` + 1 byte because `b` is an
optional = 33 bytes.

Not sure what `malloc_...` is giving?

  -- Howard.

On 24 March 2016 at 10:39, Kate Stone <k8st...@apple.com> wrote:

> I definitely concur that tools like Instruments are the best way to
> understand the impact of decisions on memory across the board.  For
> fine-grained inquiries about memory use you can also rely on malloc family
> functions to make inquiries:
>
> let required_size = malloc_size(unsafeAddressOf(*object_reference*))
> let actual_size = malloc_good_size(required_size)
>
>
> Kate Stone k8st...@apple.com
>  Xcode Low Level Tools
>
> On Mar 23, 2016, at 3:59 PM, Howard Lovatt via swift-users <
> swift-users@swift.org> wrote:
>
> Thanks, I will give that a try
>
>   -- Howard.
>
> On 24 March 2016 at 03:17, Jens Alfke <j...@mooseyard.com> wrote:
>
>>
>> On Mar 22, 2016, at 11:04 PM, Howard Lovatt via swift-users <
>> swift-users@swift.org> wrote:
>>
>> I am writing custom collection classes and trying to assess which one is
>> better, both in terms of performance and memory usage. Won't be used in
>> 'real' code, just to guide development.
>>
>>
>> You might consider using heap profiling tools too, like (on Mac OS) the
>> Instruments app or the `heap` command-line tool. If you use these while
>> running a benchmark app using your API, it can show you how much total heap
>> space gets used.
>>
>> Actual heap usage can differ from the raw “sizeof” a data type, since
>> allocators will often round up block sizes or return a somewhat larger
>> block than necessary. Heap fragmentation can also increase memory usage
>> beyond what you’d expect, and different allocation patterns can affect
>> fragmentation.
>>
>> —Jens
>>
>
> ___
> 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] Strange type error

2016-03-20 Thread Howard Lovatt via swift-users
HI,

Does anyone know what is happening here:

protocol Subscriptable {

associatedtype Element

associatedtype Index

var firstIndex: Index { get }

var lastIndex: Index { get }

subscript(index: Index) -> Element { get set }

}


struct AllSubscriptable: Subscriptable {

typealias Element = E

typealias Index = I

let firstIndexee: () -> I

let lastIndexee: () -> I

let subscriptee: (index: I) -> E

let setSubscriptee: (index: I, element: E) -> Void

var firstIndex: I { return firstIndexee() }

var lastIndex: I { return lastIndexee() }

subscript(index: I) -> E {

get { return subscriptee(index: index) }

set { setSubscriptee(index: index, element: newValue) }

}

}


extension Array {

var asScriptable: AllSubscriptable {

return AllSubscriptable(

firstIndexee: { return self.startIndex }, // Error: Cannot
convert `() -> Int` to expected `() -> _`

lastIndexee: { return self.endIndex },

subscriptee: { return self[$0] },

setSubscriptee: { self[$0] = $1 }

)

}

}


The error, "Cannot convert `() -> Int` to expected `() -> _`", on the
`firstIndexee` closure is very strange since the types are correct and the
same as `lastIndexee` which does not have an error.

Also if the set subscript in Subscriptable and then all the other set
support in AnySubscriptabe and in the extension is removed, then no error.

Any clues to why?

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


Re: [swift-users] Recommendation for thread-safe dictionary

2015-12-10 Thread Howard Lovatt via swift-users
I would do something like:

import Foundation

class Task { // Must be a class to prevent Swift copy semantics
eliminating the result

private static let queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_HIGH, 0)

private let group = dispatch_group_create()

private var _result: String?

init(name: String) {

dispatch_group_async(group, Task.queue) {

self._result = name // The asynchronous task!

}

}

var result: String { // Provide safe access to result

dispatch_group_wait(group, DISPATCH_TIME_FOREVER) // Block
until task finished

return _result!

}

}


var tasks = [String : Task]()

let names = ["One", "Two"]

names.forEach {

tasks[$0] = Task(name: $0)

}

tasks.map { (_, task) in // Prints [One, Two] in playground

task.result

}

On 11 December 2015 at 07:02, Dmitri Gribenko via swift-users <
swift-users@swift.org> wrote:

> On Thu, Dec 10, 2015 at 11:20 AM, Jens Alfke  wrote:
> > All we’re saying is that a class like this isn’t commonly useful enough
> to go into a library.
>
> And too easy to misuse if provided.
>
> Dmitri
>
> --
> main(i,j){for(i=2;;i++){for(j=2;j (j){printf("%d\n",i);}}} /*Dmitri Gribenko */
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>



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