Re: [swift-users] SwiftPM: import ncurses -> conflicting types

2017-01-02 Thread Karl via swift-users
It’s even easier than that…

import Darwin.ncurses ;)

- Karl

> On 29 Dec 2016, at 06:23, Ankit Aggarwal via swift-users 
>  wrote:
> 
> ncurses is already present in the macOS sdk, so you don't need to install it 
> via brew.
> 
> In CNCurses package, create a file called "shim.h":
> $ cat shim.h
> #include "ncurses.h"
> 
> and change the modulemap to this: 
> $ cat module.modulemap
> module CNCurses [system] {
>  header "shim.h"
>  link "ncurses"
>  export *
> }
> 
>> On 29-Dec-2016, at 1:25 AM, Bouke Haarsma via swift-users 
>>  wrote:
>> 
>> Hi all,
>> 
>> I'm trying to build something with ncurses. There's this outdated tutorial: 
>> http://dev.iachieved.it/iachievedit/ncurses-with-swift-on-linux/. In order 
>> to build, a system module map was provided here: 
>> https://github.com/iachievedit/CNCURSES. This assumes 
>> `/usr/include/ncurses.h`, which is not available on MacOS 10.12. So I've 
>> installed ncurses through homebrew and updated the modulemap: 
>> https://github.com/Bouke/CNCurses. Sadly though, it doesn't work and I can't 
>> figure out how to get it working.
>> 
>>> brew install homebrew/dupes/ncurses
>> 
>> Module map:
>> 
>>> module CNCurses [system] {
>>>   header "/usr/local/Cellar/ncurses/6.0_2/include/ncurses.h"
>>>   link "ncurses"
>>>   export *
>>> }
>> 
>> I'm building with the following command, the flags taken from the package 
>> provided ncurses.pc:
>> 
>>> swift build \
>>> -Xcc -D_DARWIN_C_SOURCE \
>>> -Xcc -I/usr/local/Cellar/ncurses/6.0_2/include \
>>> -Xcc -I/usr/local/Cellar/ncurses/6.0_2/include/ncursesw \
>>> -Xlinker -L/usr/local/Cellar/ncurses/6.0_2/lib
>> 
>> This produces the following error message (shortened):
>> 
>>> Compile Swift Module 'TermDraw' (1 sources)
>>> :1:9: note: in file included from :1:
>>> #import "/usr/local/Cellar/ncurses/6.0_2/include/ncurses.h"
>>>   ^
>>> /usr/local/Cellar/ncurses/6.0_2/include/ncurses.h:60:10: error: 
>>> 'ncursesw/ncurses_dll.h' file not found with  include; use "quotes" 
>>> instead
>>> #include 
>>>^
>>> :1:9: note: in file included from :1:
>>> #import "/usr/local/Cellar/ncurses/6.0_2/include/ncurses.h"
>>>   ^
>>> /usr/local/Cellar/ncurses/6.0_2/include/ncurses.h:653:45: error: 
>>> conflicting types for 'keyname'
>>> extern NCURSES_EXPORT(NCURSES_CONST char *) keyname (int);  /* 
>>> implemented */
>>>   ^
>>> /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/curses.h:598:45:
>>>  note: previous declaration is here
>>> extern NCURSES_EXPORT(NCURSES_CONST char *) keyname (int);  /* 
>>> implemented */
>>>   ^
>>> :1:9: note: in file included from :1:
>>> #import "/usr/local/Cellar/ncurses/6.0_2/include/ncurses.h"
>>>   ^
>> 
>> (and goes on for quite a few other conflicting types)
>> 
>> Any help on getting this to build is greatly appreciated. Example code can 
>> be found here: https://github.com/Bouke/TermDraw
>> 
>> ---
>> Thanks,
>> Bouke
>> 
>> 
>> ___
>> 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] Extending Arrays of specific type, and specialization

2016-11-25 Thread Karl via swift-users

> On 23 Nov 2016, at 01:50, Hooman Mehr via swift-users  
> wrote:
> 
> For example, this reduces the six variants of sum to two:
> 
> public protocol ContiguousBufferedArray: RandomAccessCollection {
> 
> func withUnsafeBufferPointer(_ body: 
> (UnsafeBufferPointer) throws -> R) rethrows -> R
> }
> 
> extension Array: ContiguousBufferedArray {}
> extension ContiguousArray: ContiguousBufferedArray {}
> extension ArraySlice: ContiguousBufferedArray {}
> 
> func sum(_ array: A) -> Double where A: ContiguousBufferedArray, 
> A.Iterator.Element == Double {
> var result = Double()
> array.withUnsafeBufferPointer { vDSP_sveD($0.baseAddress!, 1, , 
> numericCast(array.count)) }
> return result
> }
> 
> func sum(_ array: A) -> Float where A: ContiguousBufferedArray, 
> A.Iterator.Element == Float {
> var result = Float()
> array.withUnsafeBufferPointer { vDSP_sve($0.baseAddress!, 1, , 
> numericCast(array.count)) }
> return result
> }
> 
> I have to think a bit more to see what common API we can extract from array 
> that can be generally useful. I will put up a pic on evolution once I get a 
> clearer idea.


DaveA mentioned at the start of the month that they were looking at ways to 
allow better contiguous memory optimisations (including vectorisation).

> If you think about what it means to build APIs for contiguous memory
> into abstractions like Sequence or Collection, at least without
> penalizing the lowest-level code, it means exposing UnsafeBufferPointers
> as a first-class part of the protocols, which is really
> unappealing... unless you consider that *borrowed* UnsafeBufferPointers
> can be made safe.

https://www.mail-archive.com/swift-evolution@swift.org/msg18395.html 


- Karl

> 
>> On Nov 22, 2016, at 4:46 PM, Rick Mann > > wrote:
>> 
>> That sounds interesting. Would you mind making that pitch on 
>> swift-evolution? I just barely understood what you said :/
>> 
>>> On Nov 22, 2016, at 07:46 , Hooman Mehr >> > wrote:
>>> 
>>> It is good to know that 
>>> 
>>> extension Array where Element == Double { }
>>> 
>>> will work pretty soon with Swift 3.1.
>>> 
>>> Back to reduce(0,+):
>>> 
>>> If we get specialized instance for a reduce(0,+), so that it is known that 
>>> “+” is a (Double, Double)->Double function, LLVM’s auto-vectorization 
>>> should be able to optimize it for the CPU’s vector unit. In theory, it 
>>> should be possible to add additional optimizers to LLVM layer to use other 
>>> hardware or numeric libraries for that purpose, but I don’t think it would 
>>> be a Swift-specific thing.
>>> 
>>> Swift’s generics still has a long way to go. Since they are aiming for ABI 
>>> stability by Swift 4.0, and there isn’t much time left, I don’t think many 
>>> of the bigger generics improvements fit with the current Swift evolution 
>>> discussions, although they could have huge impact on standard library 
>>> (hence the ABI stability). 
>>> 
>>> One thing that might be worth discussing on Swift evolution and can 
>>> potentially make it to standard library and Swift 4.0 is adding a common 
>>> protocol for array-like types that have (or can have) contiguous buffers so 
>>> that manually vectorizing operations on their elements becomes easier and 
>>> cleaner.
>>> 
>>> At the moment, we can manually define a protocol that extends 
>>> RandomAccessCollection and provides `withUnsafeBufferPointer` and then 
>>> declare the conformance of all of the standard library array variants to it 
>>> so that we can provide a single generic sum global function for summing all 
>>> of them using vDSP. This protocol may be worth adding to the standard 
>>> library.
>>> 
 On Nov 21, 2016, at 7:05 PM, Rick Mann > wrote:
 
 Thanks, Hooman. Is it worth posting on swift-evolution the question about 
 specializing something like reduce(0, +) (it's complicated because it 
 would mean specializing reduce() based on both the type and the closure 
 passed, and that seems like something that would be difficult to specify 
 concisely in the syntax).
 
