Re: [swift-users] KeyedDecodingContainerProtocol decode methods non-mutating?

2017-12-31 Thread Brent Royal-Gordon via swift-users
> On Dec 28, 2017, at 1:57 PM, Ingo Maier via swift-users 
>  wrote:
> 
> Can anybody tell why the decode methods in UnkeyedDecodingContainer
> are marked mutating but those in KeyedDecodingContainerProtocol and
> SingleValueDecodingContainer are not? Is it a simple oversight or is
> there a reason for this? It seems to me that all of them should be
> mutating.


The `UnkeyedDecodingContainer.decode(_:)` methods consume values as they decode 
them; that is, the first call returns the first value, the second call returns 
the second value, etc. The ones in the other containers don't consume values; 
in theory, you could decode the same key twice and you should get the same 
value both times. So the UnkeyedDecodingContainer methods are mutating, but the 
other containers' methods are not.

-- 
Brent Royal-Gordon
Architechies

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


[swift-users] Rethrows issue

2017-12-30 Thread Brent Royal-Gordon via swift-users
I need to do something like this:

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

The problem is, the Swift compiler doesn't allow the explicit `throw` 
statement; even though it can only throw errors originally thrown by 
`predicate`, the compiler is not smart enough to prove that to itself. I cannot 
make `body` a `throws` function.

Is there any way to do this? Either to override the compiler's safety check, or 
to rewrite this function to avoid it?

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] the pain of strings

2017-06-30 Thread Brent Royal-Gordon via swift-users
> On Jun 30, 2017, at 2:44 PM, David Baraff via swift-users 
>  wrote:
> 
> Python:
>  shortID = longerDeviceID[-2:]# give me the last two 
> characters
> 
> Swift:
>  let shortID = 
> String(longerDeviceID.characters.dropFirst(longerDeviceID.characters.count - 
> 2))

This actually perfectly illustrates why Swift is designed the way it is.

The first thing to notice is that the Python version is terse, but it's 
actually impossible to know what it actually *does*. Is it operating on bytes, 
code units, Unicode scalars, or grapheme clusters? Well, that depends: is this 
Python 2 or Python 3? If it's 2, is this a `string` or a `unicode`? If it's 3, 
is it a `string` or a `bytes`? And if it is one of the Unicode-aware types, how 
are those indexed? (I honestly don't know—I can't find anything about that in 
the documentation.) And forget about understanding its performance 
characteristics—that's an implementation detail.

The second thing to notice is that your Swift solution is very inefficient. It 
counts all the characters in the string, subtracts two, then counts all but the 
last two characters in the string before returning the last two. That is, it 
unnecessarily walks over the entire string twice. If you read your expression 
closely, all of this behavior is plainly stated in the code.

What you actually want to do is count back two characters from the *end*, like 
so:

let shortID = 
String(longerDeviceID.characters[longerDeviceID.characters.index(longerDeviceID.characters.endIndex,
 offsetBy: -2) ..< longerDeviceID.characters.endIndex])

Or, in Swift 4:

let shortID = 
String(longerDeviceID[longerDeviceID.index(longerDeviceID.endIndex, offsetBy: 
-2)...])

Or, as Adrian Zubarev pointed out, you can use the very convenient `suffix(_:)` 
method, available on any `Sequence`:

let shortID = String(longerDeviceID.characters.suffix(2))   // 
Swift 3
let shortID = String(longerDeviceID.suffix(2))  
// Swift 4

Swift's strings were very deliberately designed this way. It's tougher to get 
off the ground, sure, but it's better in the long run.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Class vs Structures

2017-06-30 Thread Brent Royal-Gordon via swift-users
> On Jun 29, 2017, at 10:40 AM, Vitor Navarro via swift-users 
>  wrote:
> 
> Do you guys have any guideline regarding usage here?


Here's my suggestion: Use a class when the object represents a specific *thing* 
that can't be duplicated without consequence; use a struct (or enum) when the 
instance represents some abstract data with no concrete existence. Some 
examples using framework types:

* A piece of text is just some data; duplicating it doesn't do anything except 
maybe use more memory. So `String` should be a struct.

* A label is a particular thing that exists at a particular place on screen; if 
you duplicated it, you'd end up with two labels on the screen, or with an 
off-screen copy of a label that wouldn't have any effect when you mutated it. 
So `UILabel` should be a class.

* A URL is just some data; if you construct two URLs with the same contents, 
they are completely interchangeable. So `URL` should be a struct.

* A connection to a web server to retrieve the contents of a URL is a 
particular thing; if you duplicated it, you would either establish another 
connection, or the two instances would interfere with each other (e.g. 
canceling one would cancel the other). So `URLSessionTask` and 
`NSURLConnection` are classes.

Sometimes the same problem, approached in slightly different ways, would allow 
you to use either one. For instance, a database record is a particular *thing* 
and should probably be a class, but copy the values of the fields (perhaps 
omitting the ID) out of it and suddenly you have a plausible struct. As a 
*general* rule, it's usually better to use structs where possible because it's 
easier to reason about their behavior—mutations in one function don't suddenly 
pop up in a totally unrelated function—but sometimes a particular type works 
very easily as a class and very awkwardly as a struct. Ultimately, it's a 
judgement call.

The other point I will make is this: "Protocol-oriented programming" is new and 
exciting and often very useful, but it's a tool, not a religion. If subclassing 
works well for your use case, then subclass away.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] JSON keys survey

2017-06-24 Thread Brent Royal-Gordon via swift-users
> On Jun 23, 2017, at 9:42 AM, Tony Parker via swift-users 
>  wrote:
> 
> 1. Does your JSON use snake_case_keys or CamelCase or other?

My internal APIs use snake_case. Several APIs I write against (not necessarily 
in Swift), like Heroku and Stripe, also use snake_case. The JSON Feed format 
uses snake_case.

I suspect the deciding factor is typically the source language—if your backend 
is written in Perl, Python, or Ruby, you're probably using snake_case. If it's 
in JavaScript, Java, C#, or Swift, you're probably using camelCase.

> 2. Is the key type consistent throughout the JSON?

Yes.

> 3. If JSONEncoder/Decoder converted these, would you have any other need to 
> specify custom keys?

Occasionally, but far less often. For instance, when adapting an API that used 
Rails conventions, I would still want to translate `created_at` dates to 
`creationDate`. But that assumes I wanted to use those dates at all—I often 
ignore them.

If you're considering adding a key transformation strategy to 
JSONEncoder/Decoder, I strongly encourage you to do so. Case transformation 
will handle at least 80% of the custom keys, and even when people *do* still 
need to customize further, case transformation will help them do it more 
easily. And if you *did* want to provide a `custom` option, it might allow 
developers to move *all* of their custom JSON key names out of their `Codable` 
implementations, which would make them easier to use with multiple coders.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Doubt about the runtime system

2017-06-06 Thread Brent Royal-Gordon via swift-users
> On Jun 6, 2017, at 6:55 AM, Ronaldo Faria Lima via swift-users 
>  wrote:
> 
> The /perform/ method may fail if the configured class does not have it. But, 
> testing for the method existence by using /responds(to:)/ always return 
> false. 


That's odd. Could you use `aClass.instancesRespond(to: sel)` instead?

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Extensions

2017-05-13 Thread Brent Royal-Gordon via swift-users
> On May 13, 2017, at 5:32 PM, Don Giovanni via swift-users 
>  wrote:
> 
> Hi I was wondering if i could get some suggestions on this:
> 
> extension CGPoint : Comparable
> {
> static func <(l: CGPoint, r: CGPoint) -> 
>   Bool{
> return true;
> }
> 
>  static func ==(l: CGPoint, r: CGPoint) -> 
>Bool{
>return true;
> }
> }
> 
> CGPoint is a Core graphics struct. 
> This code gives me an error "Declaration is only valid at file scope". 
> However per swift documentation, I cannot add an access modifier to 
> extensions that adopt protocols.   I was wondering if there is an elegant 
> workaround for this limitation or if there's something I'm missing here. 
> Thanks. 

Is this the only thing in the file, or is the extension nested inside something 
else? That's what that error usually means.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Making Error sub-enums Equatable

2017-05-10 Thread Brent Royal-Gordon via swift-users
> On May 10, 2017, at 2:05 AM, Rick Mann  wrote:
> 
> This seems so obvious that I feel like it should be provided by the language 
> by default. I suppose you can make it even more compact with
> 
>case (.one, .one),
> (.two, .two),
> (.three, .three):
>   return true
> 
> Maybe swift could provide a 'case==()' so one needn't write this (I can see 
> it getting quite tedious and error-prone, should one forget to update the 
> equality after adding additional cases).


There's been some talk on swift-evolution about synthesizing an `Equatable` 
implementation for enums with associated types, but that would not implement 
your slightly weird equality semantic—it would compare the associated types, 
which isn't what you want. The same would undoubtedly be true for any other 
syntactic sugar we might provide. So I wouldn't hold your breath waiting for a 
better way to implement it than this.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Making Error sub-enums Equatable

2017-05-10 Thread Brent Royal-Gordon via swift-users
> On May 8, 2017, at 2:01 AM, Rick Mann via swift-users  
> wrote:
> 
> Seriously, I've been googling this for a half-hour, and I can't find an 
> answer (everything that comes up is for ErrorType, absolutely nothing for 
> Error).
> 
> I have an enum:
> 
> enum MyErrors : Error
> {
>case one(String)
>case two
>case three(String)
> }
> 
> let a: MyErrors = .one("foo")
> let b = .two
> let c = .towo
> 
> I want to compare them with ==, and I don't care about the associated types. 
> I can't for the life of me figure out how without an exhaustive switch 
> statement in a == definition. Is that the only way?

Yes, the correct way to compare two enums is with a `switch` statement.

