Re: [swift-users] Should I be using more catchless do blocks?

2017-06-19 Thread Rien via swift-users
Yes.

But: Only if it makes the code better.

I think that “understandability engineering” is just as important as “software 
engineering”. Maybe more so. After all, code that we understand has a better 
chance of working correctly than code that follows all paradigms but once the 
developer is gone nobody is able to maintain.

I.e. worry less about idiomatic programming and write more understandable code.

Swift is getting - well maybe it’s past already - the point where an 
experienced programmer can write code that no newbie has even a chance of 
understanding. If code blocks help in breaking this trend, go for it.

Regards,
Rien

Site: http://balancingrock.nl
Blog: http://swiftrien.blogspot.com
Github: http://github.com/Balancingrock
Project: http://swiftfire.nl - An HTTP(S) web server framework in Swift







> On 19 Jun 2017, at 04:07, Michael Savich via swift-users 
>  wrote:
> 
> So, something I did not know until recently is that do blocks in Swift are 
> for more than just error handling, they can also be used to tighten scope. 
> 
> I'm wondering, why not use a ton of do blocks? Like, if I have a 
> ViewController lifecycle method like viewDidLoad, I could segment it into out 
> a do block for creating subviews, a do block for loading data into them, and 
> a do block for adding them to the view itself. This seems like it would 
> enforce grouping code tightly together.
> 
> Yes I could adopt a functional style of programming, but that has its 
> downsides too, namely reading any functional code involves trawling through a 
> long sequence of function calls. What I'm saying is, do blocks seem like a 
> way to get many of the benefits of functional programming while maintaining 
> the readability of imperative code. (Sorry functional programmers, I promise 
> I love Haskell too!)
> 
> So I guess what I'm saying is… somebody talk me down from this ledge. Is 
> there a reason I shouldn't refactor my projects to be full of do blocks? And 
> can this usage of do really be considered idiomatic Swift? Or will most 
> people reading my code be left wondering where all the try and catch 
> statements are?
> 
> Sent from my iPad
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Should I be using more catchless do blocks?

2017-06-19 Thread Michael Savich via swift-users
Huh, I didn't realize you could nest functions like that. That being said, I'm 
not sure the declare-then-use structure really appeals to me personally. I 
might use it if the function was getting really long.

One last question: labels on do blocks. I know they are mostly intended to be 
used for that goto-lite behavior, but are labels also meant to be used by 
themselves, to describe the code they lead into? I never understood if they 
were meant to be used that way in C either… 

Sent from my iPad

> On Jun 19, 2017, at 6:51 PM, Michael Ilseman  wrote:
> 
> 
>> On Jun 19, 2017, at 11:47 AM, Michael Savich  
>> wrote:
>> 
>> Yeah, it's all about balance to be sure. Though one benefit of do blocks is 
>> in functions that are tied to a sense of time. It seems to me that the in 
>> case of something like viewDidLoad separating code into too many functions 
>> can obscure the fact that the code is meant to be executed at that time.
> 
> I was referring to defining a local function inside your function that you’re 
> refactoring. As in, rather than say:
> 
> func foo(...) -> … {
>   // some initialization
>   do {
>   … some local variables, some not local...
>   }
> 
>   code1...
> 
>   // some more scoped work
>   do {
>   … some local variables, some not local...
>   }
> 
>   code2...
> 
>   // some finalization
>   do {
>   … some local variables, some not local...
>   }
> }
> 
> You have:
> 
> func foo(…) -> … {
>   func doLocalSetup(…inputs...)  {
>   … use explicit inputs and local variables
>   }
>   func performScopedWork(…inputs…) {
>   … use explicit inputs and local variables
>   }
>   func doFinalTearDown(…inputs…) {
>   … use explicit inputs and local variables
>   }
> 
>   doLocalSetup(…)
>   defer { doFinalTearDown(…) }
>   
>   code1...
> 
>   performScopedWork(…)
> 
>   code2...
> }
> 
> 
> That’s just one option. You also mentioned using closures, which can be less 
> clear if you’re relying on implicit captures rather than explicit parameters 
> (which can have labels/names). It all depends on the details.
> 
>> Closures can provide much of the same functionality but I'm pretty sure 
>> inline closures have to have names and sometimes risking a bad name is worse 
>> than no name at all.
>> 
> 
> That might be the case. However, often such a do block is worthy of a comment 
> before it, and good names make really good comments.
> 
>> Anyway, do you think that most Swift users are even aware that do can be 
>> used in this fashion?
>> 
> 
> I wouldn’t think it would be obvious to new Swift programmers, but might be 
> familiar to programmers coming from other languages that use scopes heavily. 
> 
> It probably depends on your team specifics. As you mentioned, you only 
> recently learned of this behavior, so your experience might be a useful proxy 
> for whether others are or are not familiar.
> 
>> Sent from my iPad
>> 
>>> On Jun 19, 2017, at 2:33 PM, Michael Ilseman  wrote:
>>> 
>>> Introducing scope to manage lifetimes of local variables is a useful and 
>>> valuable practice. Note that it might also be an opportunity to refactor 
>>> the code. Any do block you want to introduce could also be a local function 
>>> definition that you call later. Alternatively, it could be generalized and 
>>> extracted into a utility component. Long function bodies with many do 
>>> blocks could be a code smell.
>>> 
>>> 
 On Jun 18, 2017, at 7:07 PM, Michael Savich via swift-users 
  wrote:
 
 So, something I did not know until recently is that do blocks in Swift are 
 for more than just error handling, they can also be used to tighten scope. 
 
 I'm wondering, why not use a ton of do blocks? Like, if I have a 
 ViewController lifecycle method like viewDidLoad, I could segment it into 
 out a do block for creating subviews, a do block for loading data into 
 them, and a do block for adding them to the view itself. This seems like 
 it would enforce grouping code tightly together.
 
 Yes I could adopt a functional style of programming, but that has its 
 downsides too, namely reading any functional code involves trawling 
 through a long sequence of function calls. What I'm saying is, do blocks 
 seem like a way to get many of the benefits of functional programming 
 while maintaining the readability of imperative code. (Sorry functional 
 programmers, I promise I love Haskell too!)
 
 So I guess what I'm saying is… somebody talk me down from this ledge. Is 
 there a reason I shouldn't refactor my projects to be full of do blocks? 
 And can this usage of do really be considered idiomatic Swift? Or will 
 most people reading my code be left wondering where 

Re: [swift-users] Protocol Conformance

2017-06-19 Thread Karl Wagner via swift-users

> On 20. Jun 2017, at 01:38, Muhammad Tahir Vali via swift-users 
>  wrote:
> 
> Hey all,
> 
> I wanted to know if theres a work around for a problem I am having
> 
> lets say I have a protocol 
> 
> protocol Graphable : CustomStringConvertible, Sequence, Collection {
> var vertices : [AnyVertexable] { get set }
> var edges: [AnyEdge]? { get set }
>  
> 
> }
> 
> Then I have 2 classes that inherit from them 
> 
> class EZUndirectedGraph : Graphable {
> var vertices : [AnyVertexable] 
> var edges: [AnyEdge]? 
>  .
> }
> 
> class EZDirectedGraph : Graphable {
> var vertices : [AnyVertexable]
> var edges: [AnyEdge]? 
> // var edges : [AnyEdge]
> 
> }
> 
> Is there a way for me to make the "edges" variable in "EZDirectedGraph" to 
> NOT be an optional while still conforming to the same protocol? As one may 
> know, a condition for directed graphs requires there to be atleast 1 edge. 
> 
> Advice or alternative workarounds would be nice with respect of what I am 
> trying to do here with Graph Theory. 
> 
> My last 2 options were to either 
> 
> 1. Create separate protocols for the different types of graphs but there's 
> many types so I would be writing a lot of redundant code. 
> 
> 2. Leaving it how it is. Inserting an enum "TypeOfGraph" for the different 
> types of graphs and then computing its type with the help of the different 
> initializer methods. 
> 
> 
> 
> -- 
> Best Regards,
> 
> Muhammad T. Vali
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



I don’t think that works, but in your case it would not be safe anyway. The 
(Optional-typed) property “edges” is mutable in the “Graphable” protocol — that 
means that anybody could take an EZDirectedGraph (where the property is 
non-optional), cast it to a Graphable, and set its “edges” property to nil. Or 
some generic code might do that.

Personally, I would recommend removing the optional. If you’re trying to 
represent the difference between possibly-empty-edges/not-empty-edges, the 
optional isn’t actually going to give you that safety. After all, there’s 
nothing in the type-system which says that EZDirectedGraph’s array is not 
empty. You would need to document that and add assertions when mutating.

If you really wanted to make it rigorously safe, you could create a 
NonEmptyArray struct which wraps an Array, intercepts mutation events and 
enforces that the underlying Array is never totally emptied. Then you would 
need to replace “edges” in Graphable with an associated type. That level of 
rigorous safety might not be required or even desired — on the other hand, it 
might help people to detect common bugs more easily. It all depends on your 
use-cases and your users.

- Karl

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


Re: [swift-users] Extensions on Typealiased Existential Protocols

2017-06-19 Thread Steven Brunwasser via swift-users
@David But the automatic conformance is currently supported through
extension A where Self: B.

@Slava When does extension A where Self: B not equal extension B where Self:
A? Why would protocol inheritance not be communicative?


On June 19, 2017 at 5:26:44 PM, David Sweeris (daveswee...@mac.com) wrote:

IIUC (which shouldn't be assumed on your part) the difference is that any
types which conform to both `A` and `B` will *automatically* conform to
`CProtocol` as well, but not `C`. I suspect the "automatic conformance" bit
is why we don't currently allow it.

- Dave Sweeris

On Jun 19, 2017, at 13:44, Jon Shier via swift-users 
wrote:

What I usually do here is:
typealias CProtocol = A & B
protocol C: CProtocol { } // or just A & B directly, I think
extension C {}

So it’s a bit silly to me.


Jon


On Jun 19, 2017, at 3:44 PM, Slava Pestov via swift-users <
swift-users@swift.org> wrote:

Hi Steven,

On Jun 19, 2017, at 11:44 AM, Steven Brunwasser via swift-users <
swift-users@swift.org> wrote:

Is this error intentional, or a bug?


It’s intentional. We could add support for this as an extra bit of sugar,
but note that

Since extension A where Self: B is the same as extension B where Self: A,


This is not quite true.

Slava

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


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


[swift-users] Protocol Conformance

2017-06-19 Thread Muhammad Tahir Vali via swift-users
Hey all,

I wanted to know if theres a work around for a problem I am having

lets say I have a protocol

protocol *Graphable* : CustomStringConvertible, Sequence, Collection {
var vertices : [AnyVertexable] { get set }
*var edges: [AnyEdge]? { get set }*
 

}

Then I have 2 classes that inherit from them

class *EZUndirectedGraph* : Graphable {
var vertices : [AnyVertexable]
*var edges: [AnyEdge]? *
 .
}

class *EZDirectedGraph* : Graphable {
var vertices : [AnyVertexable]
*var edges: [AnyEdge]? *
*// *var edges : [AnyEdge]

}

Is there a way for me to make the "edges" variable in "*EZDirectedGraph*"
to NOT be an optional while still conforming to the same protocol? As one
may know, a condition for directed graphs requires there to be atleast 1
edge.

Advice or alternative workarounds would be nice with respect of what I am
trying to do here with Graph Theory.

My last 2 options were to either

1. Create separate protocols for the different types of graphs but there's
many types so I would be writing a lot of redundant code.

2. Leaving it how it is. Inserting an enum "TypeOfGraph" for the different
types of graphs and then computing its type with the help of the different
initializer methods.



-- 
Best Regards,

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


Re: [swift-users] Should I be using more catchless do blocks?

2017-06-19 Thread Michael Ilseman via swift-users

> On Jun 19, 2017, at 11:47 AM, Michael Savich  wrote:
> 
> Yeah, it's all about balance to be sure. Though one benefit of do blocks is 
> in functions that are tied to a sense of time. It seems to me that the in 
> case of something like viewDidLoad separating code into too many functions 
> can obscure the fact that the code is meant to be executed at that time.

I was referring to defining a local function inside your function that you’re 
refactoring. As in, rather than say:

func foo(...) -> … {
// some initialization
do {
… some local variables, some not local...
}

code1...

// some more scoped work
do {
… some local variables, some not local...
}

code2...

// some finalization
do {
… some local variables, some not local...
}
}

You have:

func foo(…) -> … {
func doLocalSetup(…inputs...)  {
… use explicit inputs and local variables
}
func performScopedWork(…inputs…) {
… use explicit inputs and local variables
}
func doFinalTearDown(…inputs…) {
… use explicit inputs and local variables
}

doLocalSetup(…)
defer { doFinalTearDown(…) }

code1...

performScopedWork(…)

code2...
}


That’s just one option. You also mentioned using closures, which can be less 
clear if you’re relying on implicit captures rather than explicit parameters 
(which can have labels/names). It all depends on the details.

> Closures can provide much of the same functionality but I'm pretty sure 
> inline closures have to have names and sometimes risking a bad name is worse 
> than no name at all.
> 

That might be the case. However, often such a do block is worthy of a comment 
before it, and good names make really good comments.

> Anyway, do you think that most Swift users are even aware that do can be used 
> in this fashion?
> 

I wouldn’t think it would be obvious to new Swift programmers, but might be 
familiar to programmers coming from other languages that use scopes heavily. 

It probably depends on your team specifics. As you mentioned, you only recently 
learned of this behavior, so your experience might be a useful proxy for 
whether others are or are not familiar.

> Sent from my iPad
> 
> On Jun 19, 2017, at 2:33 PM, Michael Ilseman  > wrote:
> 
>> Introducing scope to manage lifetimes of local variables is a useful and 
>> valuable practice. Note that it might also be an opportunity to refactor the 
>> code. Any do block you want to introduce could also be a local function 
>> definition that you call later. Alternatively, it could be generalized and 
>> extracted into a utility component. Long function bodies with many do blocks 
>> could be a code smell.
>> 
>> 
>>> On Jun 18, 2017, at 7:07 PM, Michael Savich via swift-users 
>>> > wrote:
>>> 
>>> So, something I did not know until recently is that do blocks in Swift are 
>>> for more than just error handling, they can also be used to tighten scope. 
>>> 
>>> I'm wondering, why not use a ton of do blocks? Like, if I have a 
>>> ViewController lifecycle method like viewDidLoad, I could segment it into 
>>> out a do block for creating subviews, a do block for loading data into 
>>> them, and a do block for adding them to the view itself. This seems like it 
>>> would enforce grouping code tightly together.
>>> 
>>> Yes I could adopt a functional style of programming, but that has its 
>>> downsides too, namely reading any functional code involves trawling through 
>>> a long sequence of function calls. What I'm saying is, do blocks seem like 
>>> a way to get many of the benefits of functional programming while 
>>> maintaining the readability of imperative code. (Sorry functional 
>>> programmers, I promise I love Haskell too!)
>>> 
>>> So I guess what I'm saying is… somebody talk me down from this ledge. Is 
>>> there a reason I shouldn't refactor my projects to be full of do blocks? 
>>> And can this usage of do really be considered idiomatic Swift? Or will most 
>>> people reading my code be left wondering where all the try and catch 
>>> statements are?
>>> 
>>> Sent from my iPad
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org 
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> 
>> 

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


Re: [swift-users] Extensions on Typealiased Existential Protocols

2017-06-19 Thread Jon Shier via swift-users
What I usually do here is:
typealias CProtocol = A & B
protocol C: CProtocol { } // or just A & B directly, I think
extension C {}

So it’s a bit silly to me.


Jon


> On Jun 19, 2017, at 3:44 PM, Slava Pestov via swift-users 
>  wrote:
> 
> Hi Steven,
> 
>> On Jun 19, 2017, at 11:44 AM, Steven Brunwasser via swift-users 
>> > wrote:
>> 
>> Is this error intentional, or a bug?
> 
> It’s intentional. We could add support for this as an extra bit of sugar, but 
> note that
> 
>> Since extension A where Self: B is the same as extension B where Self: A,
> 
> This is not quite true.
> 
> Slava
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


[swift-users] Extensions on Typealiased Existential Protocols

2017-06-19 Thread Steven Brunwasser via swift-users
Is this error intentional, or a bug?


protocol A {}


protocol B {}


typealias C = A & B // valid


extension C {} // Error: Non-nominal type 'C' (aka 'A & B') cannot be
extended


extension A where Self: B {} // valid


struct Foo: C {} // valid


Since extension A where Self: B is the same as extension B where Self: A,
and C is defined as any A that also inherits from B, shouldn’t extension C be
just as valid?

This seems like it should be valid, so I filed this bug,
https://bugs.swift.org/browse/SR-5260.

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


Re: [swift-users] Should I be using more catchless do blocks?

2017-06-19 Thread Michael Ilseman via swift-users
Introducing scope to manage lifetimes of local variables is a useful and 
valuable practice. Note that it might also be an opportunity to refactor the 
code. Any do block you want to introduce could also be a local function 
definition that you call later. Alternatively, it could be generalized and 
extracted into a utility component. Long function bodies with many do blocks 
could be a code smell.


> On Jun 18, 2017, at 7:07 PM, Michael Savich via swift-users 
>  wrote:
> 
> So, something I did not know until recently is that do blocks in Swift are 
> for more than just error handling, they can also be used to tighten scope. 
> 
> I'm wondering, why not use a ton of do blocks? Like, if I have a 
> ViewController lifecycle method like viewDidLoad, I could segment it into out 
> a do block for creating subviews, a do block for loading data into them, and 
> a do block for adding them to the view itself. This seems like it would 
> enforce grouping code tightly together.
> 
> Yes I could adopt a functional style of programming, but that has its 
> downsides too, namely reading any functional code involves trawling through a 
> long sequence of function calls. What I'm saying is, do blocks seem like a 
> way to get many of the benefits of functional programming while maintaining 
> the readability of imperative code. (Sorry functional programmers, I promise 
> I love Haskell too!)
> 
> So I guess what I'm saying is… somebody talk me down from this ledge. Is 
> there a reason I shouldn't refactor my projects to be full of do blocks? And 
> can this usage of do really be considered idiomatic Swift? Or will most 
> people reading my code be left wondering where all the try and catch 
> statements are?
> 
> Sent from my iPad
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Restricting associated values

2017-06-19 Thread Karl Wagner via swift-users

> On 19. Jun 2017, at 04:30, Nevin Brackett-Rozinsky via swift-users 
>  wrote:
> 
> Is there a way to restrict the associated values of an enum? For example, 
> suppose I have this type:
> 
> enum Angle {
> case radians(Double)
> case degrees(Double)
> }
> 
> I want to ensure that the radians values is always in [0, 2π) and the degrees 
> values is always in [0, 360). Ideally I would like to write an initializer 
> which is called when the user writes eg. “let x: Angle = .degrees(-45)” and 
> contains the logic to wrap the provided value into the allowed range (in this 
> case by adding a multiple of 360).
> 
> I don’t see a way to do it. Is this possible?
> 
> The closest I’ve found is to create auxiliary types such as
> 
> struct Degree { … }
> struct Radian { … }
> 
> and give them appropriate initializers, then use them for the associated 
> values. However that is undesirable because it adds an extra level of depth 
> to get at the actual numeric values.
> 
> Is there a better way?
> 
> Nevin
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users 
> 

I suggested a type like this when Xiaodi announced his maths library, but a 
more efficient implementation would look like this:

public struct Angle {
public let radians: T
public var degrees: T {
return (radians / .pi) * 180
}

public static func radians(_ rads: T) -> Angle {
return Angle(radians: rads)
}
public static func degrees(_ degs: T) -> Angle {
return Angle(radians: (degs / 180) * .pi)
}
}

Floating-points don’t have extra inhabitants, so the enum representation would 
occupy { float size + 1 byte } of storage, with the extra byte marking which 
enum case you have.

A better approach is to store a single, normalised value (in this case, the 
‘radians' value), and to provide initialisers which validate and normalise 
those input values. In your case, you wrap them to an allowed range. 

I think the best-practice advice in this situation would be to consider 
switching: will anybody need to switch over the cases of your enum? In this 
case, no - Angle is just a wrapper which statically verifies that the angle 
is in the expected “notation”; You want to put an angle of either notation in, 
and grab the same angle out in another notation. The underlying stored notation 
is an implementation detail, so a struct is better.

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


Re: [swift-users] Restricting associated values

2017-06-19 Thread Karl Wagner via swift-users

> On 19. Jun 2017, at 20:03, Karl Wagner  wrote:
> 
> 
>> On 19. Jun 2017, at 04:30, Nevin Brackett-Rozinsky via swift-users 
>> > wrote:
>> 
>> Is there a way to restrict the associated values of an enum? For example, 
>> suppose I have this type:
>> 
>> enum Angle {
>> case radians(Double)
>> case degrees(Double)
>> }
>> 
>> I want to ensure that the radians values is always in [0, 2π) and the 
>> degrees values is always in [0, 360). Ideally I would like to write an 
>> initializer which is called when the user writes eg. “let x: Angle = 
>> .degrees(-45)” and contains the logic to wrap the provided value into the 
>> allowed range (in this case by adding a multiple of 360).
>> 
>> I don’t see a way to do it. Is this possible?
>> 
>> The closest I’ve found is to create auxiliary types such as
>> 
>> struct Degree { … }
>> struct Radian { … }
>> 
>> and give them appropriate initializers, then use them for the associated 
>> values. However that is undesirable because it adds an extra level of depth 
>> to get at the actual numeric values.
>> 
>> Is there a better way?
>> 
>> Nevin
>> ___
>> swift-users mailing list
>> swift-users@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-users 
>> 
> 
> I suggested a type like this when Xiaodi announced his maths library, but a 
> more efficient implementation would look like this:
> 
> public struct Angle {
> public let radians: T
> public var degrees: T {
> return (radians / .pi) * 180
> }
> 
> public static func radians(_ rads: T) -> Angle {
> return Angle(radians: rads)
> }
> public static func degrees(_ degs: T) -> Angle {
> return Angle(radians: (degs / 180) * .pi)
> }
> }
> 
> Floating-points don’t have extra inhabitants, so the enum representation 
> would occupy { float size + 1 byte } of storage, with the extra byte marking 
> which enum case you have.
> 
> A better approach is to store a single, normalised value (in this case, the 
> ‘radians' value), and to provide initialisers which validate and normalise 
> those input values. In your case, you wrap them to an allowed range. 
> 
> I think the best-practice advice in this situation would be to consider 
> switching: will anybody need to switch over the cases of your enum? In this 
> case, no - Angle is just a wrapper which statically verifies that the 
> angle is in the expected “notation”; You want to put an angle of either 
> notation in, and grab the same angle out in another notation. The underlying 
> stored notation is an implementation detail, so a struct is better.
> 
> - Karl

Oh, and one thing to note is that by making static initialiser functions, you 
can still pass angles in to functions by calling ".degrees(90)”  or 
“.radians(.pi/4)”, so you kind-of emulate the convenience of using enums. IIRC, 
RawOptionSet does a similar trick.

The above struct is source-compatible with an equivalent enum representation; 
it all comes down to implementation details, and for this, the struct is more 
efficient.

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


[swift-users] Is there any way to decode from Any type JSON Object using JSONDecoder?

2017-06-19 Thread Masaki Haga via swift-users
Hi Swift-Users,

I was wondering if there is any way to decode JSON from Any type JSON
Object using `JSONDecoder`, not from Data type object.

Currently, `JSONDecoder` has only one decode function which decodes Data
type object to `Decodable`. Inside the function, it serializes Data object
to Any Type JSON Object using `JSONSerialization` and pass it into
`_JSONDecoder(referencing:, options:)` (Refer JSONEncoder.swift#874).

As discussed in some of other threads such as "SE-0166: Swift Archival &
Serialization", the default implementation of JSONDecoder or Decodable
protocol doesn’t allow to decode from one format to another format (such as
snake-case to camel-case), we need to implement custom CodingKey enums.
However, in our project, to parse the server API JSON response with
snake-case, declaring custom CodingKey enums for all the pre-existing
models is almost impossible and very inefficient, so I decided to covert
all the JSON keys from snake-case to camel-case, and then pass it into
`JSONDecoder.decode`. To achieve this, we need to convert the Data object
resulted from `URLSession.task` to Any type JSON Object using
`JSONSerialization`, do the conversion from snake-case to camel-case and
then convert back to Data type and then pass to `JSONDecoder.decode` which
looks very redundant because the function uses `JSONSerialization` inside
of it as mentioned above. If there is a function like below, we can get rid
of this redundant call of `JSONSerialization`.

```
func decode(_ type: T.Type, from JSONObject: Any) throws -> T
```

Sorry if I am misunderstanding the new API but is there any way to decode
`Decodable` directly from Any type JSON Object?

If not, I think adding the function aforementioned and giving an ability to
opt-out this JSON serialization call would give more flexibility to the API
in my humble opinion.

Thank you for reading.

All the best,
- Masaki
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Should I be using more catchless do blocks?

2017-06-19 Thread Michael Savich via swift-users
So, something I did not know until recently is that do blocks in Swift are for 
more than just error handling, they can also be used to tighten scope. 

I'm wondering, why not use a ton of do blocks? Like, if I have a ViewController 
lifecycle method like viewDidLoad, I could segment it into out a do block for 
creating subviews, a do block for loading data into them, and a do block for 
adding them to the view itself. This seems like it would enforce grouping code 
tightly together.

Yes I could adopt a functional style of programming, but that has its downsides 
too, namely reading any functional code involves trawling through a long 
sequence of function calls. What I'm saying is, do blocks seem like a way to 
get many of the benefits of functional programming while maintaining the 
readability of imperative code. (Sorry functional programmers, I promise I love 
Haskell too!)

So I guess what I'm saying is… somebody talk me down from this ledge. Is there 
a reason I shouldn't refactor my projects to be full of do blocks? And can this 
usage of do really be considered idiomatic Swift? Or will most people reading 
my code be left wondering where all the try and catch statements are?

Sent from my iPad___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Restricting associated values

2017-06-19 Thread Travis Griggs via swift-users

> On Jun 18, 2017, at 10:33 PM, Howard Lovatt via swift-users 
>  wrote:
> 
> To me Angle is a unit with two common representations: radians and degrees. 
> It's not an enum because it doesn't have two values, it has one value that 
> you can view in two ways.
> 
> Therefore I would make an Angle struct, something like:
> 

Lots of different ways I think. I chose not between struct and enum, but used 
both:

struct Angle {
enum Unit:CGFloat {
case radians = 1.0
case degrees = 57.29577951309314 // 360.0 / Tau
case rotations = 0.1591549430918953 // 1.0 / Tau
}

// MARK: - Stored Properties
var raw:CGFloat = 0.0
var unit:Unit = .radians
….
// MARK: - Left for the Student

I do a bit of UI programming with angles and have found rotations (I’ve drunk 
too much of the Tau manifesto koolaid probably) to be the most natural fit for 
a lot of things. Having an angle object allows me to layer over (via 
extensions) the various cocoa/uikit apis that take angles with type safe angle 
objects, and yet given me the ability to express said angles in whatever 
intermediate domain best fits.
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users