> On Nov 21, 2016, at 18:29 , Hooman Mehr  > wrote:
> 
> This is not possible in Swift 3.0. Swift 4.0 will improve things with 
> conditional conformances.
> 
> For now, the best solution is using global functions instead of extending 
> types or protocols.
> 
> For example you can do this now:
> 
> extension Array where Element: FloatingPoint {
> 
>  func sum() -> Element {
>  guard count > 0 else { return 0 }
>  switch self[0] {
>  case is Double:
>  var result = Double()
>  vDSP_sveD(unsafeBitCast(self, to: Array.self), 

Re: [swift-users] Problem with mutable views and COW

2016-11-18 Thread Karl via swift-users

> On 18 Nov 2016, at 20:18, John McCall  wrote:
> 
>> 
>> On Nov 18, 2016, at 7:40 AM, Karl > > wrote:
>> 
>> 
>>> On 18 Nov 2016, at 13:05, Adrian Zubarev via swift-users 
>>> > wrote:
>>> 
>>> Hi there,
>>> 
>>> I just can’t get my head around mutable views and COW.
>>> 
>>> Here is a small example:
>>> 
>>> final class Storage {
>>>  
>>> var keys: [String] = []
>>> var values: [Int] = []
>>> }
>>> 
>>> public struct Document {
>>>  
>>> var _storageReference: Storage
>>>  
>>> public init() {
>>>  
>>> self._storageReference = Storage()
>>> }
>>>  
>>> public init(_ values: DocumentValues) {
>>>  
>>> self._storageReference = values._storageReference
>>> }
>>>  
>>> public var values: DocumentValues {
>>>  
>>> get { return DocumentValues(self) }
>>>  
>>> set { self = Document(newValue) }
>>> }
>>> }
>>> 
>>> public struct DocumentValues : MutableCollection {
>>>  
>>> unowned var _storageReference: Storage
>>>  
>>> init(_ document: Document) {
>>>  
>>> self._storageReference = document._storageReference
>>> }
>>>  
>>> public var startIndex: Int {
>>>  
>>> return self._storageReference.keys.startIndex
>>> }
>>>  
>>> public var endIndex: Int {
>>>  
>>> return self._storageReference.keys.endIndex
>>> }
>>>  
>>> public func index(after i: Int) -> Int {
>>>  
>>> return self._storageReference.keys.index(after: i)
>>> }
>>>  
>>> public subscript(position: Int) -> Int {
>>>  
>>> get { return _storageReference.values[position] }
>>>  
>>> set { self._storageReference.values[position] = newValue } // That 
>>> will break COW
>>> }
>>> }
>>> First of all the _storageReference property is unowned because I wanted to 
>>> check the following:
>>> 
>>> var document = Document()
>>> 
>>> print(CFGetRetainCount(document._storageReference)) //=> 2
>>> print(isKnownUniquelyReferenced(_storageReference)) // true
>>> 
>>> var values = document.values
>>> 
>>> print(CFGetRetainCount(values._storageReference)) //=> 2
>>> print(isKnownUniquelyReferenced(_storageReference)) // false
>>> Why is the second check false, even if the property is marked as unowned 
>>> for the view?
>>> 
>>> Next up, I don’t have an idea how to correctly COW optimize this view. 
>>> Assume the following scenario:
>>> 
>>> Scenario A:
>>> 
>>> var document = Document()
>>> 
>>> // just assume we already added some values and can mutate safely on a 
>>> given index
>>> // mutation in place
>>> document.values[0] = 10  
>>> VS:
>>> 
>>> Scenario B:
>>> 
>>> var document = Document()
>>> 
>>> let copy = document
>>> 
>>> // just assume we already added some values and can mutate safely on a 
>>> given index
>>> // mutation in place
>>> document.values[0] = 10 // <--- this should only mutate `document` but not 
>>> `copy`
>>> We could change the subscript setter on the mutable view like this:
>>> 
>>> set {
>>>  
>>> if !isKnownUniquelyReferenced(_storageReference) {
>>>  
>>> self._storageReference = ... // clone
>>> }
>>> self._storageReference.values[position] = newValue
>>> }
>>> There is only one problem here. We’d end up cloning the storage every time, 
>>> because as shown in the very first example, even with unowned the function 
>>> isKnownUniquelyReferenced will return false for scenario A.
>>> 
>>> Any suggestions? 
>>> 
>>> PS: In general I also wouldn’t want to use unowned because the view should 
>>> be able to outlive it’s parent.
>>> 
>>> 
>>> 
>>> 
>>> -- 
>>> Adrian Zubarev
>>> Sent with Airmail
>>> 
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org 
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> 
>> 
>> 
>> This is kind of an invalid/unsafe design IMO; DocumentValues may escape the 
>> scope of the Document and the underlying storage may be deallocated.
>> 
>> Instead, I’d recommend a function:
>> 
>> func withDocumentValues(_ invoke: (inout DocumentValues)->T) -> T {
>>  var view = DocumentValues(self)
>> defer { _fixLifetime(view) }
>> return invoke()
>> }
>> 
>> (unfortunately, this isn’t completely safe because somebody could still copy 
>> the DocumentValues from their closure, the same way you can copy the pointer 
>> from String’s withCString, but that’s a limitation of Swift right now)
>> 
>> CC: John McCall, because I read his suggestion in the thread about 
>> contiguous memory/borrowing that we could have a generalised @noescape. In 
>> this example, you would want the DocumentValues 

Re: [swift-users] Problem with mutable views and COW

2016-11-18 Thread Karl via swift-users

> On 18 Nov 2016, at 13:05, Adrian Zubarev via swift-users 
>  wrote:
> 
> Hi there,
> 
> I just can’t get my head around mutable views and COW.
> 
> Here is a small example:
> 
> final class Storage {
>  
> var keys: [String] = []
> var values: [Int] = []
> }
> 
> public struct Document {
>  
> var _storageReference: Storage
>  
> public init() {
>  
> self._storageReference = Storage()
> }
>  
> public init(_ values: DocumentValues) {
>  
> self._storageReference = values._storageReference
> }
>  
> public var values: DocumentValues {
>  
> get { return DocumentValues(self) }
>  
> set { self = Document(newValue) }
> }
> }
> 
> public struct DocumentValues : MutableCollection {
>  
> unowned var _storageReference: Storage
>  
> init(_ document: Document) {
>  
> self._storageReference = document._storageReference
> }
>  
> public var startIndex: Int {
>  
> return self._storageReference.keys.startIndex
> }
>  
> public var endIndex: Int {
>  
> return self._storageReference.keys.endIndex
> }
>  
> public func index(after i: Int) -> Int {
>  
> return self._storageReference.keys.index(after: i)
> }
>  
> public subscript(position: Int) -> Int {
>  
> get { return _storageReference.values[position] }
>  
> set { self._storageReference.values[position] = newValue } // That 
> will break COW
> }
> }
> First of all the _storageReference property is unowned because I wanted to 
> check the following:
> 
> var document = Document()
> 
> print(CFGetRetainCount(document._storageReference)) //=> 2
> print(isKnownUniquelyReferenced(_storageReference)) // true
> 
> var values = document.values
> 
> print(CFGetRetainCount(values._storageReference)) //=> 2
> print(isKnownUniquelyReferenced(_storageReference)) // false
> Why is the second check false, even if the property is marked as unowned for 
> the view?
> 
> Next up, I don’t have an idea how to correctly COW optimize this view. Assume 
> the following scenario:
> 
> Scenario A:
> 
> var document = Document()
> 
> // just assume we already added some values and can mutate safely on a given 
> index
> // mutation in place
> document.values[0] = 10  
> VS:
> 
> Scenario B:
> 
> var document = Document()
> 
> let copy = document
> 
> // just assume we already added some values and can mutate safely on a given 
> index
> // mutation in place
> document.values[0] = 10 // <--- this should only mutate `document` but not 
> `copy`
> We could change the subscript setter on the mutable view like this:
> 
> set {
>  
> if !isKnownUniquelyReferenced(_storageReference) {
>  
> self._storageReference = ... // clone
> }
> self._storageReference.values[position] = newValue
> }
> There is only one problem here. We’d end up cloning the storage every time, 
> because as shown in the very first example, even with unowned the function 
> isKnownUniquelyReferenced will return false for scenario A.
> 
> Any suggestions? 
> 
> PS: In general I also wouldn’t want to use unowned because the view should be 
> able to outlive it’s parent.
> 
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> ___
> swift-users mailing list
> swift-users@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-users 
> 


This is kind of an invalid/unsafe design IMO; DocumentValues may escape the 
scope of the Document and the underlying storage may be deallocated.

Instead, I’d recommend a function:

func withDocumentValues(_ invoke: (inout DocumentValues)->T) -> T {
var view = DocumentValues(self)
defer { _fixLifetime(view) }
return invoke()
}

(unfortunately, this isn’t completely safe because somebody could still copy 
the DocumentValues from their closure, the same way you can copy the pointer 
from String’s withCString, but that’s a limitation of Swift right now)

CC: John McCall, because I read his suggestion in the thread about contiguous 
memory/borrowing that we could have a generalised @noescape. In this example, 
you would want the DocumentValues parameter in the closure to be @noescape.

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


Re: [swift-users] dispatch concurrent map: is this right?

2016-10-31 Thread Karl via swift-users

> On 31 Oct 2016, at 05:15, Dave Abrahams  wrote:
> 
> 
> on Sun Oct 30 2016, Karl  > wrote:
> 
>>> On 30 Oct 2016, at 19:23, Dave Abrahams via swift-users 
>>>  wrote:
>>> 
>>> 
>>> on Sun Oct 30 2016, Karl  wrote:
>>> 
>> 
> On 30 Oct 2016, at 09:15, Karl  wrote:
> 
> I had the need for a concurrent map recently. I had a part of a
> program which needed to read chunks of data and concurrently process
> them and assemble the results in an array. This isn’t necessarily as
> obvious as it sounds, because of arrays being value types. I came up
> with the following snippet which I’d like to check for correctness;
> it could also be helpful to others.
> 
> Perhaps this is something Dispatch should provide out-of-the-box?
> 
> - Karl
 
 Ah one second, I was refactoring this and forgot to test it. Here’s the 
 actual code:
>>> 
>>> A map presumably requires an input 
>> 
>> DispatchQueue.concurrentMap maps a Range -> T, but since the
>> range is always 0..> be written quite naturally as an extension on Range and build
>> everything on top of it.
> 
> Sorry, I wrote “a map presumably requires an input” before I realized
> what you were doing.  I should have deleted that.
> 
>>> 
 extension DispatchQueue {
 
 static func concurrentMap(iterations: Int, execute block: (Int) -> T) 
 -> [T] {
 
   let __result = UnsafeMutableRawBufferPointer.allocate(count: iterations 
 * MemoryLayout.stride)
   defer { __result.deallocate() }
   let _result  = __result.baseAddress?.assumingMemoryBound(to: T.self)
>>> 
>>> You never bound the memory to T, so this will be undefined behavior.  
>>> 
   let result   = UnsafeMutableBufferPointer(start: _result, count: 
 iterations)
   concurrentPerform(iterations: iterations) { idx in
 result[idx] = block(idx)
>>> 
>>> You also never initialized the Ts in that memory region, so assigning
>>> into them will also be undefined behavior.
>>> 
   }
   return Array(result)
 }
 }
 
 extension Array {
 func concurrentMap(execute block: (Element)->T) -> [T] {
   return DispatchQueue.concurrentMap(iterations: count) { block(self[$0]) }
 }
 }
 
 Unfortunately I don’t think there’s a way to get an array to take over a +1
 UnsafeMutableBufferPointer without copying.
>>> 
>>> The only correct way to do this without creating intermediate storage is
>>> to have a way to initialize your result elements, e.g.:
>>> 
>>> import Dispatch
>>> 
>>> protocol DefaultInitializable {
>>>   init()
>>> }
>>> 
>>> extension RandomAccessCollection {
>>>   func concurrentMap(_ transform: (Iterator.Element)->T) -> [T]
>>>   where T : DefaultInitializable {
>>> var result = Array(
>>>   repeating: T(), count: numericCast(self.count))
>>> 
>>> DispatchQueue.concurrentPerform(iterations: result.count) {
>>>   offset in 
>>>   result[offset] = transform(
>>> self[index(startIndex, offsetBy: numericCast(offset))])
>>> }
>>> return result
>>>   }
>>> }
>>> 
>>> extension Int : DefaultInitializable {  }
>>> 
>>> print((3..<20).concurrentMap { $0 * 2 })
>>> 
>> 
>> I had a go at doing that before, using Optional and unwrapping at
>> the end — but it occurred to me that it would be very inefficient for
>> things like Optional, and introduces more allocations.
> 
> Yeah, optional is not really a good choice for that application.
> 
>>> If you don't want the DefaultInitializable requirement (or some other
>>> way to prepare initialized elements), you'll need to manage memory
>>> yourself:
>>> 
>>> extension RandomAccessCollection {
>>>   func concurrentMap(_ transform: (Iterator.Element)->T) -> [T] {
>>> let n = numericCast(self.count) as Int
>>> let p = UnsafeMutablePointer.allocate(capacity: n)
>>> defer { p.deallocate(capacity: n) }
>>> 
>>> DispatchQueue.concurrentPerform(iterations: n) {
>>>   offset in
>>>   (p + offset).initialize(
>>> to: transform(
>>>   self[index(startIndex, offsetBy: numericCast(offset))]))
>>> }
>>> 
>>> return Array(UnsafeMutableBufferPointer(start: p, count: n))
>>>   }
>>> }
>>> 
>>> This posting highlights a couple of weaknesses in the standard library
>>> for which I'd appreciate bug reports:
>>> 
>>> 1. No way to arbitrarily initialize an Array's storage.
>>> 2. UnsafeMutableBufferPointer doesn't have an allocating init
>>> 
>> Filed:
>> 
>> 1. https://bugs.swift.org/browse/SR-3087 
>> 
>> 2. https://bugs.swift.org/browse/SR-3088 
>> 
> 
> Thanks for these!
>> 
>> What is your opinion on the corelibs extending the standard library
>> types? 
>> Foundation does it to provide APIs from NSString, but it’s kind of a
>> 

Re: [swift-users] dispatch concurrent map: is this right?

2016-10-30 Thread Karl via swift-users

> On 30 Oct 2016, at 19:23, Dave Abrahams via swift-users 
>  wrote:
> 
> 
> on Sun Oct 30 2016, Karl  wrote:
> 
>>> On 30 Oct 2016, at 09:15, Karl  wrote:
>>> 
>>> I had the need for a concurrent map recently. I had a part of a
>>> program which needed to read chunks of data and concurrently process
>>> them and assemble the results in an array. This isn’t necessarily as
>>> obvious as it sounds, because of arrays being value types. I came up
>>> with the following snippet which I’d like to check for correctness;
>>> it could also be helpful to others.
>>> 
>>> Perhaps this is something Dispatch should provide out-of-the-box?
>>> 
>>> - Karl
>> 
>> Ah one second, I was refactoring this and forgot to test it. Here’s the 
>> actual code:
> 
> A map presumably requires an input 

DispatchQueue.concurrentMap maps a Range -> T, but since the range is 
always 0.. 
>> extension DispatchQueue {
>> 
>>  static func concurrentMap(iterations: Int, execute block: (Int) -> T) -> 
>> [T] {
>> 
>>let __result = UnsafeMutableRawBufferPointer.allocate(count: iterations * 
>> MemoryLayout.stride)
>>defer { __result.deallocate() }
>>let _result  = __result.baseAddress?.assumingMemoryBound(to: T.self)
> 
> You never bound the memory to T, so this will be undefined behavior.  
> 
>>let result   = UnsafeMutableBufferPointer(start: _result, count: 
>> iterations)
>>concurrentPerform(iterations: iterations) { idx in
>>  result[idx] = block(idx)
> 
> You also never initialized the Ts in that memory region, so assigning
> into them will also be undefined behavior.
> 
>>}
>>return Array(result)
>>  }
>> }
>> 
>> extension Array {
>>  func concurrentMap(execute block: (Element)->T) -> [T] {
>>return DispatchQueue.concurrentMap(iterations: count) { block(self[$0]) }
>>  }
>> }
>> 
>> Unfortunately I don’t think there’s a way to get an array to take over a +1
>> UnsafeMutableBufferPointer without copying.
> 
> The only correct way to do this without creating intermediate storage is
> to have a way to initialize your result elements, e.g.:
> 
>  import Dispatch
> 
>  protocol DefaultInitializable {
>init()
>  }
> 
>  extension RandomAccessCollection {
>func concurrentMap(_ transform: (Iterator.Element)->T) -> [T]
>where T : DefaultInitializable {
>  var result = Array(
>repeating: T(), count: numericCast(self.count))
> 
>  DispatchQueue.concurrentPerform(iterations: result.count) {
>offset in 
>result[offset] = transform(
>  self[index(startIndex, offsetBy: numericCast(offset))])
>  }
>  return result
>}
>  }
> 
>  extension Int : DefaultInitializable {  }
> 
>  print((3..<20).concurrentMap { $0 * 2 })
> 

I had a go at doing that before, using Optional and unwrapping at the end — 
but it occurred to me that it would be very inefficient for things like 
Optional, and introduces more allocations.


> If you don't want the DefaultInitializable requirement (or some other
> way to prepare initialized elements), you'll need to manage memory
> yourself:
> 
>  extension RandomAccessCollection {
>func concurrentMap(_ transform: (Iterator.Element)->T) -> [T] {
>  let n = numericCast(self.count) as Int
>  let p = UnsafeMutablePointer.allocate(capacity: n)
>  defer { p.deallocate(capacity: n) }
> 
>  DispatchQueue.concurrentPerform(iterations: n) {
>offset in
>(p + offset).initialize(
>  to: transform(
>self[index(startIndex, offsetBy: numericCast(offset))]))
>  }
> 
>  return Array(UnsafeMutableBufferPointer(start: p, count: n))
>}
>  }
> 
> This posting highlights a couple of weaknesses in the standard library
> for which I'd appreciate bug reports:
> 
> 1. No way to arbitrarily initialize an Array's storage.
> 2. UnsafeMutableBufferPointer doesn't have an allocating init
> 
> Thanks!
> 
> -- 
> -Dave
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users


Filed:

1. https://bugs.swift.org/browse/SR-3087
2. https://bugs.swift.org/browse/SR-3088

What is your opinion on the corelibs extending the standard library types? 
Foundation does it to provide APIs from NSString, but it’s kind of a special 
case. Would it be reasonable for Dispatch (which is not _such_ a special case) 
to also extend types like Range and Collection?

I quite like the API as an extension on Range. I think it would be a nice 
addition to Dispatch (once we start allowing additive proposals):

extension Range where Bound : Strideable, Bound.Stride : SignedInteger {

  func concurrentMap(_ transform: (Bound) -> T) -> [T] {
let n= numericCast(count) as Int
let buffer = 

Re: [swift-users] dispatch concurrent map: is this right?

2016-10-30 Thread Karl via swift-users

> On 30 Oct 2016, at 09:15, Karl  wrote:
> 
> I had the need for a concurrent map recently. I had a part of a program which 
> needed to read chunks of data and concurrently process them and assemble the 
> results in an array. This isn’t necessarily as obvious as it sounds, because 
> of arrays being value types. I came up with the following snippet which I’d 
> like to check for correctness; it could also be helpful to others.
> 
> Perhaps this is something Dispatch should provide out-of-the-box?
> 
> - Karl

Ah one second, I was refactoring this and forgot to test it. Here’s the actual 
code:

extension DispatchQueue {

  static func concurrentMap(iterations: Int, execute block: (Int) -> T) -> 
[T] {

let __result = UnsafeMutableRawBufferPointer.allocate(count: iterations * 
MemoryLayout.stride)
defer { __result.deallocate() }
let _result  = __result.baseAddress?.assumingMemoryBound(to: T.self)
let result   = UnsafeMutableBufferPointer(start: _result, count: 
iterations)
concurrentPerform(iterations: iterations) { idx in
  result[idx] = block(idx)
}
return Array(result)
  }
}

extension Array {
  func concurrentMap(execute block: (Element)->T) -> [T] {
return DispatchQueue.concurrentMap(iterations: count) { block(self[$0]) }
  }
}


Unfortunately I don’t think there’s a way to get an array to take over a +1 
UnsafeMutableBufferPointer without copying.

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


[swift-users] dispatch concurrent map: is this right?

2016-10-30 Thread Karl via swift-users
I had the need for a concurrent map recently. I had a part of a program which 
needed to read chunks of data and concurrently process them and assemble the 
results in an array. This isn’t necessarily as obvious as it sounds, because of 
arrays being value types. I came up with the following snippet which I’d like 
to check for correctness; it could also be helpful to others.

Perhaps this is something Dispatch should provide out-of-the-box?

- Karl


extension DispatchQueue {

  static func concurrentMap(iterations: Int, execute block: (Int) -> T) -> 
[T] {
var result = Array()
result.reserveCapacity(iterations)

result.withUnsafeMutableBufferPointer { (results: inout 
UnsafeMutableBufferPointer) in
  concurrentPerform(iterations: iterations) { idx in
results[idx] = block(idx)
  }
}

return result
  }
}

extension Array {
  func concurrentMap(execute block: (Element)->T) -> [T] {
return DispatchQueue.concurrentMap(iterations: count) { block(self[$0]) }
  }
}___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Cross-Compiling to Linux from macOS

2016-09-21 Thread Karl via swift-users

> On 21 Sep 2016, at 19:14, Rafael Costa via swift-users 
>  wrote:
> 
> Hello fellow Swift users,
> 
> I’m encountering some problems and I wish to know if anyone here has ever 
> come across something similar.
> 
> In essence, I want to cross-compile a Swift Project on macOS to run it on 
> Linux. I’m using the following command to (try) to do so:
> 
> swift build -c release --build-path ./.build/linux -Xswiftc -static-stdlib 
> -Xswiftc -target -Xswiftc x86_64-unknown-linux-gnu 
> 
> The “target” parameter is passing to the “swiftc” program just fine. The 
> problem is that it is overwritten by a “target” parameter added automatically 
> by swift-build (that sets the target as the same arch/OS as the host machine)
> 
> How can I prevent that? Is it possible to cross-compile for Linux on macOS?
> 
> Thanks in advance,
> Rafael Costa
> raf...@rafaelcosta.me 
> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

For example, this is what we do in LLDB to cross-compile the REPL:

https://github.com/apple/swift-lldb/blob/587e781a6fab4db0338a6e71bbc7fc3475f9d43c/tools/repl/swift/CMakeLists.txt#L11___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Cross-Compiling to Linux from macOS

2016-09-21 Thread Karl via swift-users

> On 21 Sep 2016, at 19:14, Rafael Costa via swift-users 
>  wrote:
> 
> Hello fellow Swift users,
> 
> I’m encountering some problems and I wish to know if anyone here has ever 
> come across something similar.
> 
> In essence, I want to cross-compile a Swift Project on macOS to run it on 
> Linux. I’m using the following command to (try) to do so:
> 
> swift build -c release --build-path ./.build/linux -Xswiftc -static-stdlib 
> -Xswiftc -target -Xswiftc x86_64-unknown-linux-gnu 
> 
> The “target” parameter is passing to the “swiftc” program just fine. The 
> problem is that it is overwritten by a “target” parameter added automatically 
> by swift-build (that sets the target as the same arch/OS as the host machine)
> 
> How can I prevent that? Is it possible to cross-compile for Linux on macOS?
> 
> Thanks in advance,
> Rafael Costa
> raf...@rafaelcosta.me 
> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

It is possible, but I don’t know if swift-build supports it. We don’t really 
have much comprehensive support for cross-compiling right now.

To cross-compile, you need to set the target, sysroot and tools-directory (the 
latter only required if compiling an executable, not for swiftmodules). You 
might also need to set the resource-dir to the lib/swift folder where the 
target’s standard library is.___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Implicitly type conversion ?

2016-08-25 Thread Karl via swift-users

> On 19 Aug 2016, at 18:00, Tim Vermeulen via swift-users 
>  wrote:
> 
> Any idea why Swift supports implicit casting to AnyHashable, but not to, say, 
> AnySequence?
> 

It’s a hack until existential support gets better. Explicitly casting to 
AnyHashable clutters your dictionary literals.

There’s a fair amount of code in the compiler to support it, it’s probably just 
not worth the effort for other types (and since they were never anything else, 
nothing has regressed for them as it did for AnyHashable).
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Protocol with instance var that's set on construction, otherwise read-only

2016-08-09 Thread Karl via swift-users

> On 3 Aug 2016, at 02:01, Rick Mann via swift-users  
> wrote:
> 
> It complains if I make it a let because computed properties must be var. 
> Because it's a protocol, it can't be stored (even though it can be stored in 
> the conforming type).
> 
> If I make it { get }, I can't set it in the extensions init() method.
> 
> I guess I could make it private set (not sure of the syntax for that), but it 
> still doesn't have let semantics.

It sounds like you should put the calculation function in the protocol 
extension, the property in the protocol, and let conforming types decide how to 
store that property (and when to calculate it).___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Are typealiases within protocols supposed to be visible from conforming types?

2016-08-03 Thread Karl via swift-users
Straightforward question - Are typealiases within protocols supposed to be 
visible from conforming types?

For example:

> protocol MyProto {
>   
>   typealias ComplexFunctionType = (_ paramOne: (Int, Bool?), _ paramTwo: 
> (Bool, String?, String)) throws -> (Array, Float)?
> 
>   func doSomething(callback: ComplexFunctionType)
> }
> 
> struct Conformist : MyProto {
>   
>   // do I really have to write that whole thing out again?
>   // or copy-paste and sync changes for all conforming types?
> }

Currently they are not visible from the conforming type (so you would need to 
duplicate the definition of ComplexFunctionType), but I’m not sure if that's a 
bug or feature.

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


Re: [swift-users] Why can't structs inherit from other structs?

2016-08-02 Thread Karl via swift-users


> * Structs have statically-dispatched methods and properties; there's no 
> ability to override.
> 

I wonder if that is an inherent property of structs, or a side-effect from them 
having no inheritance. There is no way to define something else which also “is” 
a CGRect, so all structs are final, and final is what gives static dispatch.
If you access a struct via a protocol reference (PWT), you will get dynamic 
dispatch.

> In my case, I have a rect-like value type, but I'd rather it inherit from 
> CGRect, rather than contain a CGRect. That makes it much more natural to use.

I’m reading this to mean you want something which “is” a CGRect. If we allowed 
those kinds of relationships for structs, and when using the open base type:

- Methods would have to be dynamically dispatched unless declared final
- Instance size would not be known, requiring heap allocation and storing 
pointers when used as a member
- The sub-structs would lose information when bridged to their C equivalents. 
The CoreGraphics/UIKit framework code is not going to store and pass around 
your big CGRects

The problem you are facing is a library limitation. CoreGraphics and UIKit do 
not allow you to abstract the concept of a “rect”. You could suggest that they 
replace CGRect with an extendable abstraction (i.e. an open class or a 
protocol) to represent a rectangle. Those libraries follow this pattern in 
other areas - for example, UITextPosition and UITextRange are abstract classes 
and intended to be subclassed. However, replacing CGRect would break lots of 
existing code and possibly introduce performance regressions, and the benefits 
are not likely to be significant enough to warrant it.

Karl

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


Re: [swift-users] More questions about protocol/value programming

2016-08-01 Thread Karl via swift-users
A protocol can require that a certain initialiser exists, but it can’t provide 
a default implementation (you can add initialisers in a protocol extension 
IIRC, but then they must delegate to an actual, required initialiser).

A protocol is not the same thing as a subclass. Any type could conform to a 
protocol. In that case, your init method wouldn’t be valid - there may be other 
stored properties besides “uuid”; in fact, “uuid” may not be a stored property 
at all by that type. For example, I could write an extension for String or 
Array which makes them now conform to Element. The fact that “uuid” isn’t 
declared mutable but you are trying to set it, is a sign that there is not 
enough knowledge about the type to do this.

If you do have some common properties and want to encapsulate their logic, 
create a struct. For example, you might create an “XMLHeader” struct, and 
PartDefinition and PartInstance can contain it by composition. You would need 
to add forwarding accessors, but they can be added in an extension to avoid 
cluttering your code.

e.g.:

> // Could this even be a nested type inside XMLElement, perhaps? That would be 
> even cleaner. Maybe there could then be a “var header: Header?" computed 
> property on XMLElement?
> 
> struct XMLElementHeader {
>   let uuid : UUID
>   var name : String?
>   var desc : String?
> 
>   static func parse(_ xml: XMLElement) -> XMLElementHeader? {
>   // Validate xml
>   return XMLElementHeader(uuid: ..., name: .none, desc: .none)
>   }
> }
> 
> class PartInstance {
> 
>   var header : XMLElementHeader
> 
>   init(xml: XMLElement) {
>   guard let parsedHeader = XMLElementHeader.parse(xml) else { 
> fatalError() }
>   header = parsedHeader
>   }
> }
> 
> class PartDefinition {
>   
>   var header : XMLElementHeader
> 
>   init(xml: XMLElement) {
>   guard let parsedHeader = XMLElementHeader.parse(xml) else { 
> fatalError() }
>   header = parsedHeader
>   }
> }

Then, if you want to provide a nicer interface, do it with an extension:

> protocol Element {
>   var uuid : UUID{ get }
>   var name : String? { get, set }
> }
> 
> extension PartInstance : Element {
>   var uuid : UUID{ return header.uuid }
>   var name : String? { get { return header.name }
>set { header.name = newValue } 
> }   
> }

That’s how I would do it, anyway.

Karl


> On 1 Aug 2016, at 22:32, Rick Mann via swift-users  
> wrote:
> 
> In my schematic capture app, I had a class hierarchy that started with 
> Element. From that I derived PartDefinition and PartInstance. Element has an 
> immutable UUID, name, and description. Element knows how to encode itself as 
> XML by conforming to an XMLCoding protocol.
> 
> Now I'm trying to make Element into a Protocol, and make PartDefinition and 
> PartInstance into structs. But I can't quite figure out how to inherit the 
> XMLCoding implementation for Element. That is, Element can encode/decode its 
> UUID, name, and desc. It does the decode in a convenience init(xml:) method 
> that takes an XMLNode to parse.
> 
> So how to I add another init(xml:) method to one of my structs (like 
> PartDefinition), and have it call the init(xml:) method on Element? With 
> class inheritance, I was able to do this with a call to super. It's not clear 
> to me how to do this with Protocols.
> 
> It needs to be in init() because I want some of the instance variables to be 
> let and non-optional. Not actually sure how to do this.
> 
> protocol Element
> {
>var uuid:  UUID { get }
>var name:  String?  { get }
>var desc:  String?  { get }
> }
> 
> extension Element
> {
>init(xml inElement: XMLElement)
>{
>self.uuid = 
>}
> }
> 
> class
> PartInstance : Element
> {
>init()
>{
>self.uuid = UUID()
>}
> 
>init(xml inElement: XMLElement)
>{
>//  Use shared implementation in Element extension?
>}
> 
>let uuid: UUID
>var name: String?
>var desc: String?
> }
> 
> class
> PartDefinition : Element
> {
>etc...
> }
> 
> I may be missing some aspect of this entirely, but I'm having a hard time 
> seeing how to avoid lots of code duplication in this scenario. Appreciate 
> thoughts and advice…
> 
> -- 
> Rick Mann
> rm...@latencyzero.com
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Can't initialise using a UTF8 string from within 'withUnsafeBufferPointer' expression

2016-07-18 Thread Karl via swift-users

> On 18 Jul 2016, at 14:51, Martin R  wrote:
> 
> This is not an answer to your question, but note that you can pass a Swift 
> String to functions expecting an UnsafePointer (C String) parameter, 
> and the compiler will generate a temporary NUL-terminated UTF-8 
> representation for you:
> 
>  let io = DispatchIO(type: .stream, path: "/path/to/file", ...)
> 
> So you don't need a convenience initializer for _this_ purpose.

Oh, my…

Isn’t it kind of strange that we have such a hidden implicit conversion, yet we 
don’t have implicit widening conversions?

Also, as interesting as that may be, I’m also curious what to do in the general 
case for types without magic compiler optimisations.

Karl

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


[swift-users] Can't initialise using a UTF8 string from within 'withUnsafeBufferPointer' expression

2016-07-18 Thread Karl via swift-users
As I understand it, we are supposed to use withUnsafe{Mutable/Buffer}Pointer or 
withExtendedLifetime to guarantee that objects we take pointers of will exist 
and won’t be optimised out by the compiler.

However, this leads to a problem when trying to initialise something which 
expects a UTF8 string using only the standard library (not Foundation’s 
equivalent cStringUsingEncoding):

> extension DispatchIO {
> 
>   convenience init(type: DispatchIO.StreamType, path: String, oflag: 
> Int32, mode: mode_t, queue: DispatchQueue, cleanupHandler: (error: Int32) -> 
> Void) {
> 
>   let utf8Path = path.nulTerminatedUTF8
>   utf8Path.withUnsafeBufferPointer {
>   self.init(type: type, path: 
> UnsafePointer($0.baseAddress!), oflag: oflag, mode: mode, queue: queue, 
> cleanupHandler: cleanupHandler)
>   }
>   }
> }

ERROR: Initializer delegation ('self.init') cannot be nested in another 
expression

I don’t really understand why that isn’t allowed for a non-capturing closure, 
but if we accept that, how do I actually use those pointer/extended lifetime 
functions to initialise things?

Thanks

Karl

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


[swift-users] How do you use protocol types?

2016-07-13 Thread Karl via swift-users
So I’m trying to work generically to construct things based on their 
conformance to a protocol with an initialiser. I’m sure this worked before; 
I’ve done it before. Maybe there have been some changes in the language or 
something, because I’ve tried everywhich-way and this just isn’t flying:

==
protocol AProto {

associatedtype ElementType
func constructInstance(_: ElementType.Type) -> ElementType
}

protocol SimpleConstructableElement {
init()
}

extension Int : SimpleConstructableElement {}

class Factory : AProto {

typealias ElementType = SimpleConstructableElement

func constructInstance(_ t: SimpleConstructableElement.Type) -> 
SimpleConstructableElement {
return t.init()
}
}

Factory().constructInstance(Int.self)
=

/tmp/MyPlayground.playground:15:7: Type 'Factory' does not conform to protocol 
'AProto'
/tmp/MyPlayground.playground:6:7: Protocol requires function 
'constructInstance' with type '(ElementType.Protocol) -> ElementType'
/tmp/MyPlayground.playground:19:7: Candidate has non-matching type 
'(SimpleConstructableElement.Type) -> SimpleConstructableElement’

=


The thing that gets me about this is that Xcode’s code-completion tells me that 
SimpleConstructableElement.Type is of type SimpleConstructableElement.Protocol, 
so it should be the same as ElementType.Protocol and should be accepted, right?

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


Re: [swift-users] lazy initialisation

2016-07-10 Thread Karl via swift-users

> On 9 Jul 2016, at 06:34, Zhao Xin  wrote:
> 
> The compiler is not smart enough to treat this as you think, nor it will be 
> designed to. According to the documents, it is the developer‘s burden ​to add 
> @noescape or weak or unowned. So I disagree it is a bug.
> 
> Zhaoxin
> 
> On Sat, Jul 9, 2016 at 7:30 AM, Karl  > wrote:
> 
>> On 5 Jul 2016, at 03:47, Zhao Xin > > wrote:
>> 
>> No, it is not a bug.
>> 
>> For a closure, you have to call self explicitly unless the closure is mark 
>> as @noescape. Also, in this situation, self is not unowned, as the closure 
>> is not stored, it ran and released. Below, is a situation that you need use 
>> unowned self. Here the closure is stored in variable d instead of running 
>> and releasing.
>> 
>> lazy var d:()->Int = { [unowned self] in
>> return self.a*self.b
>> }
>> 
>> Zhaoxin
> 
> In this specific case, when you are initialising from a closure, there is no 
> need to make the capture of ‘self’ explicit and it’s totally safe for it to 
> be unowned. You can’t invoke the closure without going through a valid 
> instance, and that instance always owns the closure and never the other way 
> around.
> 


I know that the compiler doesn’t do this today, but I disagree that it will 
never have enough information to make inferences like this. It would simply be 
an adaptation of ARC to Swift - you don’t have these kind of attached lazy 
closures in Obj-C, so there was never any need for it. They run in the context 
of the instance just like a getter would, so they should have the same 
properties as a getter (including implicit ‘self’).

In general though, I think we are moving to “property behaviours”, which may 
need something like this in general. You would want to use unowned references 
in a stored property behaviour object; any retains/releases would be 
unnecessary. I’m sure we’ll talk about it more when that gets further along.

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


Re: [swift-users] lazy initialisation

2016-07-08 Thread Karl via swift-users

> On 5 Jul 2016, at 03:47, Zhao Xin  wrote:
> 
> No, it is not a bug.
> 
> For a closure, you have to call self explicitly unless the closure is mark as 
> @noescape. Also, in this situation, self is not unowned, as the closure is 
> not stored, it ran and released. Below, is a situation that you need use 
> unowned self. Here the closure is stored in variable d instead of running and 
> releasing.
> 
> lazy var d:()->Int = { [unowned self] in
> return self.a*self.b
> }
> 
> Zhaoxin

In this specific case, when you are initialising from a closure, there is no 
need to make the capture of ‘self’ explicit and it’s totally safe for it to be 
unowned. You can’t invoke the closure without going through a valid instance, 
and that instance always owns the closure and never the other way around.___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] [Bug or ByDesign?] unowned optional values not allowed

2016-07-06 Thread Karl via swift-users

> On 5 Jul 2016, at 18:21, Jordan Rose  wrote:
> 
> Longstanding bug, rdar://problem/17277899 . 
> Surprisingly few people have asked for it.
> 
> Jordan
> 

Good to know, thanks.

Maybe not enough people know/care about the overheads of weak references?

Since the WWDC Swift performance talk I’ve been more conscious of eliminating 
unnecessary retains/releases. That goes for weak references as well, as 
(certainly on Obj-C), accessing the value means acquiring a lock to ensure 
nobody is trying to zero that reference while you read it: 
http://opensource.apple.com//source/objc4/objc4-493.9/runtime/objc-arr.mm 
 
(see: objc_loadWeak). It’s basically never going to be in contention, but it’s 
still more overhead than a simple pointer.

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


Re: [swift-users] lazy initialisation

2016-07-04 Thread Karl via swift-users

> On 4 Jul 2016, at 21:12, Mark Dalrymple via swift-users 
>  wrote:
> 
> Here's the one I started with:
> 
>lazy var c:Int = {return a*b}()
> 
> and ended up with:
> 
> lazy var c:Int = {return self.a * self.b}()
> 
> It's in a closure, so need to explicitly reference self.
> 
> Cheers,
> ++md
> 


I’ve been hitting this myself. I think it’s a bug -- yes, you are technically 
in a closure, but the closure does not capture ‘self’ beyond the lifetime of 
‘self’. In this context, ’self’ should automatically be ‘unowned’.

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


Re: [swift-users] [Possible bug] Initialising multiple instance variables from a closure

2016-06-29 Thread Karl via swift-users
Oh, I figured it out. The syntax is a bit strange, but after enough attempts I 
ended up at this:

let (toolbar, aButton) : (UIToolbar, UIBarButtonItem) = {
let toolbar = UIToolbar()
let aButton   = UIBarButtonItem()

return (toolbar, aButton)
}()

Seems to work ¯\_(ツ)_/¯

Karl

> On 30 Jun 2016, at 02:57, Karl  wrote:
> 
> Currently you can initialise a class instance variable from a closure:
> 
> let textView : UITextView = {
>   let t = UITextView()
>   t.translatesAutoresizingMaskIntoConstraints = false
>   t.autocapitalizationType = .none
>   t.autocorrectionType = .no
>   t.spellCheckingType = .no
>   return t
>   }()
> 
> However, it doesn’t seem to be possible to return and initialise multiple 
> variables from a closure:
> 
>   let (toolbar : UIToolbar, aButton : UIBarButtonItem) = {// 
> ERROR: Type of expression is ambiguous without more context
>   let toolbar = UIToolbar()
>   let aButton = UIBarButtonItem()
>   return (toolbar, aButton)
>   }()
> 
> Is this something which, in theory should be supported?
> 
> Thanks
> 
> Karl

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


Re: [swift-users] When does `Data.init?(capacity:)` fail?

2016-06-19 Thread Karl via swift-users
As I understand it, that’s not an error in the ‘try’ sense of the word. If that 
failure happens, it’s a catastrophic issue which should bring down the 
application.

So the initialiser shouldn’t be failable; you’re right. File a bug at 
bugs.swift.org.

Karl

> On 18 Jun 2016, at 06:06, Saagar Jha via swift-users  
> wrote:
> 
> This  might be 
> relavant. Basically, Data’s init will fail if memory can’t be allocated for 
> it.
> 
> 
> 
> On Fri, Jun 17, 2016 at 11:38 AM Adrian Zubarev via swift-users 
> > wrote:
> Hello there, I’m trying to optimize my code and reduce copying from different 
> buffers into a new one.
> 
> I thought I just create a Data value with enough capacity and write directly 
> into it. My problem is that Data.init?(capacity:) can fail, but why and when?
> 
> Can someone explain this behavior to me?
> 
> I’m sending data via TCP sockets and when recn function write directly into a 
> Data struct.
> 
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> ___
> swift-users mailing list
> swift-users@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-users 
> 
> -- 
> -Saagar Jha
> ___
> 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] SequenceType vs. CollectionType

2016-06-16 Thread Karl via swift-users

> On 15 Jun 2016, at 01:59, Brent Royal-Gordon via swift-users 
>  wrote:
> 
>> I find the SequenceType protocol a bit confusing.  My confusion is best 
>> explained in the context of a specific, real-world example.  Let's say that 
>> I wanted to extend a protocol with a method "repeated(Int)" that would allow 
>> me to iterate over a collection of items multiple times, like this:
>> 
>> for x in ["a", "b", "c"].repeated(3) {
>>  print(x, terminator: "")
>> }
>> 
>> That would be expected to print the string "abcabcabc".
>> 
>> Implementing the extension is simple enough.  Here's my main question: is it 
>> more appropriate to implement it by extending SequenceType or extending 
>> CollectionType?  I'm not imagining an implementation that does any 
>> buffering, so one could argue that the operation would not have predictable 
>> behavior in the context of an arbitrary SequenceType -- however, a likely 
>> implementation would rely upon nothing more than the the generate() method, 
>> which is available in the SequenceType protocol.
> 
> A protocol is not merely a collection of required members; it is a set of 
> promises about a conforming type's behavior. Some of them can be expressed in 
> code, like that a `SequenceType` provides a `generate()` method returning an 
> instance conforming to `GeneratorType`. Others can only be described in 
> documentation, like that the generator returned by `generate()` returns all 
> of the elements in the sequence, rather than skipping some of them.
> 
> In the case of `SequenceType`, the documentation says:
> 
>> SequenceType makes no requirement on conforming types regarding whether they 
>> will be destructively "consumed" by iteration. To ensure non-destructive 
>> iteration, constrain your sequence to CollectionType.
>> …
>> It is not correct to assume that a sequence will either be "consumable" and 
>> will resume iteration, or that a sequence is a collection and will restart 
>> iteration from the first element. A conforming sequence that is not a 
>> collection is allowed to produce an arbitrary sequence of elements from the 
>> second generator.
> 
> So even though the `SequenceType` protocol provides all of the calls your 
> `repeated(_:)` method will use, it explicitly does *not* promise that those 
> calls will behave in the way needed for `repeated(_:)` to work correctly. 
> Your code will be making exactly the sort of assumption the documentation 
> warns you not to make. The fact that the compiler cannot detect this mistake 
> doesn't make it any less of a mistake.
> 
> Therefore, I would say you should put `repeated(_:)` on `CollectionType`. If 
> you put it on `SequenceType`, it will malfunction on some of the sequences 
> which claim to support it.
> 
> -- 
> Brent Royal-Gordon
> Architechies
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

Well you could do it, but you’d need to build up a non-consuming sequence as 
you go so it wouldn’t be a transparent wrapper.
You could specialise for sequences which also implement CollectionType and 
handle that case more efficiently.
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Usage of final let?

2016-06-13 Thread Karl via swift-users
Welcome!

That’s a fair point; “final let” doesn’t make sense. You should file a bug 
report on https://bugs.swift.org

Karl

> On 13 Jun 2016, at 07:43, Azuan via swift-users  wrote:
> 
> Hi,
> 
> This is my first email to this mailing list. Do correct me if I did something 
> wrong :)
> 
> Read in docs, saying that by using final on variables, you can’t override it 
> in it’s subclass. Using `final var` makes sense to me. But what is the 
> purpose of using `final let` since by using `let`, it is already an immutable 
> variable anyway.
> 
> Regards,
> Azuan
> 
> ___
> 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] build-script error

2016-06-10 Thread Karl via swift-users
i686 is a 32-bit system, right? We don’t support Intel 32-bit on Linux (yet?). 
The only Intel Linux target is x86_64.


> On 10 Jun 2016, at 20:18, Jeff Ramsey via swift-users  
> wrote:
> 
> Here you go Dmitri.  It's an older Dell 1501 that was given to me; I wiped it 
> and put Ubuntu on it.  Thanks.
> 
> Python 2.7.6 (default, Jun 22 2015, 18:00:18) 
> [GCC 4.8.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import platform
> >>> print(platform.system())
> Linux
> >>> print(platform.machine())
> i686
> >>> 
> 
> Here's some additional information if it's useful:
> 
> ~/swift$ lsb_release -a
> No LSB modules are available.
> Distributor ID:Ubuntu
> Description:Ubuntu 14.04.3 LTS
> Release:14.04
> Codename:trusty
> 
> ~/swift$ uname -a
> Linux Inspiron-1501 3.13.0-74-generic #118-Ubuntu SMP Thu Dec 17 22:52:02 UTC 
> 2015 i686 athlon i686 GNU/Linux
> 
> 
> 
> On Fri, Jun 10, 2016 at 12:31 PM, Dmitri Gribenko  > wrote:
> On Fri, Jun 10, 2016 at 9:14 AM, Jeff Ramsey via swift-users
> > wrote:
> > I followed directions here to clone the compiler source and build it on
> > Ubuntu 14.04:
> >
> > https://github.com/apple/swift/blob/master/README.md 
> > 
> 
> Hi Jeff,
> 
> Which architecture are you running on?
> 
> Could you run "python" in the terminal, type the following script, and
> send me the output?
> 
> import platform
> print(platform.system())
> print(platform.machine())
> 
> 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

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


Re: [swift-users] Conditional generic initializers?

2016-05-15 Thread Karl via swift-users
Yes. You need to put it in an extension.

extension Foo where T1 == T2 {
convenience init(values: [T1]){
….
}
}

> On 15 May 2016, at 14:45, Neil Faiman via swift-users  
> wrote:
> 
> Is it possible for a generic class to have methods (specifically, 
> initializers) which are only defined if the generic parameters meet certain 
> constratins?
> 
> Here’s a concrete example:
> 
>class Foo  {
>init(pairs: [(T1, T2)]) {}
>// What I’d like to be able to doL
>convenience init "where T1 == T2" (values: [T1]) { self.init(pairs: 
> values.map{ ($0, $0) }) }
>}
> 
> That is, I’d like to provide a convenience initializer that takes an array of 
> values instead of pairs, and turns the values into pairs, IF THE TWO GENERIC 
> TYPE PARAMETERS ARE THE SAME.
> 
> I can’t find a way to accomplish this. Is there one?
> 
> Thanks,
> 
>   Neil Faiman
> ___
> 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