The good news is, Swift's `switch` statement is good enough that these aren't 
terribly difficult to write. My preferred pattern (given your "ignore the 
associated type" semantic) is:

extension MyErrors: Equatable {
static func == (lhs: MyErrors, rhs: MyErrors) -> Bool {
switch (lhs, rhs) {
case (.one, .one):
return true
case (.two, .two):
return true
case (.three, .three):
return true
case (.one, _), (.two, _), (.three, _):
return false
}
}
}

You do it this way instead of using `default:` so that, if you add another case 
later, it won't just get matched by the `default:` and always return `false`.

(P.S. I would suggest using a name like `MyError`, not `MyErrors`. A given 
instance of `MyError` only represents one of the errors, not several of them.)

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Passing value types or members of value types?

2017-05-06 Thread Brent Royal-Gordon via swift-users
> On May 6, 2017, at 9:33 PM, Kelvin Ma via swift-users  
> wrote:
> 
> If I have a “large” struct like
> 
> struct Vertex
> {
> let x:Double, y:Double
> var r:Int, g:Int, b:Int
> let s:Double, t:Double
> var selected:Bool
> }
> 
> and I want to pass it to a function without modifying it like
> 
> func taxicab_distance(_ v1:Vertex, _ v2:Vertex) -> Double
> {
> return v2.x - v1.x + v2.y - v1.y
> }
> 
> Will the entire struct Vertex get copied and pushed onto the stack, or will 
> only the relevant members be passed to the function?
> 
> In other words, does the compiler know to optimize this call down to
> 
> func taxicab_distance(v2x:Double, v1x:Double, v2y:Double, v1y:Double) -> 
> Double
> {
> return v2x - v1x + v2y - v1y
> }

When passed as an argument, a struct is recursively broken up into individual 
primitives, and each of those is passed in separate arguments. (The primitive 
types in question are mostly special "builtin" types which are wrapped by 
standard library types like `Int` and `Double`.) As far as I'm aware, there is 
no optimization that removes unused parts of the struct. That means this would 
be passed as something like:

func taxicab_distance(_ v1.x._value: Builtin.Float64, _ v1.y._value: 
Builtin.Float64, _ v1.r._value: Builtin.Int64, _ v1.g._value: Builtin.Int64, _ 
v1.b._value: Builtin.Int64, _ v1.s._value: Builtin.Float64, _ v1.t._value: 
Builtin.Float64, _ v1.selected._value: Builtin.Int1, _ v2.x._value: 
Builtin.Float64, _ v2.y._value: Builtin.Float64, _ v2.r._value: Builtin.Int64, 
_ v2.g._value: Builtin.Int64, _ v2.b._value: Builtin.Int64, _ v2.s._value: 
Builtin.Float64, _ v2.t._value: Builtin.Float64, _ v2.selected._value: 
Builtin.Int1) -> Builtin.Float64 { … }

Because of this, it may sometimes make sense to convert large structs into 
copy-on-write types by hand—basically, make a struct which wraps an inner class 
type, guarding all mutations with an `isUniquelyReferenced(_:)` check. (You're 
right that there's no implicit copy-on-write behavior in structs currently—when 
a struct has copy-on-write behavior, it has been manually implemented that way.)

Note that this may not always be the case: There's a built-in copy-on-write 
optimization which will soon come to instances which have been cast to a 
protocol type, and the "resilient" structs planned for a future version of 
Swift will probably be passed by reference in some way. But I believe that's 
the state of things in Swift 3.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Why does String.CharacterView have reserveCapacity(:)?

2017-05-04 Thread Brent Royal-Gordon via swift-users
> On May 2, 2017, at 12:35 PM, Kelvin Ma via swift-users 
>  wrote:
> 
> I’m wondering why the String.CharacterView structure has a reserveCapacity(:) 
> member?

Because it conforms to the RangeReplaceableCollection protocol, which requires 
`reserveCapacity(_:)`.

More broadly, because you can append characters to the collection, and so you 
might want to pre-size it to reduce the amount of reallocating you might need 
to do in the future.

> And even more strangely, why String itself has the same method?

Because it has duplicates of those `CharacterView` methods which don't address 
individual characters. (In Swift 4, it will be merged with CharacterView.)

> It’s even weirder that String.UnicodeScalarView has this method, but it 
> reserves `n` `UInt8`s of storage, instead of `n` `UInt32`s of storage.

Because the views are simply different wrappers around a single underlying 
buffer type, which stores the string in 8-bit (if all characters are ASCII) or 
16-bit (if some are non-ASCII). That means that `UnicodeScalarView` isn't 
backed by a UTF-32 buffer; it's backed by an ASCII or UTF-16 buffer, but it 
only generates and accepts indices corresponding to whole characters, not the 
second half of a surrogate pair.

Why not allocate a larger buffer anyway? Most strings use no extraplanar 
characters, and many strings use only ASCII characters. (Even when the user 
works in a non-ASCII language, strings representing code, file system paths, 
URLs, identifiers, localization keys, etc. are usually ASCII-only.) By 
reserving only `n` `UInt8`s, Swift avoids wasting memory, at the cost of 
sometimes having to reallocate and copy the buffer when a string contains 
relatively rare characters. I believe Swift doubles the buffer size on each 
allocation, so we're talking no more than one reallocation for a non-ASCII 
string and two for an extraplanar string. That's quite acceptable.

> Also why String.UTF8View and String.UTF16View do not have this method, when 
> it would make more sense for them to have it than for String itself and 
> String.CharacterView to have it.

Because UTF8View and UTF16View are immutable. They don't conform to 
RangeReplaceableCollection and cannot be used to modify the string (since you 
could modify them to generate an invalid string).

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Store objects of generic types in a data structure

2017-04-08 Thread Brent Royal-Gordon via swift-users
> On Apr 8, 2017, at 5:22 AM, Hugo Lundin via swift-users 
>  wrote:
> 
> How would I be able to achieve this in Swift? My current idea of this 
> approach does not seem to work, but also the idea to create specific 
> subclasses for every type (and then type cast the different properties), 
> gives a lot of work, and there would be a limitation for which types are 
> available. 

I would create a protocol with the same interface (other than initializers) as 
your `Property` type, but with an `Any` equivalent to any `T`-taking API. Then 
make your `Array` use the protocol, not `Property` itself, as its element type.

// Let's say this is your existing type:
struct Property {
let description: String
let property: T

init(description: String, property: T) {
self.description = description
self.property = property
}
}

// Create a protocol equivalent that doesn't use T:
protocol AnyProperty {
var description: String { get }
var anyProperty: Any { get }
}

// Then conform `Property` to it:
extension Property: AnyProperty {
var anyProperty: Any {
return property
}
}

// Now, in your Analytics class:
class Analytics {
private var properties: [AnyProperty]

func add(_ property: AnyProperty) {
properties.append(property)
}

func show() {
for p in properties {
print("\(p.description): \(p.anyProperty)")
}
}
}

// And do:
let stats = Analytics()
stats.add(Property(description: "HealthKit", property: false))
stats.add(Property(description: "iOS Version", property: "9.3"))
stats.show()

This is called "type erasure"; we say that the `AnyProperty` protocol is 
"erasing" the type of the `T` generic parameter because it essentially hides it 
behind the protocol. Java automatically erases all type parameters, which is 
convenient here, but it can lead to bugs. (For instance, the generic parameter 
of `List` is similarly erased, so you can cast a `List` up to 
`List`, then add non-`Property` objects to it. When you later run 
`show()`, it will throw an exception.) Swift is more strict, which prevents 
bugs but sometimes means you need to explicitly erase types.

Here we've used a protocol to erase the type of `Property`, but that often 
isn't an option—for instance, when you cast an instance to a protocol type, the 
"wrapper" around it doesn't itself conform to any protocols. When it isn't, you 
have to make a more complicated type-erasing wrapper—usually either by making a 
closure that calls each method and storing them in properties, or by writing a 
non-generic abstract superclass which declares all the visible members and a 
generic subclass that overrides the superclass declarations.

Here's an article on how to write type-erased wrappers in more complicated 
situations: 


Hope this helps,
-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] How to debug Xcode: "An internal error occurred. Source editor functionality is limited"

2017-04-07 Thread Brent Royal-Gordon via swift-users
> On Apr 7, 2017, at 11:21 AM, Jesse Grosjean via swift-users 
>  wrote:
> 
> 
> Does anyone recognize the below stack and know what might be causing that
> particular crash? Is there any way to log what file the SourceKitService is
> working on, so I can see what it's doing before the crash?
> 
> After manually going through all my code and individually adding files back 
> to the project I've found (fingers crossed!) a fix. I don't understand all 
> the conditions neccessary, but the problem is related to defining class 
> extensions in files separate from where the class is originally defined.
> 
> So I didn't change any code to fix the problem, but I did move a number of 
> class extensions out of separate files and just append the extensions text to 
> the end of the original file where the class was defined.
> 
> Hope this helps someone to avoid all the fun I just went through!

If you can reduce this down to a small test case, and especially if you get the 
same crash when you try to compile your code, it'd be very helpful if you could 
file a bug at bugs.swift.org. The compiler's repository has a big folder full 
of examples that crash it, and we do get around to fixing them!

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Property access for subclasses only

2017-03-17 Thread Brent Royal-Gordon via swift-users
> On Mar 17, 2017, at 11:54 AM, James Dempsey via swift-users 
>  wrote:
> 
> I have a class in a framework that is expected to be subclassed in modules 
> outside of the framework. I’d like to do the following:
> 
> 1. I want some properties of that class to be accessible by subclasses 
> outside of the framework.
> 2. I don’t want these properties of that class to be accessible by any piece 
> of code outside of the framework because I don’t want dependencies on these 
> properties to propagate beyond the subclass.
> 
> Am I correct in thinking that there is no way to achieve both #1 and #2 in 
> Swift?
> 
> The only way I know to achieve #1 is to make the property public or open. And 
> that makes the property public to everyone which makes #2 impossible.

No, there is no way to do this.

This reflects a judgement on the part of Swift's designers that `protected` 
access is not very useful, because you can always get around it by creating an 
extension on the type and exposing the API under a different name. At the same 
time, it prevents developers from structuring their subclass code freely; code 
which would be better moved to free functions or helper types instead has to 
remain in the subclass solely to access protected symbols.

This judgement is not uncontroversial, and gets rehashed on swift-evolution at 
least once a year.

> It seems like the best I can do is put a big comment on each property that 
> says something like:
> // NOTE: FOR SUBCLASSERS ONLY! DO NOT USE EXCEPT IN A SUBCLASS!


You can do a little bit better by putting the methods in an ancillary "sharps 
drawer" type:

open class MyClass {
open func publicThing() { … }

public struct SubclassOnly {
fileprivate var instance: MyClass

public func protectedThing() { … }
}

var subclassOnly: SubclassOnly { get { SubclassOnly(instance: 
self) } }
}

This is still sort of the "honor system", but it at least makes it impossible 
to accidentally access something you shouldn't.

If you want the protected methods to only be used from inside certain override 
points, you can actually enforce that by creating a type which can only be 
constructed internally, requiring that type be passed to the methods you want 
to protect, and only passing it to your override points. For example:

open class MyClass {
public struct ProtectionToken {
fileprivate init() {}
}

// Instead of overriding this...
public func publicThing() {
overridablePublicThing(protected: ProtectionToken())
}

// Subclasses override this.
open func overridablePublicThing(protected: ProtectionToken) { 
… }

// You can only call this if you have a protection token, and 
you can 
// only get a protection token if the class gives it to you.
public func protectedThing(protected: ProtectionToken) { … }
}

This is a heavyweight solution, but if you really care strongly about who's 
allowed to call your methods, it'll do the trick. And it allows the kind of 
restructuring that `protected` forbids, since once you have a protection token, 
you can pass it to another method or type to delegate your access. You can also 
have several different kinds of protection tokens and do various other clever 
things.

-- 
Brent Royal-Gordon
Architechies

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


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

2017-03-15 Thread Brent Royal-Gordon via swift-users
Without touching the broader question of bitmap formats:

> On Mar 15, 2017, at 12:01 PM, Nevin Brackett-Rozinsky via swift-users 
>  wrote:
> 
> Also, for my specific application, I need to take an array of floating point 
> numbers and say, “Hey, the underlying bits that make up the IEEE-754 
> representation of these numbers are exactly the bits that I want to use for 
> the colors of the pixels.” I do not know how to do that in Swift.
> 
> In C I would malloc a buffer, write to it as (float*), then pass it to a 
> function which takes (char*) and saves a PNG. Thus there is only one 
> allocation, the buffer is filled with float values, and the exact bit-pattern 
> is interpreted as RGBA pixels.
> 
> How can I do the equivalent in Swift?

Create and fill an Array (actually, a ContiguousArray would be a 
little better for this use) with your data. Then use `withUnsafeBytes` to 
access the raw bytes as an `UnsafeRawBufferPointer`, a type which behaves sort 
of like a fixed-size array of `UInt8`.

You could access the bytes one at at time by looping (or indexing, or doing 
many other things):

myFloats.withUnsafeBytes { buffer in
for byte in buffer {
putchar(byte)
}
}

Or you can pull out the start pointer and count and use them:

myFloats.withUnsafeBytes { buffer in
guard write(fd, buffer.baseAddress, buffer.count) != -1 else { 
throw MyError.IOError(errno) }
}

Or you can copy it into a `Data` or `Array` and return it to the outer context:

let bytes = myFloats.withUnsafeBytes { buffer in
return Data(buffer: buffer) // or Array(buffer)
}

One thing you should *not* do is hold on to `buffer` or its `baseAddress` 
beyond the closing bracket. Once `withUnsafeBytes` returns, the `Array` or 
`ContiguousArray` is free to move or delete its data, so you can no longer 
depend on the pointer to be correct. Copy the data to an `Array` or `Data`, or 
allocate and copy it to your own `UnsafeRawBufferPointer`, if you want to hold 
on to it longer.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Swift 3 Decimal NSDecimal NSDecimalNumber

2016-12-20 Thread Brent Royal-Gordon via swift-users
> On Dec 20, 2016, at 8:32 AM, Alex Thurston via swift-users 
>  wrote:
> 
> Swift 3 introduced the Decimal class, which at first I thought was supposed 
> to 'replace' NSDecimalNumber in Swift, like Error is the new NSError, etc.  
> However, upon further investigation, it's not clear to me that this is 
> actually the case. It appears that Swift 3's Decimal is more just an 
> NSDecimal, but with some bridging so it can use NSDecimalNumber's methods 
> when needed. What I'm wondering is, should I be replacing NSDecimalNumber in 
> my app with Decimal? Is Decimal the successor to NSDecimalNumber in Swift?

`Decimal` is actually a struct, not a class, and in fact it's just the Swift 
name for the `NSDecimal` struct in Objective-C. In Swift, functions like 
`NSDecimalAdd` are exposed as operators on `Decimal` and are used to satisfy 
the requirements of various numeric protocols like `SignedNumber`.

The end result is that `Decimal` is a lot like `Int` or `Double`—it's a value 
type which can be conveniently used to do all sorts of math. `NSDecimalNumber`, 
then, is equivalent to `NSNumber`.

> Since my app is doing a lot of formatting, it would require much casting 
> between Decimal and NSDecimalNumber, or adding of extensions to use, so I 
> don't think it would be natural/convenient without many extensions. Is Swift 
> planning to improve Decimal to be more usable with NumberFormatter, or other 
> object-oriented number APIs? Hopefully I have given enough information to 
> answer my question. 

Objective-C APIs which use `NSDecimalNumber` should be bridged to `Decimal`, 
just as `NSString` is bridged to `String`. That bridging may not work for 
category methods, though; you could expose those to Swift by writing an 
extension on `Decimal` which casts `self` to `NSDecimalNumber` and then calls 
through to your Objective-C methods.

Similarly, you should be able to use `Decimal` with `NumberFormatter` by 
casting to `NSDecimalNumber`, just as you would cast `Int` or `Double` to 
`NSNumber` to use them with `NumberFormatter`.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Understanding pass-by-value

2016-11-04 Thread Brent Royal-Gordon via swift-users
> On Nov 4, 2016, at 9:45 AM, Ryan Lovelett  wrote:
> 
> Just out of curiosity if I looked at the SIL, would that allow me to see
> any of that in action? Or would it be too opaque?

Maybe. What might be more directly useful is looking at the source for `Data` 
in Foundation:



You'll notice that `Data` has an internal property called `_wrapped` of type 
`_SwiftNSData`, which (if you jump up a few dozen lines) is a class. Since it's 
inside a class, the contents of that property won't be automatically copied.

Looking around a little more thoroughly, you might notice that `mutating` 
methods call `_applyUnmanagedMutation(_:)`: 
.
 If you search the codebase, you'll find the implementation of that method in a 
different file: 
.

The heart of the copy-on-write behavior is the call to 
`isKnownUniquelyReferenced(_:)`. This is a part of the standard library which 
is basically only used to implement copy-on-write. 
`isKnownUniquelyReferenced(_:)` returns `true` if your variable is the only one 
which has a strong reference to the object. If so, it's safe to mutate; if not, 
you'll need to make a copy so you don't affect any of the other instances 
sharing the object with you.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Understanding pass-by-value

2016-11-04 Thread Brent Royal-Gordon via swift-users
> On Nov 4, 2016, at 5:59 AM, Ryan Lovelett via swift-users 
>  wrote:
> 
> struct Foo {
>  init(from buffer: Data) {
> bar = integer(withBytes: Array(buffer[4..<6]))
> baz = integer(withBytes: Array(buffer[6..<8]))
> ...
>  }
> 
> let d = Data(count: Int(3e+8))
> let f = Foo(from: d)
> 
> Did I just make two copies of the `Data`? How would I investigate this
> to understand it?

Do you mean, "did I make two copies of the `Data`, one in a top-level variable 
named `d` and the other in a parameter named `buffer`"?

If so, then answer is "Yes, but…"

A value type like `Data` can't really hold variable-sized data like the bytes 
in a `Data` object. Instead, the bytes are stored in a separate object, and 
`Data` manages that with copy-on-write semantics. In other words, there are two 
copies of the `Data` instance itself, but they share a single copy of the bytes 
they're storing.

To illustrate more clearly, after this line:

let d = Data(count: Int(3e+8))

You have something like this:

| ...stack frame for top level...   |   
+---+
| Data instance (d) | -->| 
...3e+8 bytes of data... |
|   |   
+---+

And then once you execute the call on this line:

let f = Foo(from: d)

You have this:

| ...stack frame for top level...   |   
+---+
| Data instance (d) | -->| 
...3e+8 bytes of data... |
|   |   
+---+
| ...stack frame for Foo(from:) |   
  ^ 
| Data instance (buffer)| 
-+

If `Foo(from:)` were to copy `buffer` and then mutate the copy, the bytes would 
be copied before the mutation occurred. But since neither `f` nor `buffer` is 
mutated in this code (indeed, both are in immutable variables!), that never 
happens here.

> I _think_ that if I made it `inout` then it would not make a copy but
> now the data buffer is mutable. I want it to be clear I'm not mutating
> the buffer inside the initializer but I also want to be sure I'm not
> making a copy of the buffer either.

That's implementation-specific. Notionally, an `inout` variable is essentially 
passed in by value, modified as a copy, returned to the caller, and then 
assigned back to the original value. In some cases that's basically what 
actually ends up happening. But Swift tries to optimize `inout` behavior into 
directly mutating the original variable, and it's often successful.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Localization in Swift.

2016-11-01 Thread Brent Royal-Gordon via swift-users
> I managed to replace my code with 
> 
> let newSays = String.localizedStringWithFormat(NSLocalizedString("It runs %d 
> times", comment: "new run times"), count)
> 
> However, I still thing it would be better if we could use \(foo) directly, as 
> it is more Swift style. Any idea why this can't happen?

I have some code that does that (Swift 2 version: 
), but it relies on the 
ExpressibleByStringInterpolation protocol, which is currently deprecated 
because it's due for a redesign.

Ultimately, localization is a Foundation-level concern. I'd love to see a 
future Foundation do something clever with NSLocalizedString, but it seems like 
their hands have been full with higher-priority stuff like the value-type 
equivalents.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Referencing different objects implementing a protocol where the protocol has 'associatedtype'

2016-09-20 Thread Brent Royal-Gordon via swift-users
> On Sep 18, 2016, at 6:21 AM, Palfi, Andras via swift-users 
>  wrote:
> 
> Workaround:
> Use 'Thunks'. These are type eraser structs, which implements the same 
> protocol. For each method they referencing (capturing) the original methods 
> and properties of the object. So 'thunks' are technically proxy objects. 
> 
> struct DirtyThunk : SomeProtocol {
> 
>private let _someMethod : (SomeElementType) -> Void
> 
>init(delegate : D) where D.ElementType==SomeElementType {
>_someMethod = delegate.someMethod
>}
> 
>func someMethod(withElement: SomeElementType) {
>_someMethod(withElement)
>}
> }
> 
> the subscribe method will be modified:
> func subscribe(delegate : D) where 
> D.ElementType==SomeElementType { // would be better without generics as this 
> generates as many methods as many different types used to call it
>let thunk = DirtyThunk(delegate)
>delegates.append(thunk)
>}
> 
> This solution works - however we can never retrieve the original object any 
> more as it is not referenced. The implementation of the “thunks” are also 
> painful a bit. The methods are captured only by the name of the methods 
> without the parameters so leads the problem if different methods have the 
> same prefix.
> 
> I tried to solve using ‘Any’ to reference the delegates but then cannot cast 
> to a proper type to call them.
> 
> 
> Do one know any better solution?

There's a more complex way to write a "type-erased wrapper" (the preferred 
Swift term for a thunk). The trick is that you use a base class which is *not* 
generic on the actual type, plus a derived class which *is* generic on the 
actual type, to hold the actual instance. For example:

private class SomeProtocolBox {
private init() {}

func someMethod(withElement: SomeElementType) { fatalError() }
}

private class ConcreteSomeProtocolBox: 
SomeProtocolBox {
var value: SomeProtocolType

init(_ value: SomeProtocolType) {
self.value = value
}

override func someMethod(withElement: SomeElementType) {
value.someMethod(withElement: withElement)
}
}

public struct AnySomeProtocol: SomeProtocol {
public typealias ElementType = SomeElementType

private var box: SomeProtocolBox

public init(_ value: T) where T.ElementType == 
SomeElementType {
box = ConcreteSomeProtocolBox(value)
}

func someMethod(withElement: SomeElementType) {
box.someMethod(withElement: withElement)
}
}

With this in place, it's not difficult to support recovering the original 
instance as an `Any`:

extension SomeProtocolBox {
var base: Any { fatalError() }
}
extension ConcreteSomeProtocolBox {
override var base: Any { return value }
}
extension AnySomeProtocol {
var base: Any { return box.base }
}

It's also more efficient than the closure-based solution, since it doesn't need 
a separate closure (and context) for each method it indirects.

There's some hope that eventually all of this will be unnecessary and you'll be 
able to use protocols with associated types in more places, possibly with some 
special casting syntax to make sure you're passing the proper type. No idea if 
or when that will actually be implemented, though.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] open/public protocol with not overridable default implementation in the future?

2016-09-20 Thread Brent Royal-Gordon via swift-users
> I always wanted a way to make some protocol default implementations not 
> overridable. Now Swift 3 got open vs. public behavior for classes. (Hopefully 
> the inconsistency will be fixed soon and we’ll get open protocols as well.)
> 
> Imagine this scenario with open/public protocols.
> 
> // Module A
> // `open protocol` means that in a diff. module I'll
> // be able to conform to that protocol
> open protocol Proto {}
> 
> extension Proto {
>  // shouldn't this mean that the variable is not overridable  
>  // from a different module? :)
>  public var foo: Int { return 42 }
> }
> 
> // Module B
> struct A : Proto {
> // can I or can I not override `foo` from here?
> }
> 
> I wonder if my thinking is correct here, or do we need something else to make 
> extensions with default implementation to be fixed and not overridable?

Currently, a declaration of `A.foo` would not *override* `Proto.foo`, it would 
*shadow* it. Using `foo` on a variable of type `Proto` will always use 
`Proto`'s implementation. That's why `A.foo`'s declaration will not have the 
`override` keyword. It's a subtle distinction, but a really important one—if 
you're expecting a call to `Proto.foo` to instead go to `A.foo`, you're gonna 
have a bad time.

Personally, I think this is a bad idea, and I'd like to see the compiler reject 
conformances which cause visible shadowing. But that's a different story. As 
long as we're allowing this shadowing to pass unremarked, it makes sense that 
`public` wouldn't prevent it.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] in-app purchase coding

2016-08-11 Thread Brent Royal-Gordon via swift-users
> On Aug 10, 2016, at 1:10 PM, developer--- via swift-users 
>  wrote:
> 
> I really feel ripped off. I chose to learn to develop for iOS for particular 
> reasons, and now at the end of school, I’m about to graduate without having 
> been taught an obviously vital skill that a developer should absolutely 
> posses.

The vital skill a developer should absolutely possess is being able to sit down 
and—through reading, experimenting, debugging, Googling, and discussing 
specifics with more experienced developers—figure out how something works.

I'm sorry if this comes off as unfriendly, but you can't expect your classes to 
teach you every single API you'll ever use. Many are obscure. Many are on 
different platforms. Many have not even been designed yet. Learning new 
technologies is a vital—indispensable—skill every programmer needs to have. If 
you haven't started to acquire that skill, it's time you get to it.

That's not to say that we can't help you, but you're going to need to get a lot 
more specific. You say you're getting a bunch of errors? Well, pick one of them 
and try to figure out what's causing it. If you have no idea, put the error 
message into Google and see what it says. If you still can't figure it out, 
post here or on Stack Overflow, providing the exact error message and the 
snippet of code it's happening in. (Not the whole file, just the few lines 
around the line with the error, and anything else you think we might need to 
see to understand them.)

If you think the problem is more conceptual—if you feel like the issue is not 
with the exact code you've written, but rather that you have no idea how in-app 
purchase is supposed to work—then take a step back from your code and look for 
samples, tutorials, or books on the subject. Apple might not have anything 
specifically for in-app purchases (or their sample might be in Objective-C), 
but I'm sure somebody does. Don't read them to find code to copy; read them to 
understand how they work. And then once you do understand, bring that 
understanding back to your code.

But the most important part is an attitude change. Development is not a 
mechanical skill; your job is not merely to do the specific programming tasks 
you've been taught, but also to figure out how to perform new tasks—perhaps 
even tasks *nobody* has ever done before. Writing code that uses this API is 
not your teacher's job, or DTS's job, or this mailing list's job. It's *your* 
job.

The rest of us are here to help, but this is the job you signed up for. Roll up 
your sleeves and get to work.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] What are these types with regular expressions?

2016-08-07 Thread Brent Royal-Gordon via swift-users
> On Aug 6, 2016, at 5:25 AM, 晓敏 褚 via swift-users  
> wrote:
> 
> And when I try to use range to get a substring, I got a Range, but the 
> substring:with: method requies a Range. But there is no way I could 
> find any information about the type(or protocol?) Index, and passing a Int 
> fails.
> What are they, and how can I work with them?

"The Swift Programming Language" discusses this in more detail, but briefly: 
String indexing is much more complicated than NSString might make you think. 
For instance, the character  is spread across two "indices", because it is in 
the Supplementary Ideographic Plane of Unicode. Moreover, there are actually 
several different mechanisms that can make a single "character" actually take 
up multiple indices. To model this, a Swift String offers several views 
(`characters`, `unicodeScalars`, `utf16`, and `utf8`), each of which handles 
indices in a different way. In Swift 2, each of these has its own `Index` type; 
I believe the plan was for Swift 3 to use one Index type shared between all 
views, but I'm not sure if that change will make the release version.

`NSString`, on the other hand, uses bare `Int`s interpreted a UTF-16 indices. 
So the way to convert is to translate the `Int` into a `String.UTF16Index`, and 
then if you want to go from there, further translate the `UTF16Index` into 
`String.Index`. (This second step can fail if, for instance, the `UTF16Index` 
points to the second index within .) You can do that with an extension like 
this one:

// Swift 3:
extension String.UTF16View {
func convertedIndex(_ intIndex: Int) -> Index {
return index(startIndex, offsetBy: intIndex)
}
func convertedRange(_ intRange: Range) -> Range {
let lower = convertedIndex(intRange.lowerBound)
let offset = intRange.upperBound - intRange.lowerBound
let upper = index(lower, offsetBy: offset)

return lower ..< upper
}
}
extension String {
func convertedIndex(_ intIndex: Int) -> Index? {
let utfIndex = utf16.convertedIndex(intIndex)
return utfIndex.samePosition(in: self)
}
func convertedRange(_ intRange: Range) -> Range? {
let utfRange = utf16.convertedRange(intRange)
guard let lower = utfRange.lowerBound.samePosition(in: 
self),
let upper = 
utfRange.upperBound.samePosition(in: self) else {
return nil
}
return lower ..< upper
}
}

// Swift 2:
extension String.UTF16View {
func convertedIndex(intIndex: Int) -> Index {
return startIndex.advancedBy(intIndex)
}
func convertedRange(intRange: Range) -> Range {
let lower = convertedIndex(intRange.startIndex)
let offset = intRange.endIndex - intRange.startIndex
let upper = lower.advancedBy(offset)

return lower ..< upper
}
}
extension String {
func convertedIndex(intIndex: Int) -> Index? {
let utfIndex = utf16.convertedIndex(intIndex)
return utfIndex.samePositionIn(self)
}
func convertedRange(intRange: Range) -> Range? {
let utfRange = utf16.convertedRange(intRange)
guard let lower = 
utfRange.startIndex.samePositionIn(self),
let upper = 
utfRange.startIndex.samePositionIn(self) else {
return nil
}
return lower ..< upper
}
}

Use it like this:

let range: Range = …

// If you want to use String.UTF16Index:
let convertedRange = string.utf16.convertedRange(range)
print(string.utf16[convertedRange])

// If you want to use String.Index:
if let convertedRange = string.convertedRange(range) {
print(string[convertedRange])
}
else {
print("[Invalid range]")
}

Hope this helps,
-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Set size of byte array

2016-08-05 Thread Brent Royal-Gordon via swift-users
> On Aug 4, 2016, at 11:42 PM, KS Sreeram via swift-users 
>  wrote:
> 
> I’m trying to initialize a byte-array efficiently with minimal copying with 
> the following steps:
> 
> 1. Create an empty byte array.
> 2. Reserve sufficient capacity in the array.
> 3. Use mutable pointers into the array to fill in the data.
> 4. The actual size that was filled is known only after it is filled in.
> 5. I would like to set the size of the array to the actual size.
> 
> I couldn’t find any methods for doing the last step. Is there a way to do 
> this?

I don't believe this is possible with an Array; the only way to work with 
uninitialized memory is with an UnsafeMutablePointer.

The simplest solution is probably to load the data into an allocated chunk of 
memory with an UnsafeMutablePointer and then create an NSData object to keep 
track of its lifetime. The `init(bytesNoCopy:length:deallocator:)` initializer 
can be used to make sure it deallocates the memory correctly.

If you don't *need* to use mutable pointers to fill the array, however, a 
custom SequenceType might be a better option. For instance, you could write a 
type like this which returns the data a byte at a time:

struct MyDataSource: SequenceType, GeneratorType {
...

init(...) {
...
}

var initialCapacity: Int {
...guess at the capacity...
}

mutating func next() -> UInt8? {
...determine and return the next byte, or nil if you've 
reached the end...
}
}

Then you can write something like this:

var source = MyDataSource(...)
var array: [UInt8] = []
array.reserveCapacity(source.initialCapacity)
array.appendContentsOf(source)

And, et voila, `array` is full of your bytes. From what I can tell, if the 
capacity is already there, the standard library effectively uses a loop as 
tight as any you could hope for:

let base = buffer.firstElementAddress

while (nextItem != nil) && count < capacity {
  (base + count).initialize(to: nextItem!)
  count += 1
  nextItem = stream.next()
}
buffer.count = count

So I suspect a custom SequenceType will perform much better than you would 
first guess.

Hope this helps,
-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] non-mutating func that still mutates a struct, compiler not aware

2016-08-04 Thread Brent Royal-Gordon via swift-users
> On Aug 4, 2016, at 1:25 AM, Raphael Sebbe via swift-users 
>  wrote:
> 
> My understanding is that the compiler doesn't make a real copy in the acopy = 
>  self instruction, and then provides that contents to the mx_gels_ function 
> which modifies the memory contents.
> 
> 
> public func solve(rhs b: Matrix) -> Matrix? {
>   // ...
>   var acopy = self
>   // ...
> 
>   T.mx_gels_(, , , , 
> UnsafeMutablePointer(acopy.values), , 
> UnsafeMutablePointer(x.values), , UnsafeMutablePointer(workspace), 
> , );
>   
>   // ...
>   }
> 
> 
> Is this expected? I mean, I can force a real copy of course, but value 
> semantics would suggest the code above is correct and wouldn't need that. 
> Shouldn't the cast trigger the copy somehow? Or is there a better way of 
> expressing this operation? Thx.

The `acopy = self` line only copies the reference to the internal buffer. 
However, converting the array into a pointer will—or at least, if done 
properly, *should*—force the array to create and switch to using a unique copy 
of its buffer in preparation for writes through the UnsafeMutablePointer. I 
believe that happens here: 


(I say "should" because I'm not sure you're actually creating those pointers 
correctly. I believe you ought to be able to just say `` and 
``, and that should be a more reliable way to do it.)

-- 
Brent Royal-Gordon
Architechies

___
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 Brent Royal-Gordon via swift-users
> On Aug 2, 2016, at 8:44 PM, Tino Heth via swift-users  
> wrote:
> 
> * yes, an embedded "address"-struct would be an alternative — but copy & 
> paste or writing everything in assembler is an alternative as well ;-)

The other alternative for this particular case is a Person protocol which 
Customer and Employee both conform to. Protocols currently require you to 
redeclare their properties, but we could add a feature to change that if there 
was a strong enough justification.

-- 
Brent Royal-Gordon
Architechies

___
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 Brent Royal-Gordon via swift-users
> On Aug 1, 2016, at 5:28 PM, Rick Mann via swift-users  
> wrote:
> 
> It sure seems natural.
> 
> Is there some reason the language can't allow a sub-struct to add member 
> variables, such that the whole is treated like a contiguous set of members?

Structs are very "raw":

* There is no extra overhead for metadata; objects have a header which includes 
a type reference, a reference count, and various other housekeeping bits.

* Structs have a fixed size; there's no space for additional fields.

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

This makes them small and fast, which are necessities if we're to use them to 
implement fundamental data types like `Int`. Basically, if structs weren't 
already so "primitive", 

> 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.

Keep in mind that you have three options—not just one—if you want to increase 
the capabilities of a struct:

1. Composition, as you seem to have already evaluated.

2. Extensions to add extra methods or computed properties to an 
existing struct.

3. Protocols and retroactive modeling if you want to be able to handle 
instances of both types with a single piece of code.

You don't mention what it is you want to do, but it's possible that one of 
these will address your needs.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Serial DispatchQueue and documentation?

2016-08-01 Thread Brent Royal-Gordon via swift-users
> On Aug 1, 2016, at 3:15 PM, Jon Shier via swift-users  
> wrote:
> 
> Swifters:
>   It seems that in Xcode 8 beta 4, DispatchQueueAttributes was refactored 
> to be DispatchQueue.Attributes but in the process lost the .serial attribute. 
> How are we to create serial queues now? On a related note, where can we find 
> the latest documentation for the Dispatch overlay? The Apple docs don’t have 
> any actual usage information yet, so is there any documentation actually 
> generated from code, like swiftdoc.org does for the standard library? 
>   Here’s a link to the Apple dev forum regarding the same DispatchQueue 
> issue: https://forums.developer.apple.com/thread/53270

Isn't `serial` the default? If so, you should just be able to pass an empty 
array literal (`[]`) or omit the `attributes` parameter entirely.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Possible swift 3 method rewrite issue with NSRequestConcreteImplementation ?

2016-07-19 Thread Brent Royal-Gordon via swift-users
> On Jul 19, 2016, at 8:20 AM, John Spurlock  wrote:
> 
> Is there anything I can do in the meantime as a swift-only workaround to fix 
> my custom NSCoder?

Horrible possibility: `class_addMethod()` *is* available from Swift. You might 
be able to do some old-fashioned runtime hackery like:

class MyCoder: NSCoder {
@objc func __encodeInt(_ intv: Int, forKey: String) { ... }

override class func initialize() {
super.initialize()

// XXX I think this needs to be guarded against being 
run more than once.
let donor = class_getInstanceMethod(self, 
#selector(__encodeInt(_:forKey:)))
class_addMethod(self, Selector("encodeInt:forKey:"), 
method_getImplementation(donor), method_getTypeEncoding(donor))
}

...
}

-- 
Brent Royal-Gordon
Architechies

___
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 Brent Royal-Gordon via swift-users
> On Jul 18, 2016, at 11:44 AM, Karl via swift-users  
> wrote:
> 
> Also, as interesting as that may be, I’m also curious what to do in the 
> general case for types without magic compiler optimisations.

Wait for Swift 4, apparently: 
https://github.com/apple/swift-evolution/blob/master/proposals/0073-noescape-once.md#rationale

Or use a class method, or two-phase initialization, or some other trick to get 
around this limitation.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Possible swift 3 method rewrite issue with NSRequestConcreteImplementation ?

2016-07-18 Thread Brent Royal-Gordon via swift-users
> Hi Tony - when I add that attribute, I get an error at compile-time:
> Objective-C method has a different selector from the method it overrides 
> ('encodeInt:forKey:' vs. 'encodeInteger:forKey:')
> 
> If I update to encodeInteger:forKey as the fix describes, it compiles, but 
> I'm getting the same original problem at runtime.  i.e. "encodeInt:forKey: 
> only defined for abstract class"
> 
> Any other ideas?  See the same thing over there?  You should be able to paste 
> that into a new swift 3 test.

If you look at the NSCoder documentation, you'll see 25 methods in the Swift 
version of the "Encoding General Data" section, and 27 (non-deprecated) in the 
Objective-C version. `-encodeInt:forKey:` has no Swift equivalent. I'm not sure 
what the other missing method is.

I think this is probably a bug or design oversight, and I'd recommend you file 
a radar against Foundation. If this is a primitive method for NSCoding, it 
needs to be accessible from Swift.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Equality is broken, isn't it?

2016-07-06 Thread Brent Royal-Gordon via swift-users

> On Jul 6, 2016, at 9:54 AM, Alexey Komnin via swift-users 
>  wrote:
> 
> Here is the code:
> 
>let a: String = "abc"
>let b: NSString = "abc"
> 
>assert(a == b)
>assert(a.hashValue == b.hashValue, "a.hashValue(\(a.hashValue)) !=
> b.hashValue(\(b.hashValue))")

There's no problem if you use generics to select a single Hashable 
implementation:

import Foundation

func assertHashableConsistent(a: T, b: T) {
assert(a == b, "a and b are equal")
assert(a.hashValue == b.hashValue, "a and b have the same hash 
value")
}

assertHashableConsistent(a: "abc" as String, b: "abc" as NSString)

The problem is that, in your case, `a` uses `NSString`'s `Hashable` in the 
first line, but `String`'s `Hashable` in the second line. The 
`assertHashableConsistent(a:b:)` function, on the other hand, ensures that `a` 
uses `NSString`'s `Hashable` in both lines.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Cannot invoke 'stride' with an argument list of type '(from: Int, to: Int, by: Int)'

2016-07-05 Thread Brent Royal-Gordon via swift-users
> On Jul 5, 2016, at 11:39 AM, Adriano Ferreira via swift-users 
>  wrote:
> 
> Do you think this should be filed as a bug or just wait until the Swift team 
> removes the old stride method?

The old method is probably a stub that tells the fix-its how to find the new 
one, so it's there to stay. File a bug.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Collection's "past the end" endIndex

2016-07-02 Thread Brent Royal-Gordon via swift-users
> On Jul 2, 2016, at 11:40 AM, Jens Alfke via swift-users 
>  wrote:
> 
> It’s hard to handle empty collections, otherwise. If endIndex were the last 
> valid subscript, then in an empty collection what would its value be? 
> Presumably it would have to point to one before the start, which is rather 
> weird because that’s never a valid index (in an int-indexed collection it 
> would be negative.) Even worse, endIndex is never reachable from startIndex, 
> so an iteration can’t simply continue until it reaches the endIndex. Instead 
> the Indexable type would have to implement a (cheap, constant-time) >= 
> operator to use as the test for an iteration.

To add to Jens's point, all of this adds up to simplify iterating over a 
collection with a `while` loop (remember, all loops are `while` loops 
eventually):

// Without invalid endIndex:

var index = c.startIndex
var done = c.isEmpty

while !done {
...

if index == c.endIndex {
done = true
}
else {
index = c.index(after: index)
}
}

// With invalid endIndex:

var index = c.startIndex
while index != c.endIndex {
...
index = c.index(after: index)
}

There are even more reasons than this one. For instance, having `endIndex` be 
past the end means that `insert(_:at:)` can insert after the last element of 
the collection, in addition to before any other element. It gives other 
range-based APIs similar powers. It means that `distance(from: startIndex, to: 
endIndex)` is the count of the elements in the collection. It means you 
natively use `Range` instead of `ClosedRange`, which (perhaps 
counterintuitively) is easier to reason about. And so on.

The manuscripts of famed computer scientist Edsger Dijkstra include a little 
note about ranges and zero-based indexes; its logic is intimately related to 
this: https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] How do I find really detailed information about changes?

2016-06-22 Thread Brent Royal-Gordon via swift-users
> I'm now trying to find why, along with changing from NSCalendar to Calendar, 
> the .components are optional. I can't find any mention of it, and I'm not 
> sure in what situation minutes or hours could be nil and how I should guard 
> against it.

In Objective-C, these properties can be `NSUndefinedDateComponent`. In Swift, 
that's represented as `nil` instead.

Essentially, this happens when you don't request a particular date 
component—for instance, when you say `gregorian.components([.year, .month, 
.day], fromDate: date)`, `hours` and `minutes` will be `nil`. In Objective-C, 
they would have been `NSUndefinedDateComponent`.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Documentation for #selector

2016-06-20 Thread Brent Royal-Gordon via swift-users
> Help - I've been trying to find documentation for #selector but drawn a 
> complete blank ... would appreciate if someone could point me towards 
> anything which may be available ...

The Swift 3 beta version of "The Swift Programming Language" touches on it in 
the "Language Reference" section. For a more in-depth discussion, the Swift 3 
version of "Using Swift with Cocoa and Objective-C" has a section about it: 
https://itunes.apple.com/us/book/using-swift-cocoa-objective/id1002624212?mt=11

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] GCD : Getting current dispatch queue name with swift 3

2016-06-19 Thread Brent Royal-Gordon via swift-users
> I'm migrating one of my project to Swift 3 (xcode 8 beat release).
> Most of the changes were pretty strait-forward, but I have one required 
> change that is still blocking me :
> In my code, I retrieve the current dispatch  queue name using that code :
> 
> let queueName = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)
> 
> DispatchQueue objects do have a label attribute, but I cannot find how to get 
> the current dispatch queue.
> What would be the equivalent of it in swift 3 ?
> 
> Any idea would be very welcome :-).

Here's a horrible workaround:

extension DispatchQueue {
class var currentLabel: String {
return String(validatingUTF8: 
__dispatch_queue_get_label(nil)) 
}
}

But I think this is a hole in the current design. I'm not sure if it's an 
*intentional* hole or not; the concept of a "current queue" in general is a bit 
squirrelly.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Swift 3 Release

2016-06-19 Thread Brent Royal-Gordon via swift-users
> We would like to migrate our iOS apps to Swift 3 and iOS 10. However, we also 
> want to be able to submit iOS 10 apps when iOS 10 is released.
> 
> Does anyone know if Swift 3 will be released alongside iOS 10? Can we submit 
> Swift 3 apps to the App Store when iOS 10 goes GM?

It seems unlikely, and would be wholly unprecedented, for any Apple OS to go GM 
before the developer tools targeting it.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] See documentation comment for discussion

2016-06-17 Thread Brent Royal-Gordon via swift-users
> I've previously used myString[0...1] to get the first character of a string.

I'm not sure how, because this has never worked in Swift. Strings use opaque 
indices which specifically prevent you from doing this, so you have never been 
able to subscript a string with integers or ranges of integers. It's done this 
way because indexing into a Unicode string intrinsically requires walking 
through the data structure and counting characters one at a time; the lack of 
integer indices is meant to force you to explicitly write `index(after:)` or 
`index(_:offsetBy:)` (formerly `successor()` or `advancedBy(_:)`) in your code 
to make this cost obvious.

> What documentation is this referring to? There's no right-click definition 
> available, nothing in Navigator, and Google fails to turn up anything.

The standard library includes definitions of these subscripts which are meant 
to direct you to documentation explaining why they're not supported, but these 
definitions don't show up in the generated interfaces. Presumably Xcode is 
removing all APIs marked "unavailable". The doc comment it's trying to direct 
you to is here 
:

  /// Subscripting strings with integers is not available.
  ///
  /// The concept of "the `i`th character in a string" has
  /// different interpretations in different libraries and system
  /// components.  The correct interpretation should be selected
  /// according to the use case and the APIs involved, so `String`
  /// cannot be subscripted with an integer.
  ///
  /// Swift provides several different ways to access the character
  /// data stored inside strings.
  ///
  /// - `String.utf8` is a collection of UTF-8 code units in the
  ///   string. Use this API when converting the string to UTF-8.
  ///   Most POSIX APIs process strings in terms of UTF-8 code units.
  ///
  /// - `String.utf16` is a collection of UTF-16 code units in
  ///   string.  Most Cocoa and Cocoa touch APIs process strings in
  ///   terms of UTF-16 code units.  For example, instances of
  ///   `NSRange` used with `NSAttributedString` and
  ///   `NSRegularExpression` store substring offsets and lengths in
  ///   terms of UTF-16 code units.
  ///
  /// - `String.unicodeScalars` is a collection of Unicode scalars.
  ///   Use this API when you are performing low-level manipulation
  ///   of character data.
  ///
  /// - `String.characters` is a collection of extended grapheme
  ///   clusters, which are an approximation of user-perceived
  ///   characters.
  ///
  /// Note that when processing strings that contain human-readable
  /// text, character-by-character processing should be avoided to
  /// the largest extent possible.  Use high-level locale-sensitive
  /// Unicode algorithms instead, for example,
  /// `String.localizedStandardCompare()`,
  /// `String.localizedLowercaseString`,
  /// `String.localizedStandardRangeOfString()` etc.


-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] #selector with Swift 3?

2016-06-17 Thread Brent Royal-Gordon via swift-users
> Tried that too, it causes another error:
> 
>/Developer/SwiftNEC 3/SwiftNEC/CardViews.swift:139:28: Expected ':' after 
> 'case'

Huh, that's really strange. This syntax, which should be equivalent, causes a 
compiler crash:

case (#selector(showRescale))?:

So does the slightly-more-shorthanded version:

case .some(#selector(showRescale)):

I'd file another bug about this, this time in the Swift open-source bug tracker 
at .

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] #selector with Swift 3?

2016-06-17 Thread Brent Royal-Gordon via swift-users
> I was asked to try out the latest betas of Cocoa to check if a SceneKit bug I 
> reported has been fixed. As part of this I decided to try an update to Swift 
> 3. I've run into a number of minor issues, but one has me frustrated. In my 
> menu validate method, I have:
> 
>   switch menuItem.action {
>   case #selector!(showRescale) :
> 
> This worked fine in 2.2, but now it complains that it expects a ( after 
> #selector. Removing the ! fixes that problem, but now returns an error that 
> there's a missing !, which it inserts to cause the original error again. I 
> also tried placing it after the ()'s, and now it complains that it's 
> expecting the :
> 
> Does anyone know the proper Swift 3 syntax for this?

tl;dr: Write this instead:

case #selector(showRescale)?:

The explanation:

In Swift 2, Selectors could *always* be nil, even when they weren't optional. 
The same was true of UnsafePointer and a few other types, and it wasn't great. 
So in Swift 3, we've changed these types so they now can only be nil if they're 
optional.

Because of this change, the type of `NSMenuItem.action` changed from `Selector` 
to `Selector?`. That means the patterns in your `switch` statement need to look 
like:

case Optional.some(#selector(showRescale)):

Which you can specify in a pattern match (like a case statement) using the 
convenient trailing-question-mark syntax I showed above:

case #selector(showRescale)?:

The Swift 3 migrator should have generated this code, so you've probably 
encountered a bug. It would help them if you could create a small example 
project and file a bug report at . (The migrator 
is closed source.)

Hope this helps,
-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] SequenceType vs. CollectionType

2016-06-17 Thread Brent Royal-Gordon via 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, but the original post said:

>> I'm not imagining an implementation that does any buffering

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Swift 3.0 Preview 1 Linux release and Foundation

2016-06-14 Thread Brent Royal-Gordon via swift-users
> Today I noticed that Linux release and macOS release is quite different.
> I thought that Linux and macOS release will have Foundation in it, but
> Linux seems missing this part.
> Maybe I'm missing something but structures like "Data" (NSData
> equivalent)) are missing on Linux (Ubuntu 14).

About 15 minutes after you posted, Tony Parker announced that a branch with 
this work will be published later today, and they're hoping to merge it in the 
next couple weeks. So hang on!



-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] inout params seem to have undefined behavior

2016-06-11 Thread Brent Royal-Gordon via swift-users
> My recollection is that in Swift the subscript operator (`arr[2]` in this 
> case) can refer to the setter xor the getter, but not both within the same 
> statement.

Quite to the contrary. Rather than using the setter directly, Swift often uses 
`materializeForSet`, a combined get-and-set operation which is much more 
efficient, particularly when assigning directly into arrays. To keep from 
having to use very slow access all the time, it imposes a rule (which is not 
and cannot be enforced by the compiler) that you can't hold two mutable 
references to overlapping storage simultaneously, or they may do strange things 
like lose some of the writes you make.

Here's an old design document discussing some things in this area: 

 I'm not sure how authoritative it is, but it might give you an idea of what's 
going on.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] file io in Swift 2.2 for Linux (would like to be pointed in the right direction)

2016-06-05 Thread Brent Royal-Gordon via swift-users
> Looks good, but you'll want some error handling. There's no clean way to 
> integrate it with Generator because the protocol doesn't allow the 
> implementation to throw, unfortunately. (I've run into the same problem 
> building a Generator around a database query.) I think the best solution is 
> to add a property that returns the NSStream.streamError, or a checkError() 
> method that throws the current error if any, and have the caller use those at 
> the end of the iteration.

You can do better.

extension NSInputStream {
// I will assume you already have a byteGenerator method (which 
you can use with a for loop)
// with a checkError() method (which throws if the generation 
terminated due to an error). However, 
// you've made these private, and will use them to implement 
this safe public API.
public func withByteGenerator(blockSize: Int = 1024, 
iterate: @noescape (NSInputStream.ByteGenerator) throws -> R) throws -> R {
let generator = byteGenerator(blockSize: blockSize)
let result = iterate(generator)
try generator.checkError()
return result
}
}

Now you write:

guard let stream = NSInputStream(fileAtPath: path) else {
…
}
try stream.withByteGenerator {
// XXX This would all be more complicated if CharacterGenerator 
can throw, too.
for (i, line) in LineGenerator(source: 
CharacterGenerator(source: $0, decoder: UTF8())).enumerate() {
print("\(i+1): \(line)")
}
}

(I'm assuming that these generators take their almost-automatic Sequence 
conformance, of course.)

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Discrepancy between sharing internal Swift symbols with Obj-C when in an app vs a framework target

2016-06-04 Thread Brent Royal-Gordon via swift-users
> I ran into a major hurdle this week that basically stopped my work in
> its tracks. I've been working on moving a large codebase from an iOS app
> target to a framework target, since we have the same code in multiple
> app targets and it is problematic to have to remember to add new code to
> every single app target when they can all just share a framework.

To be clear: Are you having trouble making the Objective-C and Swift inside 
your framework talk to each other, or the Objective-C outside your framework 
talk to the Swift inside your framework?

If it's the latter, then I agree with Jens that this is "works as intended", 
and you're just going to have to spend some time pasting `public` into your 
code in a lot of places. But if you're being forced to make Swift APIs public 
so you can use them from Objective-C *inside* the framework, that might be 
something worth talking about.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] NSURLComponents - setting scheme bug?

2016-05-25 Thread Brent Royal-Gordon via swift-users
>> var components = NSURLComponents(string: "apple.com")!
> 
> That’s incorrect, and I’m surprised the method didn’t fail, since “apple.com” 
> is not a valid URL. Try initializing an empty object and then setting its 
> host to “apple.com”.

"apple.com" is a perfectly valid relative URL, and that's how NSURLComponents 
interpreted it:

  1> import Foundation
  2> let comps = NSURLComponents(string: "apple.com")!
  3> comps.description
$R1: String = " {scheme = (null), user = (null), 
password = (null), host = (null), port = (null), path = apple.com, query = 
(null), fragment = (null)}"

Note that `host` is nil, but `path` is "apple.com".

Your suggestion to initialize an empty `NSURLComponents` and set the `host` 
field is a good one, however.

-- 
Brent Royal-Gordon
Architechies

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


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

2016-05-17 Thread Brent Royal-Gordon via swift-users
> I have some ID types that are simple ints coming back from a database.  I 
> wanted to improve type safety so I don’t accidentally assign product IDs to 
> user IDs, etc.  I want to be able to print it and use it as a dictionary key. 
>  So it is a trivial wrapper of Int.  E.g.
> 
> struct CustomerID: Hashable, CustomStringConvertible {
> init(_ value: Int) { self.value = value }
> let value: Int
> var hashValue: Int { return value.hashValue }
> var description: String { return String(value) }
> }
> 
> func ==(lhs: CustomerID, rhs: CustomerID) -> Bool {
> return lhs.value == rhs.value
> }

Rather than going the protocol route, how about a generic type?

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

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

protocol Identifiable {
var id: ID? { get }
}

struct Customer: Identifiable {
var id: ID?
}


-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Swift 3.0

2016-04-17 Thread Brent Royal-Gordon via swift-users
> The app builds fine.   Running the app gives me errors such as "Must 
> implement numberOfRowsInTableView: and 
> tableView:objectValueForTableColumn:row:” when the swiftified version 
> "numberOfRows(in tableView: NSTableView) -> Int” and the required methods to 
> support a view based table exist -- unless I got them wrong.  

You may need to give the Objective-C versions of the method names in @objc(foo) 
attributes.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Generators vs. errors

2016-04-13 Thread Brent Royal-Gordon via swift-users

> On Apr 12, 2016, at 11:53 AM, Jens Alfke via swift-users 
>  wrote:
> 
> What should one do, when implementing a Generator, if the underlying data 
> source can experience errors? Generator.next isn’t allowed to throw, only to 
> return nil at the end of the sequence.
> 
> The only idea I can think of is to add an `error` property to my Generator 
> implementation, and request that the caller check it after the iteration 
> ends, and/or a `checkForError()` method that can throw an error if there is 
> one:
>   var q: Query = db.query(…)
>   for (row in q) { … }
>   q.checkForError()
> 
> As the example implies, this problem comes up when creating Swift bindings 
> for database iterators/cursors. Generator is the obvious protocol to 
> implement, especially since without it you don’t get the idiomatic for/in 
> loop, but the `next` method does have to hit the database, so it has the 
> possibility of I/O errors.

What I might do is use a block to make sure you can't forget the 
`checkForError()` method:

let query = db.query(…)
try query.withResults { results in
// `results` is a SequenceType you can iterate over.
// You can only get at it by calling `withResults` on a Query, 
and it becomes invalid once 
// `withResults` returns.
// If `results` encounters an error, it terminates early.
for row in results {
// Use your row
}
}

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Trouble constraining a generic type in an extension

2016-04-13 Thread Brent Royal-Gordon via swift-users
> I *think* the feature you’re trying to use is on the todo list for Swift 3, 
> but the last time I said that, I was completely wrong. The swift-evolution 
> mailing list probably has more information.

I think it's on the list of things they'd like to do to generics in the future, 
but it's a very long list and they might not get to that particular one.

In short, though, my understanding is that there is no principled reason for 
this limitation; it simply isn't supported yet.

-- 
Brent Royal-Gordon
Architechies

___
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-21 Thread Brent Royal-Gordon via swift-users
>> Is there a way to find out how big an object is on the heap?
> 
> Yes, the sizeof() function.

I think he's asking for the size of the object itself. For a reference type, 
`sizeof()` gives you the size of the reference.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Generic factory method and type inference

2016-03-20 Thread Brent Royal-Gordon via swift-users
> final class Something {
> 
> let value: T
> 
> init(initial: T) {
> value = initial
> }
> 
> }
> 
> extension Something {
> 
> class func zip(a: A, _ b: B) -> Something<(A, B)> {
> let initial = (a, b)
> return Something<(A, B)>(initial: initial)
> }
> 
> }
> 
> How come I can’t call zip without explicitly specifying return type?
> 
> // ERROR: Cannot invoke `zip` with an argument list of type `(Int, Int)`
> let y = Something.zip(1, 2)
> 
> // OK: Works but it’s unacceptable to require this on caller's side
> let x = Something<(Int, Int)>.zip(1, 2)

The reason you're seeing this is that there's nothing in this call:

let y = Something.zip(1, 2)

That tells Swift what `T` should be. The return type of the `zip` method is not 
connected to T; you can actually put any random type in the angle brackets 
after Something:

let y = Something.zip(1, 2)

Unfortunately, Swift doesn't currently have the features needed to properly 
connect `T` to the return type. If the language were more sophisticated, you 
could say something like this:

extension Something where T == (A, B) {
class func zip(a: A, _ b: B) -> Something {
let initial = (a, b)
return Something(initial: initial)
}
}

But for now, you'll have to make do with this horrible hack, which works by 
meaninglessly reusing the T type parameter:

extension Something {
class func zip(a: T, _ b: B) -> Something<(T, B)> {
let initial = (a, b)
return Something<(T, B)>(initial: initial)
}
}

Hope this helps,
-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] [swift-dev] Collection underestimatedCount() does _?

2016-03-19 Thread Brent Royal-Gordon via swift-users
> You gave cases for which `underestimatedCount()` is used:
>> For sequences with easily-calculated counts, this should give us a size 
>> that's just right. For sequences where they can kind of estimate the right 
>> count (for instance, if you're decoding a fixed-size buffer of UTF-8 bytes, 
>> and you know how many bytes there are but not exactly how many characters 
>> they'll decode to), it will get us at least part of the way there. For 
>> sequences whose size is completely unknown, it won't help but it won't hurt 
>> much either.
> 
> CC’ing swift-dev, I’m wondering:
> Was there a reason `underestimatedCount()` was chosen for Sequence instead of 
> `estimatedCount()`. I suppose an overestimate would be bad for iterating 
> `0.. `0.. 
> Does anything depend on an underestimate of Sequence count? And if not, would 
> it be better to be less restrictive when asking a Sequence for a size 
> estimate?
> Since the exact count is returned for collections, the name also isn’t very 
> precise.

Actually, the code samples I gave you *do* subtly depend on underestimatedCount 
being an underestimate, because the initial fast loop force-unwraps the element 
returned by `next`. If the count is an overestimate, that force unwrap will 
fail. You can see it in my example:

// Load all the fast elements
for _ in 0..https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Collection underestimatedCount() does _?

2016-03-19 Thread Brent Royal-Gordon via swift-users
> 1: that the standard API requires that 
> every Sequence type can be instantiated so as to replicate the contents of 
> another? The whole value of Sequence to the examples is that it should be 
> impossible. 

No, it's the other way around. It should be possible to copy any (finite) 
Sequence into an Array, or any other type that declares it can be instantiated 
from a Sequence. The source of a Sequence could be anything, including data 
from external sources outside the program's control (like your /dev/random or 
wireless data examples).

> 2: that the standard API requires of every Sequence that it should serve the 
> expectation of the supposedly-uncoupled API of Array that it is free to 
> buffer the entire contents of any Sequence of the same Element? Need it or 
> not? Bad news for memory and performance.

I believe there's a default implementation on Sequence as well (which would 
return 0), so it functions more as an opt-in mechanism to help Array and 
similar buffering mechanisms estimate the size of the buffer they should 
allocate. (Remember that greedy `map` and friends all use Array, so they all 
use this kind of preallocation logic, too.)

> The answer may be that if the user knows enough to build a Sequence for which 
> laziness is indispensable, she should have better sense than to rely on those 
> two things, required or not.

Yes. Basically, the standard library doesn't model the difference between an 
infinite (or otherwise unwise-to-handle-non-lazily) sequence and a finite 
sequence. It expects you to know whether a particular sequence is going to be 
too large to handle greedily and refrain from doing so.

I consider this a weakness in the standard library and would prefer to see a 
more specific protocol hierarchy, perhaps along the lines of:

/// Represents any series of elements which can be iterated over. 
Something which is 
/// merely Iterable may not be finite and, in any case, is probably not 
wise to use in
/// greedy algorithms. It also may not be possible to iterate over more 
than once.
protocol Iterable {
associatedtype Iterator: InteratorProtocol
func makeIterator() -> Iterator

associatedtype Subset: Iterable where Subset.Iterator.Element 
== Iterator.Element
}
extension Iterable {
// only APIs which are either lazy or operate on the start of 
the series
}

/// Represents any finite series of elements which can be iterated 
over. Something which 
/// is merely a Sequence may not be possible to iterate over more than 
once.
protocol Sequence: Iterable {
func underestimatedCount() -> Int
associatedtype Subset: Sequence where Subset.Iterator.Element 
== Iterator.Element
}
extension Sequence {
// adds greedy and tail-operating APIs, including `count`
}

/// Represents any finite, repeatable series of elements which can be 
iterated over and 
/// looked up by index.
protocol Collection: Sequence {
associatedtype Index: ForwardIndex
associatedtype Iterator = IndexingIterator

var startIndex: Index { get }
var endIndex: Index { get }
subscript(position: Index) -> Iterator.Element { get }

associatedtype Subset: Collection where Subset.Iterator.Element 
== Iterator.Element = Slice
subscript(bounds: Range) -> Subset { get }
}

The `for` loop would take an `Iterable` (since you can exit early from a `for` 
loop), but most APIs that are currently constrained to `Sequence` would not 
change to `Iterable`, unless they happened to operate lazily or only on the 
start of the series. That would keep you from accidentally passing an infinite, 
or might-as-well-be-infinite, sequence to a function that expected to be able 
to read the whole thing.

I might write a swift-evolution proposal to this effect someday, but right now 
the Collection protocols are being reworked and I doubt the relevant people 
have the bandwidth to work on Sequence too.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Collection underestimatedCount() does _?

2016-03-19 Thread Brent Royal-Gordon via swift-users
>> I might have missed something since a lot of the results are for tests 
>> 
>> But why would `underestimatedCount` ever be used instead of `count`? Don’t 
>> most collections have O(1) `count` anyway?
> 
> Hi Will,
> 
> This API comes from Sequence, which does not have a count that you can
> inspect without possibly consuming the sequence.

To add some color:

A sequence merely says that it has a bunch of elements and you can walk through 
them. It does *not* promise several important things:

* That you can get the elements in the sequence more than once
* That it knows the number of elements in the sequence and can quickly return 
them
* That you can get the number of elements in the sequence without walking 
through and counting them one by one

This adds up to an ugly conclusion: With just a sequence, it is impossible to 
efficiently discover the count, and doing so might destroy the sequence.

That's obviously not so great. In particular, it's not so great when you want 
to load a sequence into an array. The simple, naive way is to do this:

// Notionally
struct Array {
init(_ seq: Seq) {
self.init()

for elem in seq {
appendElement(elem)
}
}
}

But this may resize the array several times, which would be very slow. The 
fastest way to do that will be to pre-allocate the exact right number of 
elements so you don't have to keep resizing the array:

// Notionally
struct Array {
init(_ seq: Seq) {
self.init()

reserveCapacity(seq.count)
for elem in seq {

_appendElementQuicklyBecauseWeAlreadyKnowWeHaveTheCapacity(elem)
}
}
}

But `seq.count` might consume the sequence, leaving you unable to add any 
elements. What do we do?

Enter `underestimateCount()`. We can always call `underestimateCount()` and 
size to whatever it says we should be. For sequences with easily-calculated 
counts, this should give us a size that's just right. For sequences where they 
can kind of estimate the right count (for instance, if you're decoding a 
fixed-size buffer of UTF-8 bytes, and you know how many bytes there are but not 
exactly how many characters they'll decode to), it will get us at least part of 
the way there. For sequences whose size is completely unknown, it won't help 
but it won't hurt much either.

So you do this:

// Notionally
struct Array {
init(_ seq: Seq) {
self.init()

let fastCount = seq.underestimateCount()
reserveCapacity(fastCount)

// We'll have to pull elements out manually.
let generator = seq.generate()

// Load all the fast elements
for _ in 0..(source: S) -> _ContiguousArrayBuffer {
  let initialCapacity = source.underestimateCount()
  var builder =

_UnsafePartiallyInitializedContiguousArrayBuffer(
  initialCapacity: initialCapacity)

  var generator = source.generate()

  // FIXME(performance): use _initializeTo().

  // Add elements up to the initial capacity without checking for 
regrowth.
  for _ in 0.. Int {
return numericCast(count)
  }

So you just don't have to worry about this on collections. Implement `count` 
and `understimateCount` will take care of itself.

HTH,
-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Documentation about the overall architecture and functions of the source code -- where is it?

2015-12-24 Thread Brent Royal-Gordon via swift-users
> As a newbie to the source code of Swift, where is the overall white
> paper and function documentation for Swift source code?
> 
> Where are the different files in the pipeline?

This talk from a few months ago includes a very high-level overview of the 
pipeline, though certainly not to the file level: 


Other than that, this kind of basic documentation seems to mainly exist in the 
heads of the Apple folks on the swift-dev list. Unfortunately, most of them are 
on Christmas break right now.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] C/FFI interop

2015-12-23 Thread Brent Royal-Gordon via swift-users
> What are the current facilities planned or in development for FFI? Just as 
> Swift functions can be exposed through @objc, how would I add a similar 
> capability for pure C? Is this what, in fact, module maps might be for?
> 
> I ask since writing high performance native code for dynamic languages is 
> currently done in C, and that’s a pretty bad idea. It would be great for 
> Swift if people started writing native bindings in it as opposed to C, but it 
> probably needs at the least a way to re-export global public functions for 
> C/C++.
> 
> Please let me know if I should take this to swift-dev or swift-evolution!

Swift does not require a foreign function interface—it can directly call C 
functions. Sometimes Swift generates a trampoline to do this, but often not 
even that. The module map basically just tells Swift which headers and binaries 
make up a particular module. There's generally no need to write any bridging 
code—it just works.

There are a few C constructs that Swift doesn't support very well, like unions 
and fixed-size arrays in structs. In those cases, you may need to write some C 
functions which perform the operations that can't be easily expressed in Swift, 
but these functions would just be plain old C with no special bridging 
involved. Similarly, you may choose to write wrappers around some of your 
library's C constructs to make them more convenient to use—for instance, if 
your library has a struct called `foo` and an operation on that struct called 
`frobnicate_foo()`, you might extend `foo` to add a `frobnicate()` method to 
it. But this is purely optional, and you would write it in plain old Swift.

Though Apple's platforms are most commonly associated with Objective-C, there's 
a lot of C over there too. Swift works very well with it—this stuff is fast, as 
transparent as it can be, and frequently exercised.

In short: Just try it. It's pretty easy.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] C/FFI interop

2015-12-23 Thread Brent Royal-Gordon via swift-users
> Option 2. Use this syntax and swift-demangle to figure out the symbols:
> 
> public var badfood:@convention(c)(Int) -> Void = { (i:Int) in
> print(i)
> }

There's an @asmname("foo") directive which can override name mangling, but I 
don't know how useful it is in practice for this kind of thing.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-users] Instantiate Swift class from string

2015-12-10 Thread Brent Royal-Gordon via swift-users
For URL routing, I would currently suggest generating code at compile time. 
Someday you might be able to replace this with a macro-based DSL, but for now, 
I don't see a better option. 

On the bright side, this does mean you'll have actual machine code doing your 
routing, which might be faster than a more dynamic system. 

Sent from my iPad

> On Dec 10, 2015, at 12:22 PM, Matthew Davies via swift-users 
>  wrote:
> 
> I'm building a URL router in which I'd like to pass a controller and a 
> method. I don't want to instantiate all the controllers up front and pass the 
> methods in as closures, nor do I want old controller instances still kept 
> around. If there's a better way, I'm definitely open to any suggestions. I'm 
> still learning the "Swift" way to do things.
> 
> 
> Matthew Davies
> Junior Developer, GeoStrategies
> Director of Photography, OffBlock Films
> 209-225-3246 | 209-202-3284 | daviesg...@gmail.com | daviesgeek.com
>  
> 
> 
>> On Thu, Dec 10, 2015 at 10:47 AM, Dan Stenmark  
>> wrote:
>> NSSelectorFromString() is still available in Swift, and you should be able 
>> to use the result of that in performSelector, though I’m hesitant to support 
>> this approach as it flies in the face of the safety Swift tries to enforce.  
>> I’m curious about your use case here; are you trying to create some kind of 
>> dynamic proxy for a remote object ala NSXPCConnection?
>> 
>> Dan
>> 
>>> On Dec 10, 2015, at 10:33 AM, Matthew Davies via swift-users 
>>>  wrote:
>>> 
>>> Ooh okay. I think that should work for my purposes. Thanks.
>>> 
>>> Somewhat related to this, how would I then call a method dynamically on an 
>>> instance of the class, after instantiating it?
>>> 
>>> ---
>>> class Graph {
>>>   func call(method: String) {
>>> // Something goes here
>>>   }
>>> 
>>>   func redraw() -> String {
>>> return "Redraws"
>>>   }
>>> }
>>> 
>>> let inst = Graph()
>>> inst.call("redraw")
>>> ---
>>> 
>>> 
>>> Matthew Davies
>>> Junior Developer, GeoStrategies
>>> Director of Photography, OffBlock Films
>>> 209-225-3246 | 209-202-3284 | daviesg...@gmail.com | daviesgeek.com
>>>  
>>> 
>>> 
 On Thu, Dec 10, 2015 at 10:18 AM, Daniel Dunbar  
 wrote:
 Note that you can define a protocol which will allow your framework to 
 instantiate the type, and to call methods on instances of that type. If 
 you can structure your code in this fashion, it can be very elegant in 
 that it doesn't require factory functions and it is  type safe.
 
 For example:
 --
 struct GraphableDescription { }
 
 protocol Graphable {
 /// Construct a graphable item from a description.
 init(description: GraphableDescription)
 
 func graph()
 }
 
 // Example framework method.
 func graphItem(description: GraphableDescription, graphable: 
 Graphable.Type) {
 // Instantiate the graphable.
 let item = graphable.init(description: description)
 
 // Graph it.
 item.graph()
 }
 
 // Example Graphable client.
 struct Circle: Graphable {
 init(description: GraphableDescription) { }
 
 func graph() { }
 }
 
 // Example framework client.
 func foo() {
 graphItem(GraphableDescription(), graphable: Circle.self)
 }
 --
 
  - Daniel
 
> On Dec 10, 2015, at 9:59 AM, Matthew Davies via swift-users 
>  wrote:
> 
> I don't really like the idea of a factory function, but unfortunately 
> that might be the only way to do it :( However, due to my specific use 
> case, I don't think a factory function will work. I'm working on a 
> framework that will need to both instantiate the class from a string (or 
> class type) and call methods dynamically on it. Which, I'm not sure I can 
> do in the build tools that are provided in the open source package. 
> Foundation hasn't been fully implemented and is missing a lot of the 
> methods that would allow this to work.
> 
> @Jens thanks for that blog post. I'll have to make sure I check back to 
> see what his solution is for it.
> 
> 
> 
> 
> Matthew Davies
> Junior Developer, GeoStrategies
> Director of Photography, OffBlock Films
> 209-225-3246 | 209-202-3284 | daviesg...@gmail.com | daviesgeek.com
>  
> 
> 
>> On Thu, Dec 10, 2015 at 9:30 AM, Jan Neumüller  
>> wrote:
>> Please no factory madness in Swift. This stuff is bad enough in Java - 
>> don’t infect Swift with it.
>> 
>> Jan
>> 
 On 10.12.2015, at 18:23, Jens Alfke via swift-users 
  wrote:
 
 
 On Dec 10, 2015, at 7:26 AM, Harlan Haskins via swift-users 
  wrote: