Re: [swift-users] Restricting associated values

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

Therefore I would make an Angle struct, something like:

//: Angle struct instead of angle enum


import Foundation


struct Angle  {

static let d2R = Double.pi / 180



static let r2D = 180 / Double.pi



private var degs: Double



var degrees: Double {

return degs

}



var radians: Double {

return degs * Angle.d2R

}



init(degrees: Double = 0) {

degs = degrees.truncatingRemainder(dividingBy: 180)

}



init(radians: Double) {

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

}

}


extension Angle: Hashable {

var hashValue: Int {

return degs.hashValue

}



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

return lhs.degs == rhs.degs

}

}


extension Angle/*: FloatingPoint*/ {

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

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

}



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

lhs.degs += rhs.degs

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

}



// Rest of FloatingPoint ...

}


// Trig

extension Angle {

var sin: Double {

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

}



// Other trig

}


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

a.radians // pi / 2

a.sin // 1

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

b.degrees // 171.9

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

c.degrees // 81.9

c == b // false

c.hashValue // 463...

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

d.radians // -pi / 2

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

e.degrees // -171.9

e += d // Wraps over -180 degrees

e.degrees // -81.9

  -- Howard.

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

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


[swift-users] TWISt-shout Newsletter 2017-06-19

2017-06-18 Thread Kenny Leung via swift-users
Hi All.

Here is your TWISt-shout Newsletter for the week of 2017-06-12 to 2017-06-18

https://github.com/pepperdog/TWISt-shout/blob/master/2017/TWISt-shout-2017-06-19.md
 


Enjoy!

-Kenny

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


Re: [swift-users] Intended behavior or bug in Dictionary's new subscript(_:default:)?

2017-06-18 Thread David Sweeris via swift-users

> On Jun 17, 2017, at 21:12, Ben Cohen via swift-users  
> wrote:
> 
> In order for this defaulting subscript technique to work as intended, the 
> subscript { get } needs to be called, then the mutation happens, then the 
> subscript { set } writes the mutated value back, including adding it for the 
> first time it the default was needed.
> 
> Reference types, not being value types, skip the write-back part, because 
> they shouldn’t need writing back – they should just get amended in place, 
> because they’re reference types. 
> 
> Except this particular technique is relying on it.
> 
> This is probably worth a bug report, though I’m not sure if there’s an easy 
> fix. The alternative is that Dictionary.subscript(_: default:) be made a 
> mutating get that sets the default if not present, even without the set. 
> There’s downsides to this though: you would no longer be able to use this 
> defaulting subscript with immutable dictionaries, and getting a default value 
> would add it which might be very unexpected.

We could say "extension Dictionary where Value: class", but that'll only fix it 
when the compiler knows `Value` has reference semantics (and lead to even more 
confusion when used in generic functions without the "T: class" part).

Could we check if `Value: class` within the existing setter? Or if that's what 
we already do to skip the write-back, skip the skipping when one of the values 
is nil?

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


Re: [swift-users] Decode a JSON object of unknown format into a Dictionary with Decodable in Swift 4

2017-06-18 Thread Jon Shier via swift-users
Given that, per his description, “metadata” can be anything, creating a struct 
doesn’t really help.



Jon Shier

> On Jun 18, 2017, at 9:00 PM, somu subscribe  wrote:
> 
> Create a struct for Metadata and conform to Coding
> 
> Code:
> 
> let string = """
> {
>   "id": "4yq6txdpfadhbaqnwp3",
>   "email": "john@example.com ",
>   "name":"John Doe",
>   "metadata": {
> "link_id": "linked-id",
> "buy_count": 4
>   }
> }
> """
> 
> let data = string.data(using: .utf8)! //Force unwrapping just for ease of 
> explanation, use guard instead
> 
> struct User: Codable {
> 
> //Struct to handle the nested JSON
> struct Metadata : Codable {
> var linkID   : String
> var buyCount : Int
> 
> //Customisation, if you want if you want your properties to be 
> different from the JSON key
> private enum CodingKeys : String, CodingKey {
> case linkID = "link_id"
> case buyCount   = "buy_count"
> }
> }
> 
> var id: String
> var email: String
> var name : String
> var metadata : Metadata
> }
> 
> let decoder = JSONDecoder()
> 
> do {
> let user = try decoder.decode(User.self, from: data)
> print(user)
> }
> catch {
> print("error:\(error)")
> }
> 
> Reference:
> 
> https://developer.apple.com/videos/play/wwdc2017/212/ 
> 
> 
> 
> Regards,
> Muthu
> 
> 
> 
>> On 19 Jun 2017, at 3:29 AM, Jon Shier via swift-users > > wrote:
>> 
>>  The more I use Codable, the less suited to networking it becomes. In 
>> reading a variety of blog posts about implementing custom Decodable support 
>> from JSON, I kept running across the same pattern. Basically, users had 
>> started implementing their own decoding protocols which wrap Decodable 
>> types, and have a type that represents the JSON representation and then 
>> their real type, with an initializer connecting the two. But apparently this 
>> is Apple’s official solution, which is rather terrible since it would be 
>> completely unnecessary if the Decodable APIs were more flexible or we could 
>> access keys by key path rather than nesting full containers. I can’t image 
>> how much code I would have to add to decode the nasty JSON APIs I’ve used 
>> Argo to parse before. Every type would need an underlying raw representation 
>> that, at the very least, would need custom keys, lest I pollute even those 
>> models with the terrible keys the JSON actually has. Not to mention the 
>> various transforms I needed. Once I hit any reasonably complex API, Argo is 
>> far far simpler to implement in fewer lines of code.
>>  In trying to make Argo’s JSON enum Decodable itself, I can’t seem to 
>> find a way to access the Any representation of the raw JSON. In fact, it 
>> appears there’s no way to represent an Any value in Codable at all, which 
>> makes Codable rather useless for the scenarios like the one that prompted 
>> this thread. Without such an ability it’s impossible to actually use Codable 
>> with all of the JSON out there, where other solutions work just fine. Argo’s 
>> JSON type is decodable by Argo, so you can use it to represent a blob of 
>> JSON just fine. Other existing JSON frameworks have similar solutions. 
>> 
>> 
>> 
>> Jon
>> 
>>> On Jun 18, 2017, at 3:21 AM, Rien via swift-users >> > wrote:
>>> 
>>> Dang, hit send too soon. Sorry.
>>> 
>>> This does not address your question, so please ignore… (foot in mouth)!
>>> 
>>> 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 18 Jun 2017, at 09:19, Rien > wrote:
 
 Are you looking for a general purpose JSON interpreter / API ?
 
 There are many of them around, and in fact I do have my own: 
 https://github.com/Balancingrock/VJson 
 
 
 With VJson I would write:
 
 let json = VJson.parse(… your json object…)
 
 and then access the metadata as:
 
 let buyCount = (json | ”metadata” | ”buy_count”)?.intValue
 
 or:
 
 var buyCount: Int &= json | “metadata” | “buy_count”
 
 To loop over the content of metadata:
 
 for item in (json | “metadata”) ?? [ ] {
print (item.nameValue)
switch item.type {
case .object: …
case .number: …
case .string: …
etc...
}
 }
 
 Obviously I am plugging my own 

Re: [swift-users] Decode a JSON object of unknown format into a Dictionary with Decodable in Swift 4

2017-06-18 Thread somu subscribe via swift-users
Create a struct for Metadata and conform to Coding

Code:

let string = """
{
  "id": "4yq6txdpfadhbaqnwp3",
  "email": "john@example.com",
  "name":"John Doe",
  "metadata": {
"link_id": "linked-id",
"buy_count": 4
  }
}
"""

let data = string.data(using: .utf8)! //Force unwrapping just for ease of 
explanation, use guard instead

struct User: Codable {

//Struct to handle the nested JSON
struct Metadata : Codable {
var linkID   : String
var buyCount : Int

//Customisation, if you want if you want your properties to be 
different from the JSON key
private enum CodingKeys : String, CodingKey {
case linkID = "link_id"
case buyCount   = "buy_count"
}
}

var id: String
var email: String
var name : String
var metadata : Metadata
}

let decoder = JSONDecoder()

do {
let user = try decoder.decode(User.self, from: data)
print(user)
}
catch {
print("error:\(error)")
}

Reference:

https://developer.apple.com/videos/play/wwdc2017/212/ 



Regards,
Muthu



> On 19 Jun 2017, at 3:29 AM, Jon Shier via swift-users  
> wrote:
> 
>   The more I use Codable, the less suited to networking it becomes. In 
> reading a variety of blog posts about implementing custom Decodable support 
> from JSON, I kept running across the same pattern. Basically, users had 
> started implementing their own decoding protocols which wrap Decodable types, 
> and have a type that represents the JSON representation and then their real 
> type, with an initializer connecting the two. But apparently this is Apple’s 
> official solution, which is rather terrible since it would be completely 
> unnecessary if the Decodable APIs were more flexible or we could access keys 
> by key path rather than nesting full containers. I can’t image how much code 
> I would have to add to decode the nasty JSON APIs I’ve used Argo to parse 
> before. Every type would need an underlying raw representation that, at the 
> very least, would need custom keys, lest I pollute even those models with the 
> terrible keys the JSON actually has. Not to mention the various transforms I 
> needed. Once I hit any reasonably complex API, Argo is far far simpler to 
> implement in fewer lines of code.
>   In trying to make Argo’s JSON enum Decodable itself, I can’t seem to 
> find a way to access the Any representation of the raw JSON. In fact, it 
> appears there’s no way to represent an Any value in Codable at all, which 
> makes Codable rather useless for the scenarios like the one that prompted 
> this thread. Without such an ability it’s impossible to actually use Codable 
> with all of the JSON out there, where other solutions work just fine. Argo’s 
> JSON type is decodable by Argo, so you can use it to represent a blob of JSON 
> just fine. Other existing JSON frameworks have similar solutions. 
> 
> 
> 
> Jon
> 
>> On Jun 18, 2017, at 3:21 AM, Rien via swift-users  
>> wrote:
>> 
>> Dang, hit send too soon. Sorry.
>> 
>> This does not address your question, so please ignore… (foot in mouth)!
>> 
>> 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 18 Jun 2017, at 09:19, Rien  wrote:
>>> 
>>> Are you looking for a general purpose JSON interpreter / API ?
>>> 
>>> There are many of them around, and in fact I do have my own: 
>>> https://github.com/Balancingrock/VJson
>>> 
>>> With VJson I would write:
>>> 
>>> let json = VJson.parse(… your json object…)
>>> 
>>> and then access the metadata as:
>>> 
>>> let buyCount = (json | ”metadata” | ”buy_count”)?.intValue
>>> 
>>> or:
>>> 
>>> var buyCount: Int &= json | “metadata” | “buy_count”
>>> 
>>> To loop over the content of metadata:
>>> 
>>> for item in (json | “metadata”) ?? [ ] {
>>> print (item.nameValue)
>>> switch item.type {
>>> case .object: …
>>> case .number: …
>>> case .string: …
>>> etc...
>>> }
>>> }
>>> 
>>> Obviously I am plugging my own code here, but there are many others around, 
>>> I understand that SwiftyJSON is quite popular but I have not used that 
>>> myself.
>>> 
>>> 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 18 Jun 2017, at 04:07, Chris Anderson via swift-users 
  wrote:
 
 Say I have a JSON object such as:
 
 {
  "id": "4yq6txdpfadhbaqnwp3",
  "email": "john@example.com",
  "name":"John Doe",
  "metadata": {
"link_id": 

Re: [swift-users] Decode a JSON object of unknown format into a Dictionary with Decodable in Swift 4

2017-06-18 Thread Jon Shier via swift-users
The more I use Codable, the less suited to networking it becomes. In 
reading a variety of blog posts about implementing custom Decodable support 
from JSON, I kept running across the same pattern. Basically, users had started 
implementing their own decoding protocols which wrap Decodable types, and have 
a type that represents the JSON representation and then their real type, with 
an initializer connecting the two. But apparently this is Apple’s official 
solution, which is rather terrible since it would be completely unnecessary if 
the Decodable APIs were more flexible or we could access keys by key path 
rather than nesting full containers. I can’t image how much code I would have 
to add to decode the nasty JSON APIs I’ve used Argo to parse before. Every type 
would need an underlying raw representation that, at the very least, would need 
custom keys, lest I pollute even those models with the terrible keys the JSON 
actually has. Not to mention the various transforms I needed. Once I hit any 
reasonably complex API, Argo is far far simpler to implement in fewer lines of 
code.
In trying to make Argo’s JSON enum Decodable itself, I can’t seem to 
find a way to access the Any representation of the raw JSON. In fact, it 
appears there’s no way to represent an Any value in Codable at all, which makes 
Codable rather useless for the scenarios like the one that prompted this 
thread. Without such an ability it’s impossible to actually use Codable with 
all of the JSON out there, where other solutions work just fine. Argo’s JSON 
type is decodable by Argo, so you can use it to represent a blob of JSON just 
fine. Other existing JSON frameworks have similar solutions. 



Jon

> On Jun 18, 2017, at 3:21 AM, Rien via swift-users  
> wrote:
> 
> Dang, hit send too soon. Sorry.
> 
> This does not address your question, so please ignore… (foot in mouth)!
> 
> 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 18 Jun 2017, at 09:19, Rien  wrote:
>> 
>> Are you looking for a general purpose JSON interpreter / API ?
>> 
>> There are many of them around, and in fact I do have my own: 
>> https://github.com/Balancingrock/VJson
>> 
>> With VJson I would write:
>> 
>> let json = VJson.parse(… your json object…)
>> 
>> and then access the metadata as:
>> 
>> let buyCount = (json | ”metadata” | ”buy_count”)?.intValue
>> 
>> or:
>> 
>> var buyCount: Int &= json | “metadata” | “buy_count”
>> 
>> To loop over the content of metadata:
>> 
>> for item in (json | “metadata”) ?? [ ] {
>>  print (item.nameValue)
>>  switch item.type {
>>  case .object: …
>>  case .number: …
>>  case .string: …
>>  etc...
>>  }
>> }
>> 
>> Obviously I am plugging my own code here, but there are many others around, 
>> I understand that SwiftyJSON is quite popular but I have not used that 
>> myself.
>> 
>> 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 18 Jun 2017, at 04:07, Chris Anderson via swift-users 
>>>  wrote:
>>> 
>>> Say I have a JSON object such as:
>>> 
>>> {
>>>   "id": "4yq6txdpfadhbaqnwp3",
>>>   "email": "john@example.com",
>>>   "name":"John Doe",
>>>   "metadata": {
>>> "link_id": "linked-id",
>>> "buy_count": 4
>>>   }
>>> }
>>> 
>>> And with a struct of:
>>> 
>>> struct User: Codable {
>>> var id: String
>>> var email: String
>>> var name: String
>>> }
>>> 
>>> How can I decode the `metadata` field into a Dictionary?
>>> 
>>> I’ve tried doing things such as, in my struct,
>>> 
>>> var metadata: Dictionary
>>> 
>>> or
>>> 
>>> var metadata: [String: Any]
>>> 
>>> But I get the error 
>>> 
>>> MyPlayground.playground:3:7: note: cannot automatically synthesize 
>>> 'Encodable' because '<>' does not conform to 'Encodable'
>>> var metadata: Dictionary 
>>> 
>>> A meta or metadata field on many APIs (such as www.stripe.com) can contain 
>>> whatever you want, and I still want to be able to process it on the Swift 
>>> end. How can I store that meta data field into a Dictionary that I can 
>>> parse apart manually after?
>>> 
>>> Thanks!
>>> 
>>> Chris Anderson
>>> 
>>> 
>>> 
>>> 
>>> 
>>> ___
>>> 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

Re: [swift-users] Can't use unsafe pointer from second thread?

2017-06-18 Thread Michel Fortin via swift-users
Oh, right, my mistake. I think the problem is that 
UnsafeMutableRawPointer() creates a pointer to the local variable mSelf 
on the stack. When mSelf goes out of scope, your raw pointer to an object 
reference pointer on the stack becomes invalid. (And it could become invalid 
even earlier with optimisations).

The correct way to pass your pointer is the one I described earlier. You can 
use passUnretained and takeUnretainedValue if you want to avoid touching the 
retain count since the AppDelegate will retain the object anyway.

> Le 18 juin 2017 à 11:21, Robert Nikander via swift-users 
>  a écrit :
> 
> The main thread isn’t deallocating the PointerTest object, because it’s saved 
> in the AppDelegate. 
> 
> Rob
> 
> 
>> On Jun 18, 2017, at 10:45 AM, Michel Fortin > > wrote:
>> 
>> The problem is that the main thread is deallocating the object before the 
>> other thread has a chance to see it. Ideally you'd pass a managed object 
>> reference to the block that runs in the other thread so the reference count 
>> does not fall to zero. If you absolutely need to pass it as an unsafe 
>> pointer then you must manage the reference count manually, like this:
>> 
>>  let unsafePtr = Unmanaged.passRetained(self).toOpaque()
>>  let safe = 
>> Unmanaged.fromOpaque(unsafePtr).takeRetainedValue()
>>  useSafeObject(safe)
>> 
>> Make sure the calls to passRetained and takeRetainedValue are balanced. (If 
>> this is a callback that gets called multiple times, use takeRetainedValue 
>> only once at the end.)
>> 
>>> Le 18 juin 2017 à 9:23, Robert Nikander via swift-users 
>>> > a écrit :
>>> 
>>> Hi,
>>> 
>>> I’m porting some C to Swift and I need to pass a Swift instance through a 
>>> `void *` (ie, UnsafeMutableRawPointer). It works, in one thread, but when a 
>>> second thread accesses the exact same pointer, it fails with memory errors 
>>> like EXC_BAD_ACCESS
>>> 
>>> The code below could be pasted into an AppDelegate.swift in a new single 
>>> view iOS project. 
>>> 
>>> Anyone know what’s going on here? The second call to 
>>> `tryUsingUnsafePointer`, in the new thread, crashes.
>>> 
>>> Rob
>>> 
>>> 
>>> class PointerTest {
>>> 
>>> let str = "Hello"
>>> 
>>> init() { print("PointerTest.init") }
>>> deinit { print("PointerTest.deinit") }
>>> 
>>> func start() {
>>> var mSelf = self
>>> let unsafePtr = UnsafeMutableRawPointer()
>>> tryUsingUnsafePointer(unsafePtr)
>>> print("Passing unsafe pointer to another thread: \(unsafePtr)") 
>>>
>>> Thread.detachNewThread {
>>> tryUsingUnsafePointer(unsafePtr)
>>> }
>>> }
>>> }
>>> 
>>> func tryUsingUnsafePointer(_ ptr: UnsafeMutableRawPointer) {
>>> print("Using unsafe pointer:")
>>> let typedPtr = ptr.assumingMemoryBound(to: PointerTest.self)
>>> // let typedPtr = ptr.bindMemory(to: PointerTest.self, capacity: 1)
>>> print("   typedPtr: \(typedPtr)")
>>> let obj = typedPtr.pointee
>>> print("   obj.str: \(obj.str)")  // Memory error happening here, or 
>>> sometimes line above
>>> }
>>> 
>>> 
>>> @UIApplicationMain
>>> class AppDelegate: UIResponder, UIApplicationDelegate {
>>> 
>>> var window: UIWindow?
>>> var ptrTest: PointerTest?
>>> 
>>> func application(_ application: UIApplication, 
>>> didFinishLaunchingWithOptions launchOptions: 
>>> [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
>>> 
>>> ptrTest = PointerTest()
>>> ptrTest?.start()
>>> 
>>> return true
>>> }
>>> 
>>> [...]
>>> 
>>> 
>>> 
>>> 
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org 
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> 
>> 
>> -- 
>> Michel Fortin
>> https://michelf.ca 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



-- 
Michel Fortin
https://michelf.ca

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


Re: [swift-users] Intended behavior or bug in Dictionary's new subscript(_:default:)?

2017-06-18 Thread Jens Persson via swift-users
https://bugs.swift.org/browse/SR-5250

On Sun, Jun 18, 2017 at 6:12 AM, Ben Cohen  wrote:

> In order for this defaulting subscript technique to work as intended, the
> subscript { get } needs to be called, then the mutation happens, then the
> subscript { set } writes the mutated value back, including adding it for
> the first time it the default was needed.
>
> Reference types, not being value types, skip the write-back part, because
> they shouldn’t need writing back – they should just get amended in place,
> because they’re reference types.
>
> Except this particular technique is relying on it.
>
> This is probably worth a bug report, though I’m not sure if there’s an
> easy fix. The alternative is that Dictionary.subscript(_: default:) be made
> a mutating get that sets the default if not present, even without the set.
> There’s downsides to this though: you would no longer be able to use this
> defaulting subscript with immutable dictionaries, and getting a default
> value would add it which might be very unexpected.
>
> > On Jun 16, 2017, at 1:40 PM, Jens Persson via swift-users <
> swift-users@swift.org> wrote:
> >
> > // Swift 4, Xcode 9 beta 1, default toolchain
> >
> > import Foundation
> >
> > var d1 = [Int : String]()
> > d1[1, default: .init()].append("a")
> > d1[2, default: .init()].append("b")
> > d1[3, default: .init()].append("c")
> > d1[1, default: .init()].append("d")
> > print(d1) // [2: "b", 3: "c", 1: "ad"] as expected.
> >
> > var d2 = [Int : NSMutableString]()
> > d2[1, default: .init()].append("a")
> > d2[2, default: .init()].append("b")
> > d2[3, default: .init()].append("c")
> > d2[1, default: .init()].append("d")
> > print(d2) // [:] but why?
> >
> > I know that NSMutableString is a reference type and String is a value
> type and that the default argument is an @autoclosure. I also know that the
> newly created NSMutableString instance is just released immediately after
> the append call, without being stored and retained in the Dictionary's
> storage.
> >
> > Is this the intended behavior and if so, please let me better understand
> how/why.
> >
> > /Jens
> >
> > ___
> > swift-users mailing list
> > swift-users@swift.org
> > https://lists.swift.org/mailman/listinfo/swift-users
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Can't use unsafe pointer from second thread?

2017-06-18 Thread Michel Fortin via swift-users
The problem is that the main thread is deallocating the object before the other 
thread has a chance to see it. Ideally you'd pass a managed object reference to 
the block that runs in the other thread so the reference count does not fall to 
zero. If you absolutely need to pass it as an unsafe pointer then you must 
manage the reference count manually, like this:

let unsafePtr = Unmanaged.passRetained(self).toOpaque()
let safe = 
Unmanaged.fromOpaque(unsafePtr).takeRetainedValue()
useSafeObject(safe)

Make sure the calls to passRetained and takeRetainedValue are balanced. (If 
this is a callback that gets called multiple times, use takeRetainedValue only 
once at the end.)

> Le 18 juin 2017 à 9:23, Robert Nikander via swift-users 
>  a écrit :
> 
> Hi,
> 
> I’m porting some C to Swift and I need to pass a Swift instance through a 
> `void *` (ie, UnsafeMutableRawPointer). It works, in one thread, but when a 
> second thread accesses the exact same pointer, it fails with memory errors 
> like EXC_BAD_ACCESS
> 
> The code below could be pasted into an AppDelegate.swift in a new single view 
> iOS project. 
> 
> Anyone know what’s going on here? The second call to `tryUsingUnsafePointer`, 
> in the new thread, crashes.
> 
> Rob
> 
> 
> class PointerTest {
> 
> let str = "Hello"
> 
> init() { print("PointerTest.init") }
> deinit { print("PointerTest.deinit") }
> 
> func start() {
> var mSelf = self
> let unsafePtr = UnsafeMutableRawPointer()
> tryUsingUnsafePointer(unsafePtr)
> print("Passing unsafe pointer to another thread: \(unsafePtr)")   
>  
> Thread.detachNewThread {
> tryUsingUnsafePointer(unsafePtr)
> }
> }
> }
> 
> func tryUsingUnsafePointer(_ ptr: UnsafeMutableRawPointer) {
> print("Using unsafe pointer:")
> let typedPtr = ptr.assumingMemoryBound(to: PointerTest.self)
> // let typedPtr = ptr.bindMemory(to: PointerTest.self, capacity: 1)
> print("   typedPtr: \(typedPtr)")
> let obj = typedPtr.pointee
> print("   obj.str: \(obj.str)")  // Memory error happening here, or 
> sometimes line above
> }
> 
> 
> @UIApplicationMain
> class AppDelegate: UIResponder, UIApplicationDelegate {
> 
> var window: UIWindow?
> var ptrTest: PointerTest?
> 
> func application(_ application: UIApplication, 
> didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: 
> Any]?) -> Bool {
> 
> ptrTest = PointerTest()
> ptrTest?.start()
> 
> return true
> }
> 
> [...]
> 
> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-- 
Michel Fortin
https://michelf.ca

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


Re: [swift-users] Decode a JSON object of unknown format into a Dictionary with Decodable in Swift 4

2017-06-18 Thread Jon Shier via swift-users
Your issue here is Any, which will likely never be Decodable. You’ll 
need an actual type to contain the raw JSON. Hilariously, I have to wonder if 
Argo’s JSON enum could be made Decodable, as it can represent every valid JSON 
type typically contained in the Any returned by JSONSerialization. Yet another 
reason why Swift needs a real JSON serialization.


Jon Shier

> On Jun 17, 2017, at 10:07 PM, Chris Anderson via swift-users 
>  wrote:
> 
> Say I have a JSON object such as:
> 
>   {
> "id": "4yq6txdpfadhbaqnwp3",
> "email": "john@example.com ",
> "name":"John Doe",
> "metadata": {
>   "link_id": "linked-id",
>   "buy_count": 4
> }
>   }
> 
> And with a struct of:
> 
> struct User: Codable {
>   var id: String
>   var email: String
>   var name: String
> }
> 
> How can I decode the `metadata` field into a Dictionary?
> 
> I’ve tried doing things such as, in my struct,
> 
> var metadata: Dictionary
> 
> or
> 
> var metadata: [String: Any]
> 
> But I get the error 
> 
> MyPlayground.playground:3:7: note: cannot automatically synthesize 
> 'Encodable' because '<>' does not conform to 'Encodable'
>   var metadata: Dictionary 
> 
> A meta or metadata field on many APIs (such as www.stripe.com 
> ) can contain whatever you want, and I still want to 
> be able to process it on the Swift end. How can I store that meta data field 
> into a Dictionary that I can parse apart manually after?
> 
> Thanks!
> 
> Chris Anderson
> 
>   
> 
> 
> 
> ___
> 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] Decode a JSON object of unknown format into a Dictionary with Decodable in Swift 4

2017-06-18 Thread Rien via swift-users
Dang, hit send too soon. Sorry.

This does not address your question, so please ignore… (foot in mouth)!

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 18 Jun 2017, at 09:19, Rien  wrote:
> 
> Are you looking for a general purpose JSON interpreter / API ?
> 
> There are many of them around, and in fact I do have my own: 
> https://github.com/Balancingrock/VJson
> 
> With VJson I would write:
> 
> let json = VJson.parse(… your json object…)
> 
> and then access the metadata as:
> 
> let buyCount = (json | ”metadata” | ”buy_count”)?.intValue
> 
> or:
> 
> var buyCount: Int &= json | “metadata” | “buy_count”
> 
> To loop over the content of metadata:
> 
> for item in (json | “metadata”) ?? [ ] {
>   print (item.nameValue)
>   switch item.type {
>   case .object: …
>   case .number: …
>   case .string: …
>   etc...
>   }
> }
> 
> Obviously I am plugging my own code here, but there are many others around, I 
> understand that SwiftyJSON is quite popular but I have not used that myself.
> 
> 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 18 Jun 2017, at 04:07, Chris Anderson via swift-users 
>>  wrote:
>> 
>> Say I have a JSON object such as:
>> 
>>  {
>>"id": "4yq6txdpfadhbaqnwp3",
>>"email": "john@example.com",
>>"name":"John Doe",
>>"metadata": {
>>  "link_id": "linked-id",
>>  "buy_count": 4
>>}
>>  }
>> 
>> And with a struct of:
>> 
>> struct User: Codable {
>>  var id: String
>>  var email: String
>>  var name: String
>> }
>> 
>> How can I decode the `metadata` field into a Dictionary?
>> 
>> I’ve tried doing things such as, in my struct,
>> 
>> var metadata: Dictionary
>> 
>> or
>> 
>> var metadata: [String: Any]
>> 
>> But I get the error 
>> 
>> MyPlayground.playground:3:7: note: cannot automatically synthesize 
>> 'Encodable' because '<>' does not conform to 'Encodable'
>>  var metadata: Dictionary 
>> 
>> A meta or metadata field on many APIs (such as www.stripe.com) can contain 
>> whatever you want, and I still want to be able to process it on the Swift 
>> end. How can I store that meta data field into a Dictionary that I can parse 
>> apart manually after?
>> 
>> Thanks!
>> 
>> Chris Anderson
>> 
>>  
>> 
>> 
>> 
>> ___
>> 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] Decode a JSON object of unknown format into a Dictionary with Decodable in Swift 4

2017-06-18 Thread Rien via swift-users
Are you looking for a general purpose JSON interpreter / API ?

There are many of them around, and in fact I do have my own: 
https://github.com/Balancingrock/VJson

With VJson I would write:

let json = VJson.parse(… your json object…)

and then access the metadata as:

let buyCount = (json | ”metadata” | ”buy_count”)?.intValue

or:

var buyCount: Int &= json | “metadata” | “buy_count”

To loop over the content of metadata:

for item in (json | “metadata”) ?? [ ] {
print (item.nameValue)
switch item.type {
case .object: …
case .number: …
case .string: …
etc...
}
}

Obviously I am plugging my own code here, but there are many others around, I 
understand that SwiftyJSON is quite popular but I have not used that myself.

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 18 Jun 2017, at 04:07, Chris Anderson via swift-users 
>  wrote:
> 
> Say I have a JSON object such as:
> 
>   {
> "id": "4yq6txdpfadhbaqnwp3",
> "email": "john@example.com",
> "name":"John Doe",
> "metadata": {
>   "link_id": "linked-id",
>   "buy_count": 4
> }
>   }
> 
> And with a struct of:
> 
> struct User: Codable {
>   var id: String
>   var email: String
>   var name: String
> }
> 
> How can I decode the `metadata` field into a Dictionary?
> 
> I’ve tried doing things such as, in my struct,
> 
> var metadata: Dictionary
> 
> or
> 
> var metadata: [String: Any]
> 
> But I get the error 
> 
> MyPlayground.playground:3:7: note: cannot automatically synthesize 
> 'Encodable' because '<>' does not conform to 'Encodable'
>   var metadata: Dictionary 
> 
> A meta or metadata field on many APIs (such as www.stripe.com) can contain 
> whatever you want, and I still want to be able to process it on the Swift 
> end. How can I store that meta data field into a Dictionary that I can parse 
> apart manually after?
> 
> Thanks!
> 
> Chris Anderson
> 
>   
> 
> 
> 
> ___
> 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