[swift-users] Happy new year Swift community.
Well some of you guys have to wait a little longer, but I can already wish everyone a happy new year from Germany. -- Adrian Zubarev Sent with Airmail ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] A somewhat stupid question about protocol conformances
Sorry yeah you’re right, the example also requires conditional conformances. If you do not need dynamic dispatch in your use case then you can workaround the issue for now by hiding the protocol requirements and abusing the protocol extension: import UIKit protocol AreaProtocol { /* keep it empty */ } extension AreaProtocol where Self : Sequence, Self.Element == CGPoint { func area() -> CGFloat { return 0.0 } func volume(height: CGFloat) -> CGFloat { return height * area() } } // or directly extension Sequence where Element == CGPoint { // stuff from above } extension Array : AreaProtocol {} let p0 = CGPoint(x: 0.0, y: 0.0) let p1 = CGPoint(x: 2.0, y: 0.0) let p2 = CGPoint(x: 2.0, y: 2.0) let p3 = CGPoint(x: 0.0, y: 2.0) let poligon = [p0, p1, p2, p3] let a = poligon.area() let v = poligon.volume(height: 10.0) Am 25. November 2017 um 13:58:44, Antonino Ficarra (antonino.fica...@gmail.com) schrieb: Adrian, thanks, but don’t work :-( import Foundation protocol AreaProtocol { // required func area() -> CGFloat // implemented in protocol extension func volume( height:CGFloat ) -> CGFloat // } extension AreaProtocol { func volume( height:CGFloat ) -> CGFloat { return height * area() } // // } protocol CGPointSequence: Sequence, AreaProtocol where Element == CGPoint {} extension CGPointSequence { func area() -> CGFloat { return 0.0 // ... poligon area } } extension Array:CGPointSequence {} // !'CGPointSequence' requires the types 'Element' and 'CGPoint' be equivalent Il giorno 25 nov 2017, alle ore 09:11, Adrian Zubarevha scritto: This is correct. None of your types does conform to your protocol because you never conformance explicitly. The extenstion you wrote is just a conditional extension which says if the Self type conforms to AreaProtocol and the associated typed Element is a CGPoint then add the area method to it. Nothing more, nothing less. Now you may think that you have to rewrite that extension to `extension Sequence : AreaProtocol where Element == CGPoint`, but that won't work because retroactively conforming protocols to other protocols is not supported yet. Nor are conditional conformances included yet, but they will in Swift 4.1 or 5. You have one option left. protocol MySequence : Sequence, AreaProtocol where Element == CGPoint {} extension Array : MySequence {} Then also conform other sequences you need to support that functionality. Double check if the code compiles, I wrote it on my iPhone, but you get the idea now. -- Adrian Zubarev Sent with Airmail Am 25. November 2017 um 07:40:25, Antonino Ficarra via swift-users (swift-users@swift.org) schrieb: In this code example: import Foundation protocol AreaProtocol { func area() -> CGFloat // implemented in protocol extension func volume( height:CGFloat ) -> CGFloat // } extension AreaProtocol { func volume( height:CGFloat ) -> CGFloat { return height * area() } // // } // conform CGPoint sequences to AreaProtocol extension Sequence where Self : AreaProtocol, Element == CGPoint { func area() -> CGFloat { return 0.0 // ... poligon area } } let p0 = CGPoint(x: 0.0, y: 0.0) let p1 = CGPoint(x: 2.0, y: 0.0) let p2 = CGPoint(x: 2.0, y: 2.0) let p3 = CGPoint(x: 0.0, y: 2.0) let poligon = [p0,p1,p2,p3] let a = poligon.area()// ! Type '[CGPoint]' does not conform to protocol 'AreaProtocol' let v = poligon.volume( height:10.0 )// ! Value of type '[CGPoint]' has no member 'volume' An array of CGPoint is a CGPoint sequence? Why the array don't gets automatic conformance to AreaProtocol? How can conform an array of CGPoint to AreaProtocol? Sorry for my bad english, Antonino ___ 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] A somewhat stupid question about protocol conformances
This is correct. None of your types does conform to your protocol because you never conformance explicitly. The extenstion you wrote is just a conditional extension which says if the Self type conforms to AreaProtocol and the associated typed Element is a CGPoint then add the area method to it. Nothing more, nothing less. Now you may think that you have to rewrite that extension to `extension Sequence : AreaProtocol where Element == CGPoint`, but that won't work because retroactively conforming protocols to other protocols is not supported yet. Nor are conditional conformances included yet, but they will in Swift 4.1 or 5. You have one option left. protocol MySequence : Sequence, AreaProtocol where Element == CGPoint {} extension Array : MySequence {} Then also conform other sequences you need to support that functionality. Double check if the code compiles, I wrote it on my iPhone, but you get the idea now. -- Adrian Zubarev Sent with Airmail Am 25. November 2017 um 07:40:25, Antonino Ficarra via swift-users (swift-users@swift.org(mailto:swift-users@swift.org)) schrieb: > In this code example: > > import Foundation > > protocol AreaProtocol { > func area() -> CGFloat > > // implemented in protocol extension > func volume( height:CGFloat ) -> CGFloat > // > } > > extension AreaProtocol { > func volume( height:CGFloat ) -> CGFloat { > return height * area() > } > // > // > } > > > // conform CGPoint sequences to AreaProtocol > extension Sequence > where Self : AreaProtocol, Element == CGPoint > { > func area() -> CGFloat { > return 0.0 // ... poligon area > } > } > > let p0 = CGPoint(x: 0.0, y: 0.0) > let p1 = CGPoint(x: 2.0, y: 0.0) > let p2 = CGPoint(x: 2.0, y: 2.0) > let p3 = CGPoint(x: 0.0, y: 2.0) > > let poligon = [p0,p1,p2,p3] > let a = poligon.area()// ! Type '[CGPoint]' does not conform to protocol > 'AreaProtocol' > let v = poligon.volume( height:10.0 )// ! Value of type '[CGPoint]' has no > member 'volume' > > > An array of CGPoint is a CGPoint sequence? Why the array don't gets automatic > conformance to AreaProtocol? > How can conform an array of CGPoint to AreaProtocol? > > Sorry for my bad english, > Antonino > > ___ > 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] Problem with Access Control and Extensions
I don’t get your problem here. If you don’t want to debate the correctness of your code, why are you asking for help or even showing error messages for a code snippet that cannot work? 1. Drop the access modifier from the extension itself, because this is only for convenience, which may or may not rule over the members of the extension members. If you’re already explicitly setting the access modifier on the extension members then the convenience access modifier makes no sense. 2. The code cannot work, because you cannot override `viewDidLoad` on a class that you don’t own, on a subclass of `UISplitViewController` that would be possible. ``` class MySplitViewController : UISplitViewController {} extension MySplitViewController { override open func viewDidLoad() { super.viewDidLoad() /* ... */ } } ``` Am 20. September 2017 um 21:41:31, Rick Aurbach via swift-users (swift-users@swift.org) schrieb: I am trying to write an extension to a UIKit class, but am running into a can’t-win situation: The code I ‘want’ to write looks like: public extension UISplitViewController { override public func viewDidLoad() { super.viewDidLoad() if UIDevice.current.userInterfaceIdiom == .pad { preferredDisplayMode = .automatic } else { preferredDisplayMode = .primaryOverlay } } } This generates the error message /Users/rlaurb/Projects/Cooks-Memory/Cooks-Memory/AppDelegate.swift:131:23: Overriding instance method must be as accessible as the declaration it overrides /Users/rlaurb/Projects/Cooks-Memory/Cooks-Memory/AppDelegate.swift:131:23: Overridden declaration is here (UIKit.UIViewController) But I can’t change the access control of the function to ‘open’, because I get the warning that the function can’t be “more” accessible than the extension. And I can’t change the extension’s access to ‘open’ because apparently extensions can’t be open. Now I don’t want to get into a debate about whether this code works — it’s just an experiment — but is it even possible to express this idea?? I.e., is it possible to express this idea without subclassing? Cheers, Rick Aurbach ___ 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] Foundation bug or indended?
Hi there, before filing a new issue I would like to ask if this is intended behaviour or a bug: The Foundation class Operation which has it’s roots in Objective-C has a few readonly properties like the following one: @available(iOS 2.0, *) open class Operation : NSObject { ... open var isExecuting: Bool { get } ... } On the other hand the Objective-C header looks like this: NS_CLASS_AVAILABLE(10_5, 2_0) @interface NSOperation : NSObject { ... @property (readonly, getter=isExecuting) BOOL executing; ... @end Now I want to create a custom subclass of Operation and override isExecuting, everything works fine until I try to create a private stored property named executing: final class TransitionOperation : Operation { // error: cannot override with a stored property 'executing' private var executing = false override var isExecuting: Bool { ... } } I’m a little bit confused here: Is this intended behaviour or a bug? The Foundation implemented in Swift is not used for iOS deployment, instead the Obj-C one is used right? ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Type of expression is ambiguous for static tuples
Yet this is correct behavior because the compiler cannot traverse the expression tree without knowing the root type of that expression tree. The type information flow in such case should be from root to the leaves where the root is NOT the root of the expression, but the type from the function parameter, which then should be passed to the expression tree. However the expression tree is not complete, because there MIGHT be another `phythagoreanTruple` somewhere else. Even if there is no other `phythagoreanTruple`, here the general rules are applied which results into the mentioned error message. Please correct me if I’m wrong here. Am 1. September 2017 um 14:53:35, David Hart (da...@hartbit.com) schrieb: Its slightly different though. In the case of: let cgColor: CGColor = .clear.cgColor clear is a static property on UIColor, not CGColor. In his example, pythagoreanTriple is a property on Double so it does feel like a bug. On 1 Sep 2017, at 13:31, Adrian Zubarev via swift-users <swift-users@swift.org> wrote: It’s because the compiler does not support this yet. It’s the same with `let cgColor: CGColor = .clear.cgColor // will not work`. Instead you need to write `UIColor.clear.cgColor` or in your case `Double.phythagoreanTruple.0` Am 1. September 2017 um 12:17:57, Rudolf Adamkovič via swift-users (swift-users@swift.org) schrieb: Given the following extension ... extension Double { typealias Triple = (Double, Double, Double) static let pythagoreanTriple: Triple = (3, 4, 5) } ... why does Swift compiler emits the following errors? // Type of expression is ambiguous without more context let a: Double = .pythagoreanTriple.0 // Type of expression is ambiguous without more context func f(_ x: Double) {} f(.pythagoreanTriple.0) The errors disappear with explicit Double.pythagoreanTriple.0. Why doesn't the compiler infer Double in this case? FYI: Posted also to Stack Overflow here: https://stackoverflow.com/questions/45998034/type-of-expression-is-ambiguous-for-static-tuples R+ ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Type of expression is ambiguous for static tuples
It’s because the compiler does not support this yet. It’s the same with `let cgColor: CGColor = .clear.cgColor // will not work`. Instead you need to write `UIColor.clear.cgColor` or in your case `Double.phythagoreanTruple.0` Am 1. September 2017 um 12:17:57, Rudolf Adamkovič via swift-users (swift-users@swift.org) schrieb: Given the following extension ... extension Double { typealias Triple = (Double, Double, Double) static let pythagoreanTriple: Triple = (3, 4, 5) } ... why does Swift compiler emits the following errors? // Type of expression is ambiguous without more context let a: Double = .pythagoreanTriple.0 // Type of expression is ambiguous without more context func f(_ x: Double) {} f(.pythagoreanTriple.0) The errors disappear with explicit Double.pythagoreanTriple.0. Why doesn't the compiler infer Double in this case? FYI: Posted also to Stack Overflow here: https://stackoverflow.com/questions/45998034/type-of-expression-is-ambiguous-for-static-tuples R+ ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] How does "Sequence.joined" work?
Moving this thread to the correct mailing list. Am 8. August 2017 um 06:36:18, Félix Cloutier via swift-evolution (swift-evolut...@swift.org) schrieb: All this means is that `joined()` does not create an array that contains the new result. It's only as magic as the COW semantics on arrays. Le 7 août 2017 à 21:12, Daryle Walker via swift-evolutiona écrit : I was looking at random items at SwiftDoc.org, and noticed the “FlattenBidirectionalCollection” structure. It helps implement some versions of “joined” from Sequence (probably when the Sequence is also a BidirectionalCollection). The directions for the type state that “joined” does not create new storage. Then wouldn’t it have to refer to the source objects by reference? How; especially how does it work without requiring a “&” with “inout” or how it works with “let”-mode objects? Or am I misunderstanding how it works behind the covers? (If there is a secret sauce to have one object refer to another without “&”/“inout”/“UnsafeWhateverPointer”, I like to know. It may help with implementing an idea. The idea involves extending the language, so “compiler magic” that the user can’t access is OK; I’d just claim to use the same sauce in my proposal.) — Daryle Walker Mac, Internet, and Video Game Junkie darylew AT mac DOT com ___ swift-evolution mailing list swift-evolut...@swift.org https://lists.swift.org/mailman/listinfo/swift-evolution ___ swift-evolution mailing list swift-evolut...@swift.org https://lists.swift.org/mailman/listinfo/swift-evolution ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Is it possible to store a set of heterogeneous items with protocol?
No it does not have to be a generic enum at all, as long you do not want extending the types from a diffrent module. Simply add a new enum case for each type you need, like `case string(String)`. You may also want to ask the wrapped type for it's hashValue so that it will hash correctly. -- Adrian Zubarev Sent with Airmail Am 11. Juli 2017 um 15:15:11, Glen Huang (hey...@gmail.com(mailto:hey...@gmail.com)) schrieb: > > NM, I think you meant this? > > enum Either{ > case Left(T1) > case Right(T2) > } > > > On 11 Jul 2017, at 9:06 PM, Glen Huang via swift-users > > wrote: > > This sounds pretty interesting. > > > > But I can’t totally wrap my head around it. How do I "wrap types into enum > > cases”? Could you provide a sample code? Thanks. > > > > > On 11 Jul 2017, at 8:50 PM, Adrian Zubarev > > > > > > wrote: > > > If the solution you seek is not designed so that the module user can > > > extend the set of types then you could wrap your types into enum cases > > > and use the enum for your set. ;) When Swift will support anonymous enum > > > cases, this will be an elegant solution to these type of things. > > > > > > -- > > > Adrian Zubarev > > > Sent with Airmail > > > > > > Am 11. Juli 2017 um 14:46:12, Glen Huang via swift-users > > > (swift-users@swift.org(mailto:swift-users@swift.org)) schrieb: > > > > > > > > > > > Thanks for bringing AnyHashable to my attention. > > > > > > > > It works, but the types are now erased. I want to have a union of the > > > > two sets because I want to loop over it to treat each contained item as > > > > Named, so I can process them as though they are of the same type. Is > > > > this type of use case really should be addressed using super class? > > > > > > > > > On 11 Jul 2017, at 7:38 PM, Howard Lovatt > > > > > wrote: > > > > > You can have a set of AnyHashable: > > > > > > > > > > > var item = Set() > > > > > > item.insert(AnyHashable(Foo())) > > > > > > item.insert(AnyHashable(Bar())) > > > > > > > > > > Depends what you will do with the set if this is viable or not. You > > > > > can also use classes and ObjectID. > > > > > > > > > > You might want this though: > > > > > > > > > > > var item = [AnyHashable: Any] > > > > > extension Dictionary where Key == AnyHashable, Value: Hashable { > > > > > func insert(_ value: Value) { > > > > > self[AnyHashable(value)] == value > > > > > } > > > > > } > > > > > > item.insert(Foo()) > > > > > > item.insert(Bar()) > > > > > > > > > > So you get at the stored value. > > > > > > > > > > -- Howard. > > > > > > > > > > On 11 Jul 2017, at 8:09 pm, Glen Huang via swift-users > > > > > wrote: > > > > > > > > > > > Hi, > > > > > > > > > > > > I want to store some heterogeneous items all conform to a protocol > > > > > > inside a set, is it something possible to do in swift? > > > > > > > > > > > > I tried this example: > > > > > > > > > > > > ``` > > > > > > protocol Named: Hashable { > > > > > > var name: String { get } > > > > > > } > > > > > > > > > > > > extension Named { > > > > > > var hashValue: Int { > > > > > > return name.hashValue > > > > > > } > > > > > > > > > > > > static func ==(lhs: Self, rhs: Self) -> Bool { > > > > > > return lhs.name == rhs.name > > > > > > } > > > > > > } > > > > > > > > > > > > struct Foo: Named { > > > > > > var name = "foo" > > > > > > } > > > > > > > > > > > > struct Bar: Named { > > > > > > var name = "bar" > > > > > > } > > > > > > > > > > > > var item = Set() > > > > > > item.insert(Foo()) > > > > > > item.insert(Bar()) > > > > > > ``` > > > > > > > > > > > > But it failed at `Set()` where it complained "Using 'Named' > > > > > > as a concrete type conforming to protocol 'Hashable' is not > > > > > > supported”. > > > > > > > > > > > > After watching the WWDC session "Protocol-Oriented Programming in > > > > > > Swift” by Dave Abrahams, I try to use protocols whenever possible. > > > > > > But I can’t seem to overcome this barrier. Set.Element must confirm > > > > > > to Hashable, which inherits from Equatable, which has self > > > > > > requirement, which ultimately means that Set.Element all must be of > > > > > > the same type. So it seems it’s impossible to have heterogeneous > > > > > > items using protocol. Is that the case? > > > > > > > > > > > > My use case is this: > > > > > > > > > > > > I have an object that can contain two sets of other objects: > > > > > > > > > > > > ``` > > > > > > class Parent { > > > > > > var foos: Set > > > > > > var bars: Set > > > > > > } > > > > > > ``` > > > > > > > > > > > > I want to define a computed property “all” that is the union of the > > > > > > two sets.
Re: [swift-users] Is it possible to store a set of heterogeneous items with protocol?
If the solution you seek is not designed so that the module user can extend the set of types then you could wrap your types into enum cases and use the enum for your set. ;) When Swift will support anonymous enum cases, this will be an elegant solution to these type of things. -- Adrian Zubarev Sent with Airmail Am 11. Juli 2017 um 14:46:12, Glen Huang via swift-users (swift-users@swift.org(mailto:swift-users@swift.org)) schrieb: > > Thanks for bringing AnyHashable to my attention. > > It works, but the types are now erased. I want to have a union of the two > sets because I want to loop over it to treat each contained item as Named, so > I can process them as though they are of the same type. Is this type of use > case really should be addressed using super class? > > > On 11 Jul 2017, at 7:38 PM, Howard Lovatt > >wrote: > > You can have a set of AnyHashable: > > > > > var item = Set() > > > item.insert(AnyHashable(Foo())) > > > item.insert(AnyHashable(Bar())) > > > > Depends what you will do with the set if this is viable or not. You can > > also use classes and ObjectID. > > > > You might want this though: > > > > > var item = [AnyHashable: Any] > > extension Dictionary where Key == AnyHashable, Value: Hashable { > > func insert(_ value: Value) { > > self[AnyHashable(value)] == value > > } > > } > > > item.insert(Foo()) > > > item.insert(Bar()) > > > > So you get at the stored value. > > > > -- Howard. > > > > On 11 Jul 2017, at 8:09 pm, Glen Huang via swift-users > > wrote: > > > > > Hi, > > > > > > I want to store some heterogeneous items all conform to a protocol inside > > > a set, is it something possible to do in swift? > > > > > > I tried this example: > > > > > > ``` > > > protocol Named: Hashable { > > > var name: String { get } > > > } > > > > > > extension Named { > > > var hashValue: Int { > > > return name.hashValue > > > } > > > > > > static func ==(lhs: Self, rhs: Self) -> Bool { > > > return lhs.name == rhs.name > > > } > > > } > > > > > > struct Foo: Named { > > > var name = "foo" > > > } > > > > > > struct Bar: Named { > > > var name = "bar" > > > } > > > > > > var item = Set() > > > item.insert(Foo()) > > > item.insert(Bar()) > > > ``` > > > > > > But it failed at `Set()` where it complained "Using 'Named' as a > > > concrete type conforming to protocol 'Hashable' is not supported”. > > > > > > After watching the WWDC session "Protocol-Oriented Programming in Swift” > > > by Dave Abrahams, I try to use protocols whenever possible. But I can’t > > > seem to overcome this barrier. Set.Element must confirm to Hashable, > > > which inherits from Equatable, which has self requirement, which > > > ultimately means that Set.Element all must be of the same type. So it > > > seems it’s impossible to have heterogeneous items using protocol. Is that > > > the case? > > > > > > My use case is this: > > > > > > I have an object that can contain two sets of other objects: > > > > > > ``` > > > class Parent { > > > var foos: Set > > > var bars: Set > > > } > > > ``` > > > > > > I want to define a computed property “all” that is the union of the two > > > sets. Foo and Bar conform to the same protocol. I wonder what return type > > > I should use for the union? Do I have to go back to OOP and define a > > > super class for Foo and Bar? > > > > > > Thanks. > > > ___ > > > swift-users mailing list > > > swift-users@swift.org(mailto:swift-users@swift.org) > > > https://lists.swift.org/mailman/listinfo/swift-users > > ___ > swift-users mailing list > swift-users@swift.org > https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] How to write better Swift
It should be willSet because in the example the job is executed before the new value is set. class SomeClass { var status: Int { willSet { guard newValue != self.status { return } // do something here } } } -- Adrian Zubarev Sent with Airmail Am 10. Juli 2017 um 17:35:34, Geordie J via swift-users (swift-users@swift.org) schrieb: Would "didSet" on a normal variable work for you? var status: Int { didSet { doSomething() } } Geordie > Am 10.07.2017 um 17:34 schrieb Gerriet M. Denkmann via swift-users >: > > This works (Xcode Version 8.3.2 (8E2002)): > > class SomeClass > { > private var privateStatus: Int > > var status: Int > { > get{ return privateStatus } > set(new) > { > if new == privateStatus {return} > > … do something here … > > privateStatus = new > } > } > } > > But is this “privateStatus” really necessary? > If not, how can it be avoided? > > Gerriet. > > ___ > swift-users mailing list > swift-users@swift.org > https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] is this a defect in equatable for swift tuples?
Easy: class SomeClass : Equatable { -- Adrian Zubarev Sent with Airmail Am 9. Juli 2017 um 17:11:14, David Baraff via swift-users (swift-users@swift.org) schrieb: Given 2-tuples of type (T1, T2), you should be able to invoke the == operator if you could on both types T1 and T2, right? i.e. (“abc”, 3) == (“abc”, 4) // legal but: class SomeClass { static public func ==(_ lhs:SomeClass, _ rhs:SomeClass) -> Bool { return lhs === rhs } } let c1 = SomeClass() let c2 = SomeClass() let t1 = ("abc", c1) let t2 = ("abc", c2) c1 == c2 // legal t1 == t2 // illegal Why is t1 == t2 not legal given that c1 == c2 IS legal? ___ 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] did i just imagine tuples were going to be hashable in swift 4?
Welcome to the group of people who thinks that the character from Monopoly had a monocle, including myself. You've just experienced a transdimensional jump from your universe without even notecing, but where Swift 4 actually had hashable tuples. :) Jokes aside, I haven't read anything about it in this universe, at least not for Swift 4. -- Adrian Zubarev Sent with Airmail Am 7. Juli 2017 um 04:40:55, David Baraff via swift-users (swift-users@swift.org(mailto:swift-users@swift.org)) schrieb: > > I thought I read that tuples would finally be hashable in swift 4, allowing > for them to be used in dictionaries/sets, but now that i google for it, i > find no mention of it. > > are there any plans? so often i just want to quickly create a dictionary set > from a tuple of an integer or string or two, and not being able to do so is > just plain annoying. > > ___ > 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] the pain of strings
Plus if you want to play with Swift 4 without running a toolchain or the new Xcode you can do it in your browser: https://swift.sandbox.bluemix.net/#/repl Just change that repl to Swift 4. -- Adrian Zubarev Sent with Airmail Am 1. Juli 2017 um 03:02:38, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: The best docs you can get without Xcode I know about is this one here: https://developer.apple.com/documentation/swift/string In Swift 4 a String will yet again become a collection type. -- Adrian Zubarev Sent with Airmail Am 1. Juli 2017 um 02:57:05, David Baraff (davidbar...@gmail.com) schrieb: I only know a little bit of what I’ve read online in blog posts and such. I don’t have access to the Swift 4 API documentation, since i’m not running the xcode beta yet. Is there someplace I can see the actual new API’s for String, in swift 4? i googled but haven’t found it yet. On Jun 30, 2017, at 5:44 PM, Adrian Zubarevwrote: Well you’ve mentioned Swift 4 in your original post, therefore I provided a solution using Swift 4. It’s returning a view called `Substring`. -- Adrian Zubarev Sent with Airmail Am 1. Juli 2017 um 00:38:42, David Baraff (davidbar...@gmail.com) schrieb: I’m sorry, but I don’t see suffix() as a member function in any documentation, nor does it complete in Xcode. Is this perhaps only in Swift 4? If so, that’s a definite improvement! Begin forwarded message: From: Adrian Zubarev Subject: Re: [swift-users] the pain of strings Date: June 30, 2017 at 3:13:42 PM PDT To: David Baraff Cc: swift-users@swift.org This looks way better than the subscript in Python and 1000 times better than your example. It might be a good idea to look up possible API first before writing such ugly long lines. I mean they get the job done, but just why so complicated? :( -- Adrian Zubarev Sent with Airmail Am 1. Juli 2017 um 00:08:47, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: let longString = "1234567890" print(longString.suffix(2)) // prints "90" -- Adrian Zubarev Sent with Airmail Am 30. Juni 2017 um 23:45:01, David Baraff via swift-users (swift-users@swift.org) schrieb: I know, I’ve read tons about about this. I sympathize. Unicode, it’s all very complex. But. BUT. Python: shortID = longerDeviceID[-2:] # give me the last two characters Swift: let shortID = String(longerDeviceID.characters.dropFirst(longerDeviceID.characters.count - 2)) I can’t even read the above without my eyes glazing over. As has been pointed out, an API which demands this much verbosity is crippling for many developers, to say the least. With Swift 4, am I correct that it will be at least: let shortID = String(longerDeviceID.dropFirst(longerDeviceID.count - 2)) ___ 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] the pain of strings
The best docs you can get without Xcode I know about is this one here: https://developer.apple.com/documentation/swift/string In Swift 4 a String will yet again become a collection type. -- Adrian Zubarev Sent with Airmail Am 1. Juli 2017 um 02:57:05, David Baraff (davidbar...@gmail.com) schrieb: I only know a little bit of what I’ve read online in blog posts and such. I don’t have access to the Swift 4 API documentation, since i’m not running the xcode beta yet. Is there someplace I can see the actual new API’s for String, in swift 4? i googled but haven’t found it yet. On Jun 30, 2017, at 5:44 PM, Adrian Zubarevwrote: Well you’ve mentioned Swift 4 in your original post, therefore I provided a solution using Swift 4. It’s returning a view called `Substring`. -- Adrian Zubarev Sent with Airmail Am 1. Juli 2017 um 00:38:42, David Baraff (davidbar...@gmail.com) schrieb: I’m sorry, but I don’t see suffix() as a member function in any documentation, nor does it complete in Xcode. Is this perhaps only in Swift 4? If so, that’s a definite improvement! Begin forwarded message: From: Adrian Zubarev Subject: Re: [swift-users] the pain of strings Date: June 30, 2017 at 3:13:42 PM PDT To: David Baraff Cc: swift-users@swift.org This looks way better than the subscript in Python and 1000 times better than your example. It might be a good idea to look up possible API first before writing such ugly long lines. I mean they get the job done, but just why so complicated? :( -- Adrian Zubarev Sent with Airmail Am 1. Juli 2017 um 00:08:47, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: let longString = "1234567890" print(longString.suffix(2)) // prints "90" -- Adrian Zubarev Sent with Airmail Am 30. Juni 2017 um 23:45:01, David Baraff via swift-users (swift-users@swift.org) schrieb: I know, I’ve read tons about about this. I sympathize. Unicode, it’s all very complex. But. BUT. Python: shortID = longerDeviceID[-2:] # give me the last two characters Swift: let shortID = String(longerDeviceID.characters.dropFirst(longerDeviceID.characters.count - 2)) I can’t even read the above without my eyes glazing over. As has been pointed out, an API which demands this much verbosity is crippling for many developers, to say the least. With Swift 4, am I correct that it will be at least: let shortID = String(longerDeviceID.dropFirst(longerDeviceID.count - 2)) ___ 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] the pain of strings
Well you’ve mentioned Swift 4 in your original post, therefore I provided a solution using Swift 4. It’s returning a view called `Substring`. -- Adrian Zubarev Sent with Airmail Am 1. Juli 2017 um 00:38:42, David Baraff (davidbar...@gmail.com) schrieb: I’m sorry, but I don’t see suffix() as a member function in any documentation, nor does it complete in Xcode. Is this perhaps only in Swift 4? If so, that’s a definite improvement! Begin forwarded message: From: Adrian ZubarevSubject: Re: [swift-users] the pain of strings Date: June 30, 2017 at 3:13:42 PM PDT To: David Baraff Cc: swift-users@swift.org This looks way better than the subscript in Python and 1000 times better than your example. It might be a good idea to look up possible API first before writing such ugly long lines. I mean they get the job done, but just why so complicated? :( -- Adrian Zubarev Sent with Airmail Am 1. Juli 2017 um 00:08:47, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: let longString = "1234567890" print(longString.suffix(2)) // prints "90" -- Adrian Zubarev Sent with Airmail Am 30. Juni 2017 um 23:45:01, David Baraff via swift-users (swift-users@swift.org) schrieb: I know, I’ve read tons about about this. I sympathize. Unicode, it’s all very complex. But. BUT. Python: shortID = longerDeviceID[-2:] # give me the last two characters Swift: let shortID = String(longerDeviceID.characters.dropFirst(longerDeviceID.characters.count - 2)) I can’t even read the above without my eyes glazing over. As has been pointed out, an API which demands this much verbosity is crippling for many developers, to say the least. With Swift 4, am I correct that it will be at least: let shortID = String(longerDeviceID.dropFirst(longerDeviceID.count - 2)) ___ 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] the pain of strings
let longString = "1234567890" print(longString.suffix(2)) // prints "90" -- Adrian Zubarev Sent with Airmail Am 30. Juni 2017 um 23:45:01, David Baraff via swift-users (swift-users@swift.org) schrieb: I know, I’ve read tons about about this. I sympathize. Unicode, it’s all very complex. But. BUT. Python: shortID = longerDeviceID[-2:] # give me the last two characters Swift: let shortID = String(longerDeviceID.characters.dropFirst(longerDeviceID.characters.count - 2)) I can’t even read the above without my eyes glazing over. As has been pointed out, an API which demands this much verbosity is crippling for many developers, to say the least. With Swift 4, am I correct that it will be at least: let shortID = String(longerDeviceID.dropFirst(longerDeviceID.count - 2)) ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Is "lazy let" on the schedule anywhere?
I myself highly want lazy constants (I’m tired of writing something like file private private(set) lazy var propertyName: ReferenceType just to hide the setter from the rest of the codebase), but I don’t think this will ever happen in Swift, at least not as an improvement for the lazy keyword itself. Joe Groff had a really awesome proposal last year, which is currently in a deferred state but will be resurrected in the future. https://github.com/apple/swift-evolution/blob/master/proposals/0030-property-behavior-decls.md It’s simply is a prioritization question, when this will happen. That said, I’d expect some kind of readOnlyLazy property behavior that will match the mentioned lazy let. -- Adrian Zubarev Sent with Airmail Am 26. Juni 2017 um 21:32:35, Edward Connell via swift-users (swift-users@swift.org) schrieb: It sure would be nice if the compiler supported lazy lets for structs. Any idea when or if this will be supported? Seems like a nice performance win, lazy var is a pain because you can't access arguments passed into a function without mutation complaints. Thanks, Ed ___ 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] Applying MVC pattern to iOS Swift apps
Well you are right this is not the right place for such questions, because this mailing list is about pure Swift topics. Think about MVC as MVVM where M = M, V = V and C = VM. Don't get confused by the `Controller` suffix, especially there is no `ViewController` suffix, because it always is and should be view name + controller suffix. That said, a view(controller) is a view and not a ViewModel. For navigation one could extend MVVM with a C for Coordinator (MVVM-C). I just said that you habe to think of MVC as MVVM. If you now apply the extended MVVM-C version backwards you'll get MVC-C, latter naming is confusing right!? ^^ Usually AppDelegate is your main object in your project, except if you need a custom subclass of UIApplication. MVVM-C is a good bullet proof arch. If you try to rethink everything that way you'll quickly notice how you can/should link your objects in such a project. Furthermore you should seperate your business logic completely from everything else, so that is kinda modular. This will help you testing your app and logic better and mantain a good app arch. Hopefully I could help you a little. -- Adrian Zubarev Sent with Airmail Am 23. Juni 2017 um 11:41:51, Roy Henderson via swift-users (swift-users@swift.org(mailto:swift-users@swift.org)) schrieb: > > Firstly, my apologies for submitting a question which is perhaps not strictly > on-topic but hopefully the list will permit me a little latitude. > > Thinking specifically of iOS Swift application design architecture I would be > very interested to hear how other members map traditional MVC patterns to the > architecture of the standard Xcode templates? > > Should controller functions be incorporated in the AppDelegate or is it > better to keep the AppDelegate minimal and put them in a separate controller > module? > > Is there any sensible demarcation point regarding which controller functions > are acceptable in a ViewController? Does it make better sense to include them > in the ViewController most closely associated with their actions or are they > better placed in a separate module? In particular, I am trying to avoid > breaking the rule regarding never having the V communicate directly with the > M. > > I appreciate this is a rather general question with no single right answer. I > am happy simply to be pointed towards any guidance documentation which > members may be aware of. I have read some of the Apple documentation but have > not yet found any definitive answer. > > Thank you, > > Roy > ___ > 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] swift 4.0 "swift-version 4" errors with "type(of:"
Well, I think it’s a step forward by making type(of:) *like* a stdlib function. Now we need to change .Type and .Protocol syntax to something like Type, AnyType and also fix the way it behaves in a generic context to finally open up Type for custom type names. This should also help removing .self. =) -- Adrian Zubarev Sent with Airmail Am 20. Mai 2017 um 00:42:27, David Hart via swift-users (swift-users@swift.org) schrieb: That's worrisome. type is such a common identifier that I worry its going to break a lot of code, create some confusion and force the un-esthetic qualifying. On 19 May 2017, at 21:38, Slava Pestov via swift-userswrote: Do you have a member named ‘type’ in the current scope? We changed the behavior of type(of:) so that it behaves like a normal declaration in the Swift module instead of a special keyword. Unfortunately this means if you have a ‘type’ already visible in scope, you have to fully qualify Swift.type(of:). Slava On May 19, 2017, at 11:18 AM, Edward Connell via swift-users wrote: When running the compiler using the "-swift-version 4" flag, the compiler complains about creating a dynamic type. Errors are flagged from within concrete base classes and also within protocol extensions. error: cannot invoke 'type' with an argument list of type '(of: Self)' let newObject = type(of: self).init() Has this changed?? Are we supposed to create dynamic types a different way now? Thanks, Ed ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Why is static a keyword?
Furthermore: In a class declaration, the static keyword has the same effect as marking the declaration with both the class and final declaration modifiers. Source. -- Adrian Zubarev Sent with Airmail Am 11. Mai 2017 um 19:07:53, Austin Zheng (austinzh...@gmail.com) schrieb: `class` and `static` in classes have subtly different meanings, if I recall correctly. A `class` declaration can be overriden in subclasses; a `static` one can't. Best, Austin On Thu, May 11, 2017 at 10:04 AM, Zhao Xin via swift-userswrote: No. I think it is just a compromise. Zhaoxin On Fri, May 12, 2017 at 1:01 AM, Adrian Zubarev wrote: I don’t think this is the answer that was asked for. I bet it’s more a technical question from the internal point of of view. -- Adrian Zubarev Sent with Airmail Am 11. Mai 2017 um 18:59:58, Zhao Xin via swift-users (swift-users@swift.org) schrieb: In Swift, you use `static in struct and enum` and `class in class`. For example, struct Foo { static func bar() { } } class ClassFoo { class func bar() { } } Another the `class func bar()` can replace to `static` as well. Here the `static` and `class` are equal in functions of classes. And `class` is a keyword. class ClassFoo2 { static func bar() { } } Zhaoxin On Fri, May 12, 2017 at 12:17 AM, Jose Cheyo Jimenez via swift-users wrote: I was expecting static to be a builtin. Does anybody know why it must be a keyword? Background. https://bugs.swift.org/browse/SR-4834 ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Why is static a keyword?
Have you read closely the bug issue before posting your answer? -- Adrian Zubarev Sent with Airmail Am 11. Mai 2017 um 19:05:13, Zhao Xin (owe...@gmail.com) schrieb: No. I think it is just a compromise. Zhaoxin On Fri, May 12, 2017 at 1:01 AM, Adrian Zubarevwrote: I don’t think this is the answer that was asked for. I bet it’s more a technical question from the internal point of of view. -- Adrian Zubarev Sent with Airmail Am 11. Mai 2017 um 18:59:58, Zhao Xin via swift-users (swift-users@swift.org) schrieb: In Swift, you use `static in struct and enum` and `class in class`. For example, struct Foo { static func bar() { } } class ClassFoo { class func bar() { } } Another the `class func bar()` can replace to `static` as well. Here the `static` and `class` are equal in functions of classes. And `class` is a keyword. class ClassFoo2 { static func bar() { } } Zhaoxin On Fri, May 12, 2017 at 12:17 AM, Jose Cheyo Jimenez via swift-users wrote: I was expecting static to be a builtin. Does anybody know why it must be a keyword? Background. https://bugs.swift.org/browse/SR-4834 ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Why is static a keyword?
I don’t think this is the answer that was asked for. I bet it’s more a technical question from the internal point of of view. -- Adrian Zubarev Sent with Airmail Am 11. Mai 2017 um 18:59:58, Zhao Xin via swift-users (swift-users@swift.org) schrieb: In Swift, you use `static in struct and enum` and `class in class`. For example, struct Foo { static func bar() { } } class ClassFoo { class func bar() { } } Another the `class func bar()` can replace to `static` as well. Here the `static` and `class` are equal in functions of classes. And `class` is a keyword. class ClassFoo2 { static func bar() { } } Zhaoxin On Fri, May 12, 2017 at 12:17 AM, Jose Cheyo Jimenez via swift-userswrote: I was expecting static to be a builtin. Does anybody know why it must be a keyword? Background. https://bugs.swift.org/browse/SR-4834 ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] weak self
Not answering the questions, but sharing a neat trick. [weak self] in guard let `self` = self else { return } self.foo() // strong self :) -- Adrian Zubarev Sent with Airmail Am 1. Mai 2017 um 16:46:33, Rien via swift-users (swift-users@swift.org) schrieb: In my code I use a lot of queues. And (very often) I will use [weak self] to prevent doing things when ‘self’ is no longer available. Now I am wondering: how does the compiler know that [weak self] is referenced? I am assuming it keeps a reverse reference from self to the [weak self] in order to ‘nil’ the [weak self] when self is nilled. But when a job is executing it has no control over the exclusive rights to [weak self]. I.e. [weak self] may be nilled by an outside event in the middle of say: if self != nil { return self!.myparam } The if finding [weak self] non nil, but the return finding [weak self] as nil Is that correct? i.e. should we never use the above if construct but always: return self?.myparam ?? 42 Regards, Rien Site: http://balancingrock.nl Blog: http://swiftrien.blogspot.com Github: http://github.com/Balancingrock Project: http://swiftfire.nl - A server for websites build in Swift ___ 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] UIview frame and bounds properties
Have you tried using self.? It’s a good practice to always using self. to avoid issues where the compiler might use other globally available variables/constants functions. -- Adrian Zubarev Sent with Airmail Am 27. April 2017 um 19:28:42, Mohamed Salah via swift-users (swift-users@swift.org) schrieb: Thanks for your support … here you are the piece of code import UIKit class FaceVeiw: UIView { /* it make error to use frame or bounds outside any functions WHY WHY WHY */ let width = frame.size.width // (Gives an ERROR) frame property is not known here let width2 = bounds.size.width // Gives an ERROR) bound property is not know here as well override func draw(_ rect: CGRect) { let w = bounds.size.width // however bounds is known here let h = bounds.size.height let w2 = frame.size.width // frame as well known here let h2 = frame.size.height } } On Apr 27, 2017, at 9:23 PM, Saagar Jhawrote: Would you mind sharing the code you’re having trouble with? Saagar Jha On Apr 27, 2017, at 10:22, Mohamed Salah via swift-users wrote: Hi , why UIview frame and bounds properties are not seen outside any functions ? please advise thank you Mohamed Salah ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] UIview frame and bounds properties
First of all, the swift-user list is mainly for Swift related question, which are not related to other frameworks like UIKit. You might find a better answer at Apple developer forums or on stackoverflow. ;) Second, this question is too general and not easy to answer without any code of yours. We need the scopes of your code to solve that issue. -- Adrian Zubarev Sent with Airmail Am 27. April 2017 um 19:22:49, Mohamed Salah via swift-users (swift-users@swift.org) schrieb: Hi , why UIview frame and bounds properties are not seen outside any functions ? please advise thank you Mohamed Salah ___ 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] Xcode Windows
I’m confused, what exactly are you trying to solve? A single view application without the main Storyboard? If that’s the case, take a look at my answer here: http://stackoverflow.com/a/43304755/4572536 Stackoverflow is a better place for such questions. This list is about pure Swift. ;) -- Adrian Zubarev Sent with Airmail Am 13. April 2017 um 11:12:22, LAURENT Charles via swift-users (swift-users@swift.org) schrieb: Hello, My question concerns Xcode Interface : the choice between 1 window and storyBoard The book Apress copyright 2017 macOS Programming for Absolute Beginners Wallace Wang still creates projects using the choice between 1 window and storyBoard The recent update of Xcode Version 8 3 1 apparently creates at first only projects with storyBoard How to proceed next to get a single window ? Thank you very much Charles ___ 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] typealias for Generic in Generic
R is a non generic type, because the generic part is set to T, that’s why R() works. Otherwise you could create typealias Q = Сarriage and use it like this Q() -- Adrian Zubarev Sent with Airmail Am 4. April 2017 um 19:25:45, Седых Александр via swift-users (swift-users@swift.org) schrieb: Hello. I stumbled on ambiguous behaviour of compiler. Is not allowed explicitly indicate type in Generic typealias. struct Сarriage { let g = [T]() } struct Coma { typealias R = Сarriage let m = R() let d = R() \\ error: cannot specialize non-generic type 'Сarriage' var b = Сarriage() mutatingfunc work() { m.g.append(<#T##newElement: T##T#>) \\ what I can write here? b.g.append("Z") } } -- Седых Александр ___ 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] Function conforming to a typealias
Typo, should be instance not istance. -- Adrian Zubarev Sent with Airmail Am 18. Februar 2017 um 12:16:34, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: You’re welcome. I don’t think there is a better way of doing that. However you can build some wrappers with some shortcuts. func createInstance(of _: T.Type, _ istance: T) -> T { return istance } let myGreatFunc1 = createInstance(of: Function.self) { return "\($0) \($1)" // Or whatever } -- Adrian Zubarev Sent with Airmail Am 18. Februar 2017 um 12:05:57, Rien (r...@balancingrock.nl) schrieb: It feels a bit strange to write it like that, but yes, that would work. Thanks! (It will prevent me from having to touch up old functions when adding more parameters to the signature as the project evolves) Regards, Rien Site: http://balancingrock.nl Blog: http://swiftrien.blogspot.com Github: http://github.com/Balancingrock Project: http://swiftfire.nl > On 18 Feb 2017, at 11:52, Adrian Zubarev> wrote: > > Not sure what you’re trying to solve there but you could use it like this > with closures: > > typealias Function = (Int, Bool) -> String? > > let myGreatFunc1: Function = { _ in return nil /* or whatever you need there > */ } > let myGreatFunc2: Function = { _ in return nil } > > > > > -- > Adrian Zubarev > Sent with Airmail > > Am 18. Februar 2017 um 11:47:26, Rien via swift-users (swift-users@swift.org) > schrieb: > >> I want to create a few functions that all have the same signature. >> >> The signature is defined in a typealias >> >> Is there any way to shortcut the function definition, or alternatively >> ensure that the function signature will always be equal to the typealias? >> >> Examplecode: >> >> typealias Mysig = (Int, Bool) -> String? >> >> func myGreatFunc1:Mysig {…} >> >> func myGreatFunc2:Mysig { …} >> >> Alternatively >> >> @conformsTo(Mysig) >> func myGreatFunc1(_ a:Int, _ b: Bool) -> String? {…} >> >> Regards, >> Rien >> >> Site: http://balancingrock.nl >> Blog: http://swiftrien.blogspot.com >> Github: http://github.com/Balancingrock >> Project: http://swiftfire.nl >> >> >> >> >> >> ___ >> 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] Function conforming to a typealias
You’re welcome. I don’t think there is a better way of doing that. However you can build some wrappers with some shortcuts. func createInstance(of _: T.Type, _ istance: T) -> T { return istance } let myGreatFunc1 = createInstance(of: Function.self) { return "\($0) \($1)" // Or whatever } -- Adrian Zubarev Sent with Airmail Am 18. Februar 2017 um 12:05:57, Rien (r...@balancingrock.nl) schrieb: It feels a bit strange to write it like that, but yes, that would work. Thanks! (It will prevent me from having to touch up old functions when adding more parameters to the signature as the project evolves) Regards, Rien Site: http://balancingrock.nl Blog: http://swiftrien.blogspot.com Github: http://github.com/Balancingrock Project: http://swiftfire.nl > On 18 Feb 2017, at 11:52, Adrian Zubarev> wrote: > > Not sure what you’re trying to solve there but you could use it like this > with closures: > > typealias Function = (Int, Bool) -> String? > > let myGreatFunc1: Function = { _ in return nil /* or whatever you need there > */ } > let myGreatFunc2: Function = { _ in return nil } > > > > > -- > Adrian Zubarev > Sent with Airmail > > Am 18. Februar 2017 um 11:47:26, Rien via swift-users (swift-users@swift.org) > schrieb: > >> I want to create a few functions that all have the same signature. >> >> The signature is defined in a typealias >> >> Is there any way to shortcut the function definition, or alternatively >> ensure that the function signature will always be equal to the typealias? >> >> Examplecode: >> >> typealias Mysig = (Int, Bool) -> String? >> >> func myGreatFunc1:Mysig {…} >> >> func myGreatFunc2:Mysig { …} >> >> Alternatively >> >> @conformsTo(Mysig) >> func myGreatFunc1(_ a:Int, _ b: Bool) -> String? {…} >> >> Regards, >> Rien >> >> Site: http://balancingrock.nl >> Blog: http://swiftrien.blogspot.com >> Github: http://github.com/Balancingrock >> Project: http://swiftfire.nl >> >> >> >> >> >> ___ >> 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] Function conforming to a typealias
Not sure what you’re trying to solve there but you could use it like this with closures: typealias Function = (Int, Bool) -> String? let myGreatFunc1: Function = { _ in return nil /* or whatever you need there */ } let myGreatFunc2: Function = { _ in return nil } -- Adrian Zubarev Sent with Airmail Am 18. Februar 2017 um 11:47:26, Rien via swift-users (swift-users@swift.org) schrieb: I want to create a few functions that all have the same signature. The signature is defined in a typealias Is there any way to shortcut the function definition, or alternatively ensure that the function signature will always be equal to the typealias? Examplecode: typealias Mysig = (Int, Bool) -> String? func myGreatFunc1:Mysig {…} func myGreatFunc2:Mysig { …} Alternatively @conformsTo(Mysig) func myGreatFunc1(_ a:Int, _ b: Bool) -> String? {…} Regards, Rien Site: http://balancingrock.nl Blog: http://swiftrien.blogspot.com Github: http://github.com/Balancingrock Project: http://swiftfire.nl ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] How do I word wrap a UIButton title in code?
If I remember correctly the property on the UIButton is called `.lineBreakMode`, which accepts an enum. -- Adrian Zubarev Sent with Airmail Am 28. Januar 2017 um 00:46:18, Mutlu Qwerty via swift-users (swift-users@swift.org(mailto:swift-users@swift.org)) schrieb: > > > How do I make a UIButton wrap lines in the Title? Here is a sample code: > > > > > > > func testing() { > > > let aButton = UIButton(type: .system) > > > aButton.lineWrap = true //How do I make aButton wrap lines? > > > aButton.setTitle("123\n456\n789", for: .normal) > > > self.view.addSubview(aButton) > > > } > > > > > > > What I want to see is a button like this: > > > ——— > > > |123| > > > |456| > > > |789| > > > ——- > > > > > > > This can be done in the Storyboard by selecting “Word Wrap” in the Button’s > Control - Line Break attribute. But I am creating my UIButtons in code and > can not find the proper syntax to code this. > > > > > > > > > > Thomas Cavalli > > > ___ > 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] Why this string not work. Any and Optionals in dictionary
There is no universal `nil`. `nil` is typed. That said think of `nil` as a shorthand form for `Optional.none` -- Adrian Zubarev Sent with Airmail Am 23. Januar 2017 um 11:24:18, Седых Александр via swift-users (swift-users@swift.org(mailto:swift-users@swift.org)) schrieb: > > Hello. > I have a simple expression with Any and is not work. Why? > > > var dictarray: [[String: Any]] = [["kek": nil]] > > \\ Nil is not compatible with expected dictionary value type 'Any' > > > > > > > -- > > And in other hand this is work > > > var dictarray: [[String: Any]] = [[:]] \\ [[:]], dictarray.count = 1 > > > > > Седых Александр ___ > 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] default struct initializer internal even if class declared public
PS: If we’re talking about iOS here than public and open makes less sense as long as you’re not writing a framework for iOS. Each type that is considered to be used in other projects can be seen as an own module, only then access modifiers like public or open makes some sense again. ;) -- Adrian Zubarev Sent with Airmail Am 18. Januar 2017 um 17:45:10, Shawn Erickson (shaw...@gmail.com) schrieb: Yeah I am fairly sure that is by design. A lot of swifts access controls are about getting you up and going with little work / boilerplate while internal to your model while requiring you to be explicit about what you want to expose publicly outside of your module. On Wed, Jan 18, 2017 at 8:40 AM Adrian Zubarev via swift-users <swift-users@swift.org> wrote: I feel like I’ve seen this discussion somewhere on the mailing list before. If I remember correctly or it could be only me, this behavior is by design, because you don’t want to open your API implicitly to everyone. Internally it won’t hurt your module, but only allow you to write less code and use the type right away. It might be your intention of using this init(firstName:lastName) only internally, but disallow the module user from being able to construct that type manually. (The current behavior.) Please feel free to correct me if I’m wrong here ;) -- Adrian Zubarev Sent with Airmail Am 18. Januar 2017 um 16:33:22, Dave Reed via swift-users (swift-users@swift.org) schrieb: I’m teaching an iOS with Swift this semester and one of my students pointed out that: struct Person { var firstName: String var lastName: String } does create a default initializer that you can call as: p = Person(firstName: “Dave”, lastName: “Reed”) but if you write: public struct Person { var firstName: String var lastName: String } The default initializer is still internal so if you want it to be public, you have to write it yourself (i.e.) public struct Person { var firstName: String var lastName: String public init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } } Is there a way around this (other than writing it)? We both agree it would be reasonable/nice that the default initializer have the same protection level as the struct itself. Thanks, Dave Reed ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] default struct initializer internal even if class declared public
I feel like I’ve seen this discussion somewhere on the mailing list before. If I remember correctly or it could be only me, this behavior is by design, because you don’t want to open your API implicitly to everyone. Internally it won’t hurt your module, but only allow you to write less code and use the type right away. It might be your intention of using this init(firstName:lastName) only internally, but disallow the module user from being able to construct that type manually. (The current behavior.) Please feel free to correct me if I’m wrong here ;) -- Adrian Zubarev Sent with Airmail Am 18. Januar 2017 um 16:33:22, Dave Reed via swift-users (swift-users@swift.org) schrieb: I’m teaching an iOS with Swift this semester and one of my students pointed out that: struct Person { var firstName: String var lastName: String } does create a default initializer that you can call as: p = Person(firstName: “Dave”, lastName: “Reed”) but if you write: public struct Person { var firstName: String var lastName: String } The default initializer is still internal so if you want it to be public, you have to write it yourself (i.e.) public struct Person { var firstName: String var lastName: String public init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } } Is there a way around this (other than writing it)? We both agree it would be reasonable/nice that the default initializer have the same protection level as the struct itself. Thanks, Dave Reed ___ 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] Strange Error about Default values
Computed properties do not have any default values. That said, you can only use didSet or willSet on properties like yours to observe them or remove the default value from the computed property completely to use get and set. -- Adrian Zubarev Sent with Airmail Am 18. Januar 2017 um 15:06:16, Wang LiMing via swift-users (swift-users@swift.org) schrieb: In latest Xcode(8.2.1), playground struct S1 { var v = 1 { get { // report Error: Use of unresolved identifier ‘get' return self.v. // report Error: Use of unresolved identifier ‘self' } } I can’t found the reason about the error. ___ 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] Weird protocol behaviour.
I’m not sure what you mean. P is an existential for x: P = … where it is upgraded to the static P in foo, but the static P does not conform to the existential P, which results in an error described by the OP. x: P = … here it’s Any any type that conforms to P. Any is a type of it’s own, and when existentials will be implemented I’d assume that there won’t be any upgrade to P from generic context. let x: Any = … foo(x) // A == Any which should make foo equivalent to // `func foo(_ x: Any)` or the current `func foo(_ x: P)` Right now we just cannot be explicit about existentials. Please correct me if I’m wrong. ;) -- Adrian Zubarev Sent with Airmail Am 23. Dezember 2016 um 13:47:18, Zhao Xin (owe...@gmail.com) schrieb: You mis-labelled you problem in your original email. let x = X() as P // this does not compile. Why? foo(x) The issue is not in line ` let x = X() as P`. It is in line ` foo(x)`, `x's type is P`, but `foo(:)` request a parameter type of `A`, not `P`. `func foo(_ x:A) {}` means, `x` must be `A`, and `A` conforms `P`. But not all `P`s are `A`. Zhaoxin On Fri, Dec 23, 2016 at 5:26 PM, Adrian Zubarev via swift-users <swift-users@swift.org> wrote: Whoops, wait a second. Correcting my self here. Copied the wrong url. Here is the proposal I meant. LINK -- Adrian Zubarev Sent with Airmail Am 23. Dezember 2016 um 09:57:49, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: What are you trying to solve here? Do you heavily rely on what A can be? Can’t you just write func foo(_ x: P) {} (here P is an existential like [in some future] Any)?! AnyObject is for classes, but you’d get the same result changing X to a class ;) If you want scratch the surface of what happens to protocols in a generic context, you could read our proposal about meta types here. -- Adrian Zubarev Sent with Airmail Am 23. Dezember 2016 um 09:43:34, Mikhail Seriukov via swift-users (swift-users@swift.org) schrieb: No it does not. You have made a type out of the parameter. It’s no longer a protocol. IMO the failure here is to understand the difference between a type and a protocol. A type (even if empty) is always a combination of storage with functions (that are assumed to work on the data in storage) A protocol is just a definition of functions without the accompanying data. I see your point. But actually when I write it as `let x = X() as P` I really mean that I want `x` to be `AnyObject` but conforming to P, not just protocol itself. Is it even possible to downcast it this way? 2016-12-23 14:51 GMT+07:00 Marinus van der Lugt <r...@starbase55.com>: On 22 Dec 2016, at 22:43, Howard Lovatt <howard.lov...@gmail.com> wrote: The following variation works: protocol P {} class P1:P {} class X:P1 {} func foo(_ x:A) {} func bar() { //let x = X() // this compiles let x = X() as P1 // this does not compile. Why? foo(x) } Which adds credence to the bug theory. No it does not. You have made a type out of the parameter. It’s no longer a protocol. IMO the failure here is to understand the difference between a type and a protocol. A type (even if empty) is always a combination of storage with functions (that are assumed to work on the data in storage) A protocol is just a definition of functions without the accompanying data. Rien. Note two changes: 1. two levels of inheritance and 2. change to classes. If you do two levels using protocols it doesn't work if you use either classes or structs. -- Howard. On 23 December 2016 at 07:29, Kevin Nattinger <sw...@nattinger.net> wrote: I recall seeing a request on the -evolution list for something like `T := X` to indicate it could be X itself or anything inheriting / implementing it, so it’s certainly known behavior, if not desired. IMO it’s a bug and `:` should be fixed to include the root type, whether or not that requires a discussion on -evolution. On Dec 22, 2016, at 2:17 PM, Howard Lovatt via swift-users <swift-users@swift.org> wrote: I suspect a compiler bug since A is a P. The equivalent in Java works: interface P {} class X implements P {} void foo(A x) {} void bar() { final P x = new X(); foo(x); } -- Howard. On 23 Dec 2016, at 3:19 am, Rien via swift-users <swift-users@swift.org> wrote: IMO the error message says it all: Playground execution failed: error: MyPlayground8.playground:9:5: error: cannot invoke 'foo' with an argument list of type '(P)' foo(x) ^ MyPlayground8.playground:9:5: note: expected an argument list of type '(A)' foo(x) ^ I.e. you are passing in a protocol while the function is specified for a type. Said other way: On which data do you expect the protocol to operate? Regards, Rien Site: http://balancingrock.nl Blog: http://swiftrien.blogspot.com Github: http://github.com/Swiftrien Project: http://swiftfire.nl On 22 Dec 2016, at 17:05, Mikhail Seriukov via swift-users <swift-user
Re: [swift-users] Weird protocol behaviour.
I assume when we get existentials, your problem could be solved like this: protocol P {} class X: P {} func foo(_ x:A) {} func bar() { let x = X() as Any foo(x) } Here A will be Any which conforms to P and makes the compiler happy. let c: P = … here is P and existential like (future) Any. x as P here is P used as a type. It’s weird that the latter is a type but the first example is an existential. I think this is a design choice, because we almost never need the protocol as a type. -- Adrian Zubarev Sent with Airmail Am 23. Dezember 2016 um 09:57:49, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: What are you trying to solve here? Do you heavily rely on what A can be? Can’t you just write func foo(_ x: P) {} (here P is an existential like [in some future] Any)?! AnyObject is for classes, but you’d get the same result changing X to a class ;) If you want scratch the surface of what happens to protocols in a generic context, you could read our proposal about meta types here. -- Adrian Zubarev Sent with Airmail Am 23. Dezember 2016 um 09:43:34, Mikhail Seriukov via swift-users (swift-users@swift.org) schrieb: No it does not. You have made a type out of the parameter. It’s no longer a protocol. IMO the failure here is to understand the difference between a type and a protocol. A type (even if empty) is always a combination of storage with functions (that are assumed to work on the data in storage) A protocol is just a definition of functions without the accompanying data. I see your point. But actually when I write it as `let x = X() as P` I really mean that I want `x` to be `AnyObject` but conforming to P, not just protocol itself. Is it even possible to downcast it this way? 2016-12-23 14:51 GMT+07:00 Marinus van der Lugt: On 22 Dec 2016, at 22:43, Howard Lovatt wrote: The following variation works: protocol P {} class P1:P {} class X:P1 {} func foo(_ x:A) {} func bar() { //let x = X() // this compiles let x = X() as P1 // this does not compile. Why? foo(x) } Which adds credence to the bug theory. No it does not. You have made a type out of the parameter. It’s no longer a protocol. IMO the failure here is to understand the difference between a type and a protocol. A type (even if empty) is always a combination of storage with functions (that are assumed to work on the data in storage) A protocol is just a definition of functions without the accompanying data. Rien. Note two changes: 1. two levels of inheritance and 2. change to classes. If you do two levels using protocols it doesn't work if you use either classes or structs. -- Howard. On 23 December 2016 at 07:29, Kevin Nattinger wrote: I recall seeing a request on the -evolution list for something like `T := X` to indicate it could be X itself or anything inheriting / implementing it, so it’s certainly known behavior, if not desired. IMO it’s a bug and `:` should be fixed to include the root type, whether or not that requires a discussion on -evolution. On Dec 22, 2016, at 2:17 PM, Howard Lovatt via swift-users wrote: I suspect a compiler bug since A is a P. The equivalent in Java works: interface P {} class X implements P {} void foo(A x) {} void bar() { final P x = new X(); foo(x); } -- Howard. On 23 Dec 2016, at 3:19 am, Rien via swift-users wrote: IMO the error message says it all: Playground execution failed: error: MyPlayground8.playground:9:5: error: cannot invoke 'foo' with an argument list of type '(P)' foo(x) ^ MyPlayground8.playground:9:5: note: expected an argument list of type '(A)' foo(x) ^ I.e. you are passing in a protocol while the function is specified for a type. Said other way: On which data do you expect the protocol to operate? Regards, Rien Site: http://balancingrock.nl Blog: http://swiftrien.blogspot.com Github: http://github.com/Swiftrien Project: http://swiftfire.nl On 22 Dec 2016, at 17:05, Mikhail Seriukov via swift-users wrote: Hello community! I' wondering if somebody can explain this to me. Please take look at the snippet. protocol P {} struct X:P {} func foo(_ x:A) {} func bar() { //let x = X() // this compiles let x = X() as P // this does not compile. Why? foo(x) } I expect the both cases to work though. But only first works? And I do not understand why. My coworkers said that it is a compiler bug, but I'm not shure it is. Thanks for the help. ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org
Re: [swift-users] Weird protocol behaviour.
What are you trying to solve here? Do you heavily rely on what A can be? Can’t you just write func foo(_ x: P) {} (here P is an existential like [in some future] Any)?! AnyObject is for classes, but you’d get the same result changing X to a class ;) If you want scratch the surface of what happens to protocols in a generic context, you could read our proposal about meta types here. -- Adrian Zubarev Sent with Airmail Am 23. Dezember 2016 um 09:43:34, Mikhail Seriukov via swift-users (swift-users@swift.org) schrieb: No it does not. You have made a type out of the parameter. It’s no longer a protocol. IMO the failure here is to understand the difference between a type and a protocol. A type (even if empty) is always a combination of storage with functions (that are assumed to work on the data in storage) A protocol is just a definition of functions without the accompanying data. I see your point. But actually when I write it as `let x = X() as P` I really mean that I want `x` to be `AnyObject` but conforming to P, not just protocol itself. Is it even possible to downcast it this way? 2016-12-23 14:51 GMT+07:00 Marinus van der Lugt: On 22 Dec 2016, at 22:43, Howard Lovatt wrote: The following variation works: protocol P {} class P1:P {} class X:P1 {} func foo(_ x:A) {} func bar() { //let x = X() // this compiles let x = X() as P1 // this does not compile. Why? foo(x) } Which adds credence to the bug theory. No it does not. You have made a type out of the parameter. It’s no longer a protocol. IMO the failure here is to understand the difference between a type and a protocol. A type (even if empty) is always a combination of storage with functions (that are assumed to work on the data in storage) A protocol is just a definition of functions without the accompanying data. Rien. Note two changes: 1. two levels of inheritance and 2. change to classes. If you do two levels using protocols it doesn't work if you use either classes or structs. -- Howard. On 23 December 2016 at 07:29, Kevin Nattinger wrote: I recall seeing a request on the -evolution list for something like `T := X` to indicate it could be X itself or anything inheriting / implementing it, so it’s certainly known behavior, if not desired. IMO it’s a bug and `:` should be fixed to include the root type, whether or not that requires a discussion on -evolution. On Dec 22, 2016, at 2:17 PM, Howard Lovatt via swift-users wrote: I suspect a compiler bug since A is a P. The equivalent in Java works: interface P {} class X implements P {} void foo(A x) {} void bar() { final P x = new X(); foo(x); } -- Howard. On 23 Dec 2016, at 3:19 am, Rien via swift-users wrote: IMO the error message says it all: Playground execution failed: error: MyPlayground8.playground:9:5: error: cannot invoke 'foo' with an argument list of type '(P)' foo(x) ^ MyPlayground8.playground:9:5: note: expected an argument list of type '(A)' foo(x) ^ I.e. you are passing in a protocol while the function is specified for a type. Said other way: On which data do you expect the protocol to operate? Regards, Rien Site: http://balancingrock.nl Blog: http://swiftrien.blogspot.com Github: http://github.com/Swiftrien Project: http://swiftfire.nl On 22 Dec 2016, at 17:05, Mikhail Seriukov via swift-users wrote: Hello community! I' wondering if somebody can explain this to me. Please take look at the snippet. protocol P {} struct X:P {} func foo(_ x:A) {} func bar() { //let x = X() // this compiles let x = X() as P // this does not compile. Why? foo(x) } I expect the both cases to work though. But only first works? And I do not understand why. My coworkers said that it is a compiler bug, but I'm not shure it is. Thanks for the help. ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Documentation for Linux-based Swift Development Sought
'.epub' extension is not an iBooks exclusive ;) It's an e-book. Find yourself a capable reader :) -- Adrian Zubarev Sent with Airmail Am 19. Dezember 2016 um 17:43:22, Steven Harms via swift-users (swift-users@swift.org(mailto:swift-users@swift.org)) schrieb: > > Hi, > > I've been playing with Swift in Linux contexts, but I was wondering, how am I > meant to avail myself of reference materials? > > The Swift book is written in iBooks...so I don't have access to that. I'd > love for there to be a PDF equivalent that I could leave on the Linux server > to work with. > > Alternatively, is there a rich HTML download with the classes so that I could > at least browse that? > > Thanks, > > Steven ___ > swift-users mailing list > swift-users@swift.org > https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] How to rewrite this snippet without `existentials`?
Thanks, that works party as needed but I just realize this main idea here is exactly an example where one would need generic protocols, because I cannot overload the function with associatedtype as I’d need it. -- Adrian Zubarev Sent with Airmail Am 2. Dezember 2016 um 13:33:37, Tino Heth (2...@gmx.de) schrieb: Any advice how to rewrite the code so it still would do its job under the hood? I'm not aware of any clean way to do this (with current Swift ;-) — but this hack passes compilation: protocol Proto : class { // `A` is a generic type and therefore should stay as an associatedtype associatedtype A func performWith(_ a: A) } struct Box { var performWith: (B) -> Void init(value: T) where T.A == B { self.performWith = value.performWith } } final class SomeType { var protos: [Box] init(_ protos: [Box]) { self.protos = protos } func callProtosWith(_ b: B) { self.protos.forEach { $0.performWith(b) } } } ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Bool to Int
Where is your problem here? It’s simple and easy ;) extension Integer { init(_ boolean: Bool) { self = boolean ? 1 : 0 } } Int(10 > 4) UInt32(1 <= 2) -- Adrian Zubarev Sent with Airmail Am 22. November 2016 um 00:54:47, Rick Mann via swift-users (swift-users@swift.org) schrieb: > On Nov 21, 2016, at 15:09 , Marco S Hymanwrote: > >> Except it does, because if I write >> >> let a = 2 > >> a is of type Int (at least, according to Xcode's code completion). > > and if you write > > let b = 2 + 0.5 > > 2 is treated as a double. The type of the literal “2” varies with context. Do > you also find that inconsistent and confusing? Nope. I can see how the promotion works. Also, Xcode would tell me b is a Double. > >> But this gives inconsistent results: >> >> let t = true >> >> let a = Int(true) >> let b = Int(t) // Error >> >> I find this to be very inconsistent and confusing. > > t is a Bool and there is no automatic conversion from Bool to Int. > > true is not a Bool. It may be treated as a Bool depending upon context. In > the line `let t = true` it is treated as a Bool. In `let a = Int(true)` it is > treated as an NSNumber (assuming you import foundation). That may be what's happening, but it's still confusing and unintuitive. That something is lost in the transitivity of going through a variable, aside from "literalness", is confusing. And really, it would be nice if the language provided a fast way of getting an number "1" out of a Bool variable true (and 0 out of false). But that conversation is a bigger can of worms than I care to open right now. -- Rick Mann rm...@latencyzero.com ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Bool to Int
A literal doesn’t have a type on its own. Instead, a literal is parsed as having infinite precision and Swift’s type inference attempts to infer a type for the literal. Source -- Adrian Zubarev Sent with Airmail Am 21. November 2016 um 18:46:32, Kenny Leung via swift-users (swift-users@swift.org) schrieb: This is so confusing. "Literals are untyped", but there’s a “BooleanLiteral”, which is obviously of type Boolean. -Kenny > On Nov 21, 2016, at 2:49 AM, Adrian Zubarev via swift-users > <swift-users@swift.org> wrote: > > In general this is a correct behaviour, because literals in Swift are > untyped. Int does not have any initializer for a Bool so the compiler tries > to find a type that might conforms to ExpressibleByBooleanLiteral for all > possible initializer of Int (Int.init(_: TYPE)). This resolution decides to > go with NSNumber in your case?! > > The thing is, when you write Int(a > b), you’re passing a Bool and not a > literal anymore. Here the compiler does not fallback to NSNumber anymore and > reports you an error, because Int.init(_: Bool) does not exist. > > > > > -- > Adrian Zubarev > Sent with Airmail > > Am 21. November 2016 um 04:48:35, Rick Mann via swift-users > (swift-users@swift.org) schrieb: > >> It seems I can't do this: >> >> let r = Int(a > b) >> >> but I can do it with a literal: >> >> let r = Int(true) >> >> I'd like to do this to implement signum without branching, but perhaps >> that's not possible. >> >> -- >> Rick Mann >> rm...@latencyzero.com >> >> >> ___ >> swift-users mailing list >> swift-users@swift.org >> https://lists.swift.org/mailman/listinfo/swift-users > > ___ > swift-users mailing list > swift-users@swift.org > https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Problem with mutable views and COW
What exactly to you mean by unsafe/invalide? If you refer to unowned than yes this is incorrect. That was only part of the first question about isKnownUniquelyReferenced, where I myself missed the part from the docs that says that weak references don’t affect the result. In general DocumentValues has a strong reference to the storage and should be able to outlive Document. I borrowed the main idea from: proposal: https://github.com/natecook1000/swift-evolution/blob/nc-dictionary-collections/proposals/-dictionary-key-and-value-collections.md implementation: https://github.com/apple/swift/compare/master…natecook1000:nc-dictionary But it uses some buildin stuff that I don’t have. :/ -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 16:43:40, Karl (razie...@gmail.com) schrieb: On 18 Nov 2016, at 16:40, Karl <raziel.im+swift-us...@gmail.com> wrote: On 18 Nov 2016, at 13:05, Adrian Zubarev via swift-users <swift-users@swift.org> wrote: Hi there, I just can’t get my head around mutable views and COW. Here is a small example: final class Storage { var keys: [String] = [] var values: [Int] = [] } public struct Document { var _storageReference: Storage public init() { self._storageReference = Storage() } public init(_ values: DocumentValues) { self._storageReference = values._storageReference } public var values: DocumentValues { get { return DocumentValues(self) } set { self = Document(newValue) } } } public struct DocumentValues : MutableCollection { unowned var _storageReference: Storage init(_ document: Document) { self._storageReference = document._storageReference } public var startIndex: Int { return self._storageReference.keys.startIndex } public var endIndex: Int { return self._storageReference.keys.endIndex } public func index(after i: Int) -> Int { return self._storageReference.keys.index(after: i) } public subscript(position: Int) -> Int { get { return _storageReference.values[position] } set { self._storageReference.values[position] = newValue } // That will break COW } } First of all the _storageReference property is unowned because I wanted to check the following: var document = Document() print(CFGetRetainCount(document._storageReference)) //=> 2 print(isKnownUniquelyReferenced(_storageReference)) // true var values = document.values print(CFGetRetainCount(values._storageReference)) //=> 2 print(isKnownUniquelyReferenced(_storageReference)) // false Why is the second check false, even if the property is marked as unowned for the view? Next up, I don’t have an idea how to correctly COW optimize this view. Assume the following scenario: Scenario A: var document = Document() // just assume we already added some values and can mutate safely on a given index // mutation in place document.values[0] = 10 VS: Scenario B: var document = Document() let copy = document // just assume we already added some values and can mutate safely on a given index // mutation in place document.values[0] = 10 // <--- this should only mutate `document` but not `copy` We could change the subscript setter on the mutable view like this: set { if !isKnownUniquelyReferenced(_storageReference) { self._storageReference = ... // clone } self._storageReference.values[position] = newValue } There is only one problem here. We’d end up cloning the storage every time, because as shown in the very first example, even with unowned the function isKnownUniquelyReferenced will return false for scenario A. Any suggestions? PS: In general I also wouldn’t want to use unowned because the view should be able to outlive it’s parent. -- Adrian Zubarev Sent with Airmail ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users This is kind of an invalid/unsafe design IMO; DocumentValues may escape the scope of the Document and the underlying storage may be deallocated. Instead, I’d recommend a function: func withDocumentValues(_ invoke: (inout DocumentValues)->T) -> T { var view = DocumentValues(self) defer { _fixLifetime(view) } Oops.. actually, I think this should be: defer { _fixLifetime(self) } return invoke() } (unfortunately, this isn’t completely safe because somebody could still copy the DocumentValues from their closure, the same way you can copy the pointer from String’s withCString, but that’s a limitation of Swift right now) CC: John McCall, because I read his suggestion in the thread about contiguous memory/borrowing
Re: [swift-users] Problem with mutable views and COW
Nah it’s okay mate. ;) This is the right list, because I ask for help. COW stands for copy-on-write. If you’re interesting on learning something new, read this paragraph https://github.com/apple/swift/blob/7e68e02b4eaa1cf44037a383129cbef60ea55d67/docs/OptimizationTips.rst#advice-use-copy-on-write-semantics-for-large-values -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 16:22:06, Zhao Xin (owe...@gmail.com) schrieb: Sorry. If you are doing something on implementing proposals, you should use [swift-dev] list instead. Yes. I do don't know what the COW means. Zhaoxin On Fri, Nov 18, 2016 at 11:09 PM, Adrian Zubarev <adrian.zuba...@devandartist.com> wrote: I’m sorry but you seem not to understand what I’m asking for! If you don’t know what a mutable view is, please read this proposal to get the basic idea: https://github.com/natecook1000/swift-evolution/blob/nc-dictionary-collections/proposals/-dictionary-key-and-value-collections.md Your answer doesn’t make any sense. -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 16:05:25, Zhao Xin (owe...@gmail.com) schrieb: protocol Copyable { func copy() -> Self } final class Storage:Copyable { var keys: [String] = [] var values: [Int] = [] func copy() -> Storage { let s = Storage() s.keys = keys s.values = values return s } } public struct Document:Copyable { var _storageReference: Storage public init() { self._storageReference = Storage() } public init(_ values: DocumentValues) { self._storageReference = values._storageReference } public var values: DocumentValues { get { return DocumentValues(self) } set { self = Document(newValue) } } public func copy() -> Document { var d = Document() d._storageReference = _storageReference.copy() return d } } var document = Document() let copy = document.copy() // just assume we already added some values and can mutate safely on a given index // mutation in place document.values[0] = 10 // <--- this will only mutate `document` but not `copy` You use `class` property inside `struct`, so the `struct` is no longer copyable. You have to do it yourself. Zhaoxin On Fri, Nov 18, 2016 at 10:09 PM, Adrian Zubarev <adrian.zuba...@devandartist.com> wrote: Ups sorry for CCing the post to the evolution list. That happens from time to time. :/ -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 15:07:43, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: I apologize about the weak/unowned issue I mentioned. I kinda missed that portion from the docs Weak references do not affect the result of this function.. Okay it’s clear to me now why the result is evaluated as false. But how do I solve the COW problem for mutable views? -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 15:04:55, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: This doesn’t make any sense. Somewhere from the Swift book: Weak and unowned references enable one instance in a reference cycle to refer to the other instance without keeping a strong hold on it. The instances can then refer to each other without creating a strong reference cycle. From the sdlib of the function isKnownUniquelyReferenced: Returns a Boolean value indicating whether the given object is a class instance known to have a single strong reference. unowned doesn’t increase the reference count, so the view in the examples I showed should have no strong reference to that class instance. The only strong reference that exists is from Document. So why exactly is the result of the second isKnownUniquelyReferenced call false again? -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 14:50:57, Zhao Xin (owe...@gmail.com) schrieb: >Why is the second check false, even if the property is marked as unowned for >the view? Please search the mailing list, this is not the first time it comes as a new question. Shortly speaking, it is `false` only because you used `unowned`. If you you can grantee it always exists. Just use it directly, this is what `unowned` for. If you can't grantee that. You should use `weak` and check it with `if let` or `if foo == nil` Zhaoxin On Fri, Nov 18, 2016 at 8:05 PM, Adrian Zubarev via swift-users <swift-users@swift.org> wrote: Hi there, I just can’t get my head around mutable views and COW. Here is a small example: final class Storage { var keys: [String] = [] var values: [Int] = [] } public struct Document { var _storageReference: Storage public init() { self._storageReference = Storage() } public init(_ values: DocumentValues) { self._storage
Re: [swift-users] Problem with mutable views and COW
I’m sorry but you seem not to understand what I’m asking for! If you don’t know what a mutable view is, please read this proposal to get the basic idea: https://github.com/natecook1000/swift-evolution/blob/nc-dictionary-collections/proposals/-dictionary-key-and-value-collections.md Your answer doesn’t make any sense. -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 16:05:25, Zhao Xin (owe...@gmail.com) schrieb: protocol Copyable { func copy() -> Self } final class Storage:Copyable { var keys: [String] = [] var values: [Int] = [] func copy() -> Storage { let s = Storage() s.keys = keys s.values = values return s } } public struct Document:Copyable { var _storageReference: Storage public init() { self._storageReference = Storage() } public init(_ values: DocumentValues) { self._storageReference = values._storageReference } public var values: DocumentValues { get { return DocumentValues(self) } set { self = Document(newValue) } } public func copy() -> Document { var d = Document() d._storageReference = _storageReference.copy() return d } } var document = Document() let copy = document.copy() // just assume we already added some values and can mutate safely on a given index // mutation in place document.values[0] = 10 // <--- this will only mutate `document` but not `copy` You use `class` property inside `struct`, so the `struct` is no longer copyable. You have to do it yourself. Zhaoxin On Fri, Nov 18, 2016 at 10:09 PM, Adrian Zubarev <adrian.zuba...@devandartist.com> wrote: Ups sorry for CCing the post to the evolution list. That happens from time to time. :/ -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 15:07:43, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: I apologize about the weak/unowned issue I mentioned. I kinda missed that portion from the docs Weak references do not affect the result of this function.. Okay it’s clear to me now why the result is evaluated as false. But how do I solve the COW problem for mutable views? -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 15:04:55, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: This doesn’t make any sense. Somewhere from the Swift book: Weak and unowned references enable one instance in a reference cycle to refer to the other instance without keeping a strong hold on it. The instances can then refer to each other without creating a strong reference cycle. From the sdlib of the function isKnownUniquelyReferenced: Returns a Boolean value indicating whether the given object is a class instance known to have a single strong reference. unowned doesn’t increase the reference count, so the view in the examples I showed should have no strong reference to that class instance. The only strong reference that exists is from Document. So why exactly is the result of the second isKnownUniquelyReferenced call false again? -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 14:50:57, Zhao Xin (owe...@gmail.com) schrieb: >Why is the second check false, even if the property is marked as unowned for >the view? Please search the mailing list, this is not the first time it comes as a new question. Shortly speaking, it is `false` only because you used `unowned`. If you you can grantee it always exists. Just use it directly, this is what `unowned` for. If you can't grantee that. You should use `weak` and check it with `if let` or `if foo == nil` Zhaoxin On Fri, Nov 18, 2016 at 8:05 PM, Adrian Zubarev via swift-users <swift-users@swift.org> wrote: Hi there, I just can’t get my head around mutable views and COW. Here is a small example: final class Storage { var keys: [String] = [] var values: [Int] = [] } public struct Document { var _storageReference: Storage public init() { self._storageReference = Storage() } public init(_ values: DocumentValues) { self._storageReference = values._storageReference } public var values: DocumentValues { get { return DocumentValues(self) } set { self = Document(newValue) } } } public struct DocumentValues : MutableCollection { unowned var _storageReference: Storage init(_ document: Document) { self._storageReference = document._storageReference } public var startIndex: Int { return self._storageReference.keys.startIndex } public var endIndex: Int { return self._storageReference.keys.endIndex } public f
Re: [swift-users] Problem with mutable views and COW
Ups sorry for CCing the post to the evolution list. That happens from time to time. :/ -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 15:07:43, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: I apologize about the weak/unowned issue I mentioned. I kinda missed that portion from the docs Weak references do not affect the result of this function.. Okay it’s clear to me now why the result is evaluated as false. But how do I solve the COW problem for mutable views? -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 15:04:55, Adrian Zubarev (adrian.zuba...@devandartist.com) schrieb: This doesn’t make any sense. Somewhere from the Swift book: Weak and unowned references enable one instance in a reference cycle to refer to the other instance without keeping a strong hold on it. The instances can then refer to each other without creating a strong reference cycle. From the sdlib of the function isKnownUniquelyReferenced: Returns a Boolean value indicating whether the given object is a class instance known to have a single strong reference. unowned doesn’t increase the reference count, so the view in the examples I showed should have no strong reference to that class instance. The only strong reference that exists is from Document. So why exactly is the result of the second isKnownUniquelyReferenced call false again? -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 14:50:57, Zhao Xin (owe...@gmail.com) schrieb: >Why is the second check false, even if the property is marked as unowned for >the view? Please search the mailing list, this is not the first time it comes as a new question. Shortly speaking, it is `false` only because you used `unowned`. If you you can grantee it always exists. Just use it directly, this is what `unowned` for. If you can't grantee that. You should use `weak` and check it with `if let` or `if foo == nil` Zhaoxin On Fri, Nov 18, 2016 at 8:05 PM, Adrian Zubarev via swift-users <swift-users@swift.org> wrote: Hi there, I just can’t get my head around mutable views and COW. Here is a small example: final class Storage { var keys: [String] = [] var values: [Int] = [] } public struct Document { var _storageReference: Storage public init() { self._storageReference = Storage() } public init(_ values: DocumentValues) { self._storageReference = values._storageReference } public var values: DocumentValues { get { return DocumentValues(self) } set { self = Document(newValue) } } } public struct DocumentValues : MutableCollection { unowned var _storageReference: Storage init(_ document: Document) { self._storageReference = document._storageReference } public var startIndex: Int { return self._storageReference.keys.startIndex } public var endIndex: Int { return self._storageReference.keys.endIndex } public func index(after i: Int) -> Int { return self._storageReference.keys.index(after: i) } public subscript(position: Int) -> Int { get { return _storageReference.values[position] } set { self._storageReference.values[position] = newValue } // That will break COW } } First of all the _storageReference property is unowned because I wanted to check the following: var document = Document() print(CFGetRetainCount(document._storageReference)) //=> 2 print(isKnownUniquelyReferenced(_storageReference)) // true var values = document.values print(CFGetRetainCount(values._storageReference)) //=> 2 print(isKnownUniquelyReferenced(_storageReference)) // false Why is the second check false, even if the property is marked as unowned for the view? Next up, I don’t have an idea how to correctly COW optimize this view. Assume the following scenario: Scenario A: var document = Document() // just assume we already added some values and can mutate safely on a given index // mutation in place document.values[0] = 10 VS: Scenario B: var document = Document() let copy = document // just assume we already added some values and can mutate safely on a given index // mutation in place document.values[0] = 10 // <--- this should only mutate `document` but not `copy` We could change the subscript setter on the mutable view like this: set { if !isKnownUniquelyReferenced(_storageReference) { self._storageReference = ... // clone } self._storageReference.values[position] = newValue } There is only one problem here. We’d end up cloning the storage every time, because as shown in the very first example, even with unowned the function isKnownUniquelyR
Re: [swift-users] Problem with mutable views and COW
This doesn’t make any sense. Somewhere from the Swift book: Weak and unowned references enable one instance in a reference cycle to refer to the other instance without keeping a strong hold on it. The instances can then refer to each other without creating a strong reference cycle. From the sdlib of the function isKnownUniquelyReferenced: Returns a Boolean value indicating whether the given object is a class instance known to have a single strong reference. unowned doesn’t increase the reference count, so the view in the examples I showed should have no strong reference to that class instance. The only strong reference that exists is from Document. So why exactly is the result of the second isKnownUniquelyReferenced call false again? -- Adrian Zubarev Sent with Airmail Am 18. November 2016 um 14:50:57, Zhao Xin (owe...@gmail.com) schrieb: >Why is the second check false, even if the property is marked as unowned for >the view? Please search the mailing list, this is not the first time it comes as a new question. Shortly speaking, it is `false` only because you used `unowned`. If you you can grantee it always exists. Just use it directly, this is what `unowned` for. If you can't grantee that. You should use `weak` and check it with `if let` or `if foo == nil` Zhaoxin On Fri, Nov 18, 2016 at 8:05 PM, Adrian Zubarev via swift-users <swift-users@swift.org> wrote: Hi there, I just can’t get my head around mutable views and COW. Here is a small example: final class Storage { var keys: [String] = [] var values: [Int] = [] } public struct Document { var _storageReference: Storage public init() { self._storageReference = Storage() } public init(_ values: DocumentValues) { self._storageReference = values._storageReference } public var values: DocumentValues { get { return DocumentValues(self) } set { self = Document(newValue) } } } public struct DocumentValues : MutableCollection { unowned var _storageReference: Storage init(_ document: Document) { self._storageReference = document._storageReference } public var startIndex: Int { return self._storageReference.keys.startIndex } public var endIndex: Int { return self._storageReference.keys.endIndex } public func index(after i: Int) -> Int { return self._storageReference.keys.index(after: i) } public subscript(position: Int) -> Int { get { return _storageReference.values[position] } set { self._storageReference.values[position] = newValue } // That will break COW } } First of all the _storageReference property is unowned because I wanted to check the following: var document = Document() print(CFGetRetainCount(document._storageReference)) //=> 2 print(isKnownUniquelyReferenced(_storageReference)) // true var values = document.values print(CFGetRetainCount(values._storageReference)) //=> 2 print(isKnownUniquelyReferenced(_storageReference)) // false Why is the second check false, even if the property is marked as unowned for the view? Next up, I don’t have an idea how to correctly COW optimize this view. Assume the following scenario: Scenario A: var document = Document() // just assume we already added some values and can mutate safely on a given index // mutation in place document.values[0] = 10 VS: Scenario B: var document = Document() let copy = document // just assume we already added some values and can mutate safely on a given index // mutation in place document.values[0] = 10 // <--- this should only mutate `document` but not `copy` We could change the subscript setter on the mutable view like this: set { if !isKnownUniquelyReferenced(_storageReference) { self._storageReference = ... // clone } self._storageReference.values[position] = newValue } There is only one problem here. We’d end up cloning the storage every time, because as shown in the very first example, even with unowned the function isKnownUniquelyReferenced will return false for scenario A. Any suggestions? PS: In general I also wouldn’t want to use unowned because the view should be able to outlive it’s parent. -- Adrian Zubarev Sent with Airmail ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
[swift-users] Problem with mutable views and COW
Hi there, I just can’t get my head around mutable views and COW. Here is a small example: final class Storage { var keys: [String] = [] var values: [Int] = [] } public struct Document { var _storageReference: Storage public init() { self._storageReference = Storage() } public init(_ values: DocumentValues) { self._storageReference = values._storageReference } public var values: DocumentValues { get { return DocumentValues(self) } set { self = Document(newValue) } } } public struct DocumentValues : MutableCollection { unowned var _storageReference: Storage init(_ document: Document) { self._storageReference = document._storageReference } public var startIndex: Int { return self._storageReference.keys.startIndex } public var endIndex: Int { return self._storageReference.keys.endIndex } public func index(after i: Int) -> Int { return self._storageReference.keys.index(after: i) } public subscript(position: Int) -> Int { get { return _storageReference.values[position] } set { self._storageReference.values[position] = newValue } // That will break COW } } First of all the _storageReference property is unowned because I wanted to check the following: var document = Document() print(CFGetRetainCount(document._storageReference)) //=> 2 print(isKnownUniquelyReferenced(_storageReference)) // true var values = document.values print(CFGetRetainCount(values._storageReference)) //=> 2 print(isKnownUniquelyReferenced(_storageReference)) // false Why is the second check false, even if the property is marked as unowned for the view? Next up, I don’t have an idea how to correctly COW optimize this view. Assume the following scenario: Scenario A: var document = Document() // just assume we already added some values and can mutate safely on a given index // mutation in place document.values[0] = 10 VS: Scenario B: var document = Document() let copy = document // just assume we already added some values and can mutate safely on a given index // mutation in place document.values[0] = 10 // <--- this should only mutate `document` but not `copy` We could change the subscript setter on the mutable view like this: set { if !isKnownUniquelyReferenced(_storageReference) { self._storageReference = ... // clone } self._storageReference.values[position] = newValue } There is only one problem here. We’d end up cloning the storage every time, because as shown in the very first example, even with unowned the function isKnownUniquelyReferenced will return false for scenario A. Any suggestions? PS: In general I also wouldn’t want to use unowned because the view should be able to outlive it’s parent. -- Adrian Zubarev Sent with Airmail ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Custom little/big endian data structure.
Hi Chris, thank you for your answer. I can’t wait for property behaviors, it’s going to be such a powerful feature. :) -- Adrian Zubarev Sent with Airmail Am 1. November 2016 um 18:34:55, Chris Lattner (clatt...@apple.com) schrieb: On Oct 30, 2016, at 12:50 PM, Adrian Zubarev via swift-users <swift-users@swift.org> wrote: Hi there, is there actually a way to build a custom data structure that will automatically be converted to little/big endian on a little/big endian system, just like (U)Int16/32/64 do? I could build as a workaround a mechanism that will do that for me, but I’m curious if this is possible with some workaround. Hi Adrian, This isn’t something that Swift provides a magic answer to today, but it seems possible that the “property behaviors” proposal (which is currently shelved, but will hopefully come back in the future) could be used to address this. -Chris ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
[swift-users] Custom little/big endian data structure.
Hi there, is there actually a way to build a custom data structure that will automatically be converted to little/big endian on a little/big endian system, just like (U)Int16/32/64 do? I could build as a workaround a mechanism that will do that for me, but I’m curious if this is possible with some workaround. Specifically, I’m talking about a 128 Bit data structure. Best regards, -- Adrian Zubarev Sent with Airmail___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] find std lib doc
You could also fallback to http://swiftdoc.org. ;) -- Adrian Zubarev Sent with Airmail Am 12. Oktober 2016 um 17:01:48, Jon Shier via swift-users (swift-users@swift.org) schrieb: I’m guessing you only came to Apple’s developer environment with Swift? (If not I apologize.) The searchability and discoverability of anything on Apple’s dev site is rather low. You learn to live with it and use Google whenever you need to find something. (Which turns up the standard library docs as the first result if you search for “swift standard library documentation”). Jon On Oct 12, 2016, at 7:58 AM, J.E. Schotsman via swift-userswrote: On 12 Oct 2016, at 13:31, Adrian Zubarev wrote: It’s not hidden. https://developer.apple.com/ Develop API Reference Swift Standard Library Profit https://developer.apple.com/reference/swift I see. I still find it strange that it cannot be found on developer.apple.com with the search function. The swift.org version used to have a nice display of the hierarchical arrangement of protocols. Is that still available anywhere? Jan E. ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] ideas to remove NSCoding as requirement in UIView subclasses
This is a wrong place to ask. This topic is part of the iOS SDK from Apple not part of Swift itself or libraries like Foundation. -- Adrian Zubarev Sent with Airmail Am 8. Oktober 2016 um 18:32:50, Lou Zell via swift-users (swift-users@swift.org(mailto:swift-users@swift.org)) schrieb: > > Oh wow, I stumbled on this immediately after posting: For anyone else that > fills their NSCoding initializers with assert(false), switch them to > fatalError("message") > > On Sat, Oct 8, 2016 at 9:22 AM, Lou Zell >wrote: > > Hi all, > > > > For better or worse I still hand code most of my views. I am getting > > frustrated by the constant compiler error that I haven't updated "required > > init(coder:)", which is something that will never be executed in my case. > > > > Is there some hacky mechanism that I could use to create a subtype that > > doesn't conform to all protocols of the parent? Seems like recipe for > > disaster so I suspect it's not built into swift directly. > > > > Is there a creative way to use UIViews, but with the dependency on NSCoding > > removed? I am open to total hacks. > > > > Thanks! > > Lou > > > > ___ > 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] [swift-evolution] [Question] Types of functions
Maybe :D No actually I had to test an iOS app feature depending on that date but forget to reset the system date and time. -- Adrian Zubarev Sent with Airmail Am 6. Oktober 2016 um 20:38:53, Vladimir.S (sva...@gmail.com) schrieb: (Adrian, are you from the future? ;-) ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] [swift-evolution] [Question] Types of functions
We should move this thread to swift-users. Here is something that I just tried: func foo(_: Int, _: Int) {} func boo(_: (Int, Int)) {} type(of: foo) == type(of: boo) //=> true ; (((Int, Int)) -> ()).Type let tuple = (0, 42) foo(tuple) // Tuple splat was removed => Error boo(tuple) // Expected => Okay -- Adrian Zubarev Sent with Airmail Am 5. Oktober 2016 um 17:02:43, Anton Zhilin via swift-evolution (swift-evolut...@swift.org) schrieb: print(type(of: [Int].append)) //=> (inout Array) -> (Int) -> () print(type(of: print)) //=> ((Array, String, String)) -> () ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
[swift-users] RawRepresentable bug or intended?
struct B : RawRepresentable { let rawValue: Int // init?(rawValue: Int) { // // self.rawValue = rawValue // } static let c: B = B(rawValue: 0) static let d: B = B(rawValue: 1) } It seems to me that the memberwise initializer init(rawValue: Int) ignores the failable initializer init?(rawValue: Int) from RawRepresentable and is even able to satisfy RawRepresentable in that case. -- Adrian Zubarev Sent with Airmail ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
[swift-users] Problem with COW optimization
Dear Swift community, currently I’m building a value type XML library which is baked behind the scene with a reference type to manage graph traversing between nodes. I also like to COW optimize the xml graph, but I run into one single problem atm. Image this xml tree: It’s just a root element with one single child. As for value types it should be totally fine to do something like this: // The given xml tree var root = XML.Element(name: "root") let item = XML.Element(name: "item") root.add(item) // The problematic behavior root.add(root) If this would be a simple value type without any references behind the scenes you could imagine that the result of the last code line will look like this: Basically we copied the whole tree and added it as the second child into the original root element. As for COW optimization this is a problem, just because the passed root is a copy of a struct that contains the exact same reference as the original root element. isKnownUniquelyReferenced() will result in false inside the add method. Is there any chance I could force my program to decrease the reference counter of that last item after I’m sure I don’t need it?! A few more details: inside the add method I’m always cloning the passed reference just because graphs aren’t that trivial and otherwise I could possibly end up with a cycle graph, which would be really bad. After that job I’m sure that I don’t need the passed reference anymore and I need a way to escape from it. I’d appreciate any suggestions and help. :) -- Adrian Zubarev Sent with Airmail ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
[swift-users] open/public protocol with not overridable default implementation in the future?
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? -- Adrian Zubarev Sent with Airmail ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] [swift-evolution] Tuple
CC to the right place. -- Adrian Zubarev Sent with Airmail Am 20. Juli 2016 um 10:08:13, Fabian Ehrentraud via swift-evolution (swift-evolut...@swift.org) schrieb: Hi, I have a problem with tuple parameter types in a closure. Is this a language restriction or a bug in the Swift compiler? I used the Swift shipped with Xcode beta 3, also tried in Swift 2.2. let d: [Int: String] = [1:"1", 0:"0"] let e = d.sorted(isOrderedBefore: { e1, e2 in e1.0 < e2.0 }) // works let f = d.sorted(isOrderedBefore: { (k1, v1), (k2, v2) in k1 < k2 }) // does not compile Best, Fabian ___ swift-evolution mailing list swift-evolut...@swift.org https://lists.swift.org/mailman/listinfo/swift-evolution ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] When does `Data.init?(capacity:)` fail?
I’ve got an answer on Twitter for that behavior: https://twitter.com/phausler/status/743927492096851969 I’ve anyone like me needs Data to have a specific capacity and still be non-optional, here is how I build a workaround (Data and Data.Deallocator aren’t fully implemented yet, thats why I’m using a custom deallocator rather then .free): let capacity = 42 // or get the value somehow let dataBufferPointer = UnsafeMutablePointer(allocatingCapacity: capacity) dataBufferPointer.initialize(with: 0, count: capacity) // do some work and mutation to the data here let deallocator = Data.Deallocator.custom { (buffer, _) in free(buffer) } // this initializer says you should not mutate that data after constructing it let data = Data(bytesNoCopy: dataBufferPointer, count: capacity, deallocator: deallocator) -- Adrian Zubarev Sent with Airmail Am 19. Juni 2016 um 19:27:21, Saagar Jha (saagarjh...@gmail.com) schrieb: Not quite: Swift’s policy on memory allocation failure is that fixed-size object allocation is considered to be a runtime failure if it cannot be handled. OTOH, APIs that can take a variable and arbitrarily large amount to allocate should be failable. NSData falls into the later category. Source On Sun, Jun 19, 2016 at 10:00 AM Karl <razie...@gmail.com> wrote: As I understand it, that’s not an error in the ‘try’ sense of the word. If that failure happens, it’s a catastrophic issue which should bring down the application. So the initialiser shouldn’t be failable; you’re right. File a bug at bugs.swift.org. Karl On 18 Jun 2016, at 06:06, Saagar Jha via swift-users <swift-users@swift.org> wrote: This might be relavant. Basically, Data’s init will fail if memory can’t be allocated for it. On Fri, Jun 17, 2016 at 11:38 AM Adrian Zubarev via swift-users <swift-users@swift.org> wrote: Hello there, I’m trying to optimize my code and reduce copying from different buffers into a new one. I thought I just create a Data value with enough capacity and write directly into it. My problem is that Data.init?(capacity:) can fail, but why and when? Can someone explain this behavior to me? I’m sending data via TCP sockets and when recn function write directly into a Data struct. -- Adrian Zubarev Sent with Airmail ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users -- -Saagar Jha ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users -- -Saagar Jha ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Coding style for internal/private variables
A little bit off-topic: Is there any way to create autocompletion shortcuts in Xcode that will show only private, internal or both values of an instance? class Foo { private var integer: Int = 0 internal var string: String = "foo" internal func boo() {} } let instance = Foo() instance.@p |[V] Int integer | || // where @p is an autocompletion shortcut for Xcode that will filter private vars, functions etc. // when you choose one `@p` will be replaced // or @i for internal instance.@i __ |[M] Void boo() | |[V] String string | |__| Something like this would be handy. -- Adrian Zubarev Sent with Airmail Am 1. Juni 2016 um 18:23:46, Tino Heth (2...@gmx.de) schrieb: I never liked the underscores (so for me, they have been the best choice to mark stuff I should not know of in Cocoa ;-). For several years, I prefixed instance variables with "m", but stopped doing so after a talk about bad habits in writing Java code: It is like Hungarian notation, which also puts redundant information into names — and if even Java-folks think it's anachronistic… ;-) Objective-C lacked some features that Swift has, so workarounds had been created; but those shouldn't be carried over (by the way: It's similar with file names and those extensions, and a modern file system for OS X is years overdue ;-) ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] UnsafeMutablePointer vs. UnsafeMutablePointer
I’ve got one more question that bothers me. Lets say I’ve got a class that might look something like this: class Reference { var pointer: UnsafeMutablePointer init(integer: Int) { self.pointer = UnsafeMutablePointer.alloc(1) self.pointer.initialize(integer) } deinit { self.pointer.destroy(1) self.pointer.dealloc(1) } } Let talk about ARC here. If I use optionals here and release manually the reference deinit will be called and we’re happy here: var reference: Reference? = Reference(integer: 123456789) reference = nil If I don’t use optionals because I want my value to exist while the application is running, deinit will never be called but my application terminates just fine (SIGKILL?): let reference = Reference(integer: 123456789) Doesn’t this create a memory leak? How do I solve this problem, especially if don’t know whats inside the Reference type (assume I’m a different developer who only has access to the framework but not its implementation)? -- Adrian Zubarev Sent with Airmail Am 23. Mai 2016 um 18:31:43, Jordan Rose (jordan_r...@apple.com) schrieb: On May 21, 2016, at 01:48, Adrian Zubarev via swift-users <swift-users@swift.org> wrote: I played around with UnsafeMutablePointer and realized one behavior: let pString = UnsafeMutablePointer.alloc(1) pString.initialize("test") pString.predecessor().memory // will crash ax expected pString.predecessor() == pString.advancedBy(-1) // true pString.destroy() pString.dealloc(1) where let iInt = UnsafeMutablePointer.alloc(1) iInt.initialize("test") iInt.predecessor().memory // will not crash iInt.predecessor() == iInt.advancedBy(-1) // true iInt.predecessor().memory = 42 // did I just modified some memory I don't own? iInt.destroy() iInt.dealloc(1) Is this intended? This is really the case where its unsafe. Dmitri’s answers are all better for this specific discussion, but in general, “unsafe” in Swift means “if you don’t follow the rules, this may crash, may silently corrupt memory or do other bad things, may cause other code to be optimized out or miscompiled, may be harmless”. In this particular case, it’d be hard to check for the validity of the pointer while also being fast and binary-compatible with C. Jordan ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
[swift-users] Coding style for internal/private variables
I’d like to talk about your personal coding styles in swift for its access control. Remember these variable names like __magic or _spell or even garbage_? Sure swift solves the synthesize problem but there might be old habits that let us write such code. Here are some examples: internal _name internal i_name private __name private p_name // not sure where `garbage_` would fit I’d love to see your responses and opinions what and why the style you choose suits you. -- Adrian Zubarev Sent with Airmail ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Unsafe(Mutable)Pointer (suc)predecessor and advancedBy functions
It's also not clear sometimes exactly what "out of bounds" means - for example, you might have a big chunk of memory representing an array, and then you take a pointer to only part of that memory, representing a slice of the array. In this case you can write "out of bounds" of the slice, but the pointer type doesn't know that (because you are still within the range of the chunk of memory that you got from `UnsafeMutablePointer.memory()`). True story. :D Thank you for clarifying that to me, its a good example. Also the new pointer that I’ll get here won’t be a slice of an array just because `Memory` isn’t a slice. I’ll have to cast the pointer first, but I got the point here. ;) One more thing: - How does ARC work here when I create a new pointer to one of my allocated objects? - Do I have 2 strong references to my main piece of memory? -- Adrian Zubarev Sent with Airmail Am 26. Mai 2016 bei 20:07:36, Austin Zheng (austinzh...@gmail.com) schrieb:___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users
Re: [swift-users] Unsafe(Mutable)Pointer (suc)predecessor and advancedBy functions
So theoretically I could build a wrapper type for Unsafe(Mutable)Pointer which will be safe to use and never exceed the allocated range! public func successor() -> UnsafeMutablePointer? { // return `nil` if out of range } So why don’t we have safe pointers today? Any technical reasons or do I miss something here?! -- Adrian Zubarev Sent with Airmail Am 26. Mai 2016 bei 19:14:41, Andrew Trick (atr...@apple.com) schrieb: On May 26, 2016, at 9:59 AM, Adrian Zubarev via swift-users <swift-users@swift.org> wrote: I’ve got one more questions about Unsafe(Mutable)Pointer. I know that I’m able to access memory that might not belong to me. My question is: Can I trust these functions that they will return a pointer to some memory when I allocate more than one object AND when I’m moving only inside that range? Yes. public func successor() -> UnsafeMutablePointer public func predecessor() -> UnsafeMutablePointer public func advancedBy(n: Int) -> UnsafeMutablePointer UnsafeMutablePointer.alloc(4) when I advance only in range of [0,1,2,3] am I safe or could I get a pointer to memory that does not belong to me? UnsafeMutablePointer.alloc(N) creates a single object in memory that holds N consecutive T values. Each value resides at index*strideof(T.self) bytes beyond the allocated pointer where index is valid in the range 0..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] UnsafeMutablePointer vs. UnsafeMutablePointer
So basically if I do something like this I should be on the safe side: public class Characters { private let reference: UnsafeMutablePointer var characters: [Character] { var characters = [Character]() for index in 0...alloc(self.count) self.reference.initializeFrom(characters) } deinit { self.reference.destroy(self.count) self.reference.dealloc(self.count) } } Or do I have to fix something? Here I don’t walk out of the boundary I allocate. Does the UnsafeMutablePointer reserves me a safe portion of memory (by safe I mean which isn’t used by anyone at the time I will start using it)? Sure another pointer could be created and hack into my memory but that wasn’t the question. :) Thanks. -- Adrian Zubarev Sent with Airmail Am 21. Mai 2016 bei 11:04:10, Dmitri Gribenko (griboz...@gmail.com) schrieb: Hi Adrian, On Sat, May 21, 2016 at 1:48 AM, Adrian Zubarev via swift-users <swift-users@swift.org> wrote: > I played around with UnsafeMutablePointer and realized one behavior: > > let pString = UnsafeMutablePointer.alloc(1) > pString.initialize("test") > pString.predecessor().memory // will crash ax expected > pString.predecessor() == pString.advancedBy(-1) // true > pString.destroy() > pString.dealloc(1) > > where > > let iInt = UnsafeMutablePointer.alloc(1) > iInt.initialize("test") > iInt.predecessor().memory // will not crash > iInt.predecessor() == iInt.advancedBy(-1) // true > iInt.predecessor().memory = 42 // did I just modified some memory I don't > own? Yes, you did. In the String case the crash is not guaranteed (it is a segmentation fault, not a controlled trap). Someone else's valid String can happen to be located immediately before your memory chunk, and then the code would "just work", loading that other string. Dereferencing (reading or writing into) an out-of-bounds pointer is undefined behavior in Swift. Dmitri -- main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if (j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/ ___ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users