pnre / exswift Goto Github PK
View Code? Open in Web Editor NEWA set of Swift extensions for standard types and classes.
License: Other
A set of Swift extensions for standard types and classes.
License: Other
Hi.
I was using your library and run into one issue when converting an array to a dictionary.
Using ExSwift for converting arrays to dictionaries converts array values to dictionary values but I need to convert array values to dictionary keys and generate values based on the keys.
Would you mind adding something similar to this to ExSwift:
func toDictionary<E, K, V>(
array: [E],
transformer: (element: E) -> (key: K, value: V)?)
-> Dictionary<K, V>
{
return array.reduce([:]) {
(var dict, e) in
if let (key, value) = transformer(element: e)
{
dict[key] = value
}
return dict
}
}
Source: http://ijoshsmith.com/2014/06/18/create-a-swift-dictionary-from-an-array/
Hi,
in the Array section of the documentation:
takeFirst (condition: (Element) -> Bool) -> Element
should be
takeFirst (condition: (Element) -> Bool) -> Element?
What do you think? :)
Thanks.
I think there is a bug in skipWhile method (and its test):
func testSkipWhile () {
var skipped = SequenceOf(sequence).skipWhile { $0 < 3 }
XCTAssertEqual(Array(skipped), [4, 5])
}
Number 3 should not be skipped so test should be:
XCTAssertEqual(Array(skipped), [3, 4, 5])
Float has some neat tricks like .abs(), .floor(), etc. why not add this to Double as well or do you expect to just use the abs(val: Double) function?
In https://github.com/pNre/ExSwift/blob/master/ExSwift/Range.swift, there are "DP2 style open range operators" that are just wrappers around ..<
. Seems like this should be taken out.
returning -1
from these methods seems like a good old hack from C-languages days. Now we have fancy optionals and it suits well here.
What do you think? Pull request is coming.
Hello, here is my problem when using your library. This is my first Swift (and iOS) application so I could have made errors in importing or whatever.
CONTEXT
importing your library into my application by drag and dropping the ExSwift folder (not the xcodeproj) into the root of my iOS application.
ACTION
Build the application. No error in my personal code.
RESULT
errors in all methods of the Array class of ExSwift : "Extension of generic type 'Array' from a different module cannot provide public declarations"
EXPECTED
The application should build.
Thanks in advance for your help. Great library by the way !
This isn't an issue, per say – I'm new to iOS development but have experience with LoDash and Javascript. How do I import this into my app and use it?
func explode (separator: Character) -> [String] {
- return split(self, { (element: Character) -> Bool in
+ return split(self, isSeparator: { (element: Character) -> Bool in
return element == separator
})
}
Is it possible to include the ExSwift *.swift files in multiple targets without causing compilation conflicts?
I'm having an issue now where I can only either use these extensions in my base target OR in my test target but not both.
Any plans to support the latest swift release?
Sometimes I want to, given an array of an optional type, return an array of the corresponding non-optional type, where all nil values have been filtered out. Here's my best attempt, but it doesn't compile: https://gist.github.com/michaeleisel/32f7e80ce2186f1edc95
Any ideas?
can enhance the support for weak?
Weak Object
as if
class Weak<T: AnyObject> {
weak var value: T?
init (_ value: T) {
self.value = value
}
}
Weak Array
http://stackoverflow.com/questions/24127587/how-do-i-declare-an-array-of-weak-references-in-swift
The following code
let array1 = ["zero", "one", "two", "three"][1...3]
let array2 = ["zero", "one", "two", "three"][1..<3]
In a project which includes ExSwift results, for the first statement, in
'ClosedInterval<T>' is not convertible to 'Int'
And for the second statement:
'HalfOpenInterval<T>' is not convertible to 'Int'
In both cases the error marker points at the first dot in the subscript.
i import exswift in my project , but i found exswift class don't export array extension function,like this:
extension Array {
}
because in exswift module array is defined as internal , how to solve it.
The merge dictionary instance method is reported in the readme, but is nowhere to be seen in the code.
I've tried everything and more to include your wonderful library, as a single .framework file, in a project of mine, but all I get is a Mach-O Linjer Error: symbol(s) not found for architecture x86_64.
All my other custom libraries included in my project compile correctly...
If I import the sources into my project everything compiles correctly. But i'd like to use the library feature instead...
Really I don't know if it's my issue or an XCode bug.
Thanks for any advice!
bridgeFromObjectiveCConditional
is no longer a recognized identifier (release notes don't mention this one unfortunately), and the .by()
method has been replaced with stride( from: to: by: )
.
I was thinking, since Google doesn't turn up any authoritative Regex Swift libraries, Regex would be a good idea. I haven't heard of any way to write out a Regex pattern without it being escaped, but oh well. I was thinking of adding a prefix operator, "/", that takes a String, so you would define a Regex literal like this:
let a: Regex = /"[0-9]*"
I would also add the =~ operator, a subscript lookup on strings, and almost all of Ruby's stuff for regexes, which you can find by searching for "regexp" on this page: http://www.ruby-doc.org/core-2.2.0/String.html
One question is whether or not to use iOS's existing regular expression class, NSRegularExpression. I don't know a lot about it, but it seems to reasonable to just make extension methods for it as needed, and perhaps subclass it as we need in the future.
Thoughts?
In Xcode Beta 4 I'm attempting to use the String subscript function subscript (index: Int) -> String?
as follows: println( "hello"[0]! )
This results in compile time error: "Character' is not convertible to '(T, inout TargetStream)'".
If I remove the exclamation point and use println( "hello"[0] )
instead, I get the compile time error: "Missing argument for parameter #2 in call"
Only if I comment out the String subscript function that accepts more than one index, subscript (indexes: Int...) -> Array<String>
does the code finally compile.
Definitely struggling to work my way through swift, but it looks like something has gone wrong with method overloading.
I'm using flatMap
in a project, would that be a generally useful thing to add to ExSwift?
func flatMap<A, B>(x: A?, f: A -> B?) -> B? {
if let value = x {
return f(value)
}
return nil
}
If so I can open a PR, just wanted to check since I'm not sure this matches the style of the rest of the extensions.
/**
Returns a new NSDate object representing the date calculated by adding an amount of minutes to self date
:param: minutes number of minutes to add
:returns: the NSDate computed
*/
public func addMinutes (minute: Int) -> NSDate {
return add(minutes: minute)
}
The parameter name declared in the comments (minutes) is different form that in the method declaration which would cause XCode to raise an error.
Current syntax in Standard Library:
[T] += [T]
Proposed extension:
[T] += T
As a developer becomes familiar with Swift, they will likely find it strange that Apple would provide optional accessors on all of their data structures (which play nicely with the "if let" idiom), with the singular exception of Array.
Instead of being able to do this:
if let foo = array[3]
{
// do something with foo
}
Instead you have to do something which feels clumsy in comparison:
if array.count > 3
{
let foo = array[3]!
// do something with foo
}
Writing an optional accessor seems a very obvious thing to do, to make Array fit better with the style of the rest of the language.
So I was quite shocked to discover that your "get()" method automatically wraps an out-of-bounds index, and that this behavior was intentional. I'm just having trouble wrapping my head around it.
Who would expect out-of-bounds index wrapping to be the default behavior of a method named "get()"?
If someone needed the (somewhat uncommon) behavior of out-of-bounds index wrapping, why would they want to hide that implementation detail behind a method call, instead of doing something explicit which calls better attention to it, like "array.get(index % array.count)"?
If they insist on hiding the behavior behind a method call, why wouldn't they choose a method name which at least hints at the behavior, like maybe .wrappedGet()?
This behavior and this method name just don't belong together.
ExSwift now contains some functions that contain the Right appendix (e.g. reduceRight) meaning to do a reverse operation compared to reduce. May I suggest to avoid the Right appendix and replace it by e.g. Reverse because Right has a strong connotation to writing directions (right-to-left vs left-to-right) which is not at all what these functions are about.
I wonder if you have considered to include support classes that are not only related to data types in ExSwift. For instance code like the accepted answer at http://stackoverflow.com/questions/24581517/read-a-file-url-line-by-line-in-swift might be a good addition, starting a new _file handling_ group of classes/functions.
I am trying to use the library in my Swift project and I think is great, but with Xcode 6.1 I found an issue when I try to build the project specifically with the random
function declaration. Here's the way it should be declared to work properly:
static func random(#max: Int, min: Int = 0) -> Int {
return Int(arc4random_uniform(UInt32((max - min) + 1))) + min
}
My project won't compile onXcode 6.1. It gives me a bunch of errors on the Array.swift in the methods declarations.
(Extension of generic type 'Array' from a different module cannot provide public declarations)
Does anyone know what needs to be changed?
I'm confused about the compilation of this library ... as far as I understand there are two different compilation targets, one for OSX, one for iOS. The compiled framework for OSX is about 840 kb while the one for iOS is only about 5 kb. I think this can't be right. What is going on here?
Looks like the following things are problematic:
There may be some additional things but just a heads up
If you add Travis to this project all the push and all the PR can be tested on multiple platfork. See Build Matrix
let a = [1.2, 3.0, 4.5]
let i = a.indexOf(3) // i is nil
let a = [1.2, 3.0, 4.5]
let i = find(a, 3) // i is Optional(1)
change add to below works
public func add(seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> NSDate {
var calendar = NSCalendar.currentCalendar()
let version = floor(NSFoundationVersionNumber)
if ( version <= NSFoundationVersionNumber_iOS_7_1 || version <= NSFoundationVersionNumber10_9_2 ) {
var component = NSDateComponents()
component.second = seconds
component.minute = minutes
component.hour = hours
component.day = days + weeks * 7
component.month = months
component.year = years
return calendar.dateByAddingComponents(component, toDate: self, options: nil)!
}
var date : NSDate! = calendar.dateByAddingUnit(.CalendarUnitSecond, value: seconds, toDate: self, options: nil)
date = calendar.dateByAddingUnit(.CalendarUnitMinute, value: minutes, toDate: date, options: nil)
date = calendar.dateByAddingUnit(.CalendarUnitDay, value: days, toDate: date, options: nil)
date = calendar.dateByAddingUnit(.CalendarUnitHour, value: hours, toDate: date, options: nil)
date = calendar.dateByAddingUnit(.CalendarUnitWeekOfMonth, value: weeks, toDate: date, options: nil)
date = calendar.dateByAddingUnit(.CalendarUnitMonth, value: months, toDate: date, options: nil)
date = calendar.dateByAddingUnit(.CalendarUnitYear, value: years, toDate: date, options: nil)
return date
}
This is a suggestion for code improvement, but I’m too lazy to fork and suggest a pullRequest, sorry!
I’ve been playing with SequenceOf and GeneratorOf and created a functions that do the take
and takeWhile
without the need to create custom struct
s . You may adapt these functions for use in your Sequence.swift extensions (just specialize on self instead of the second parameter).
func takeWhile<S : SequenceType>(includeElement: S.Generator.Element -> Bool, source: S) -> SequenceOf<S.Generator.Element> {
return SequenceOf { () -> GeneratorOf<S.Generator.Element> in
var takeMore = true
var g = source.generate()
return GeneratorOf {
if takeMore {
if let e = g.next() {
takeMore = includeElement(e)
return takeMore ? e : .None
}
}
return .None
}
}
}
func take<S : SequenceType>(count: Int, source: S) -> SequenceOf<S.Generator.Element> {
return SequenceOf { () -> GeneratorOf<S.Generator.Element> in
var i = 0
var g = source.generate()
return GeneratorOf {
return (i++ < count) ? g.next() : .None
}
}
}
FWIW it appears to also be a little bit more performant...
Hi - are you interested in a contribution which adds Sequence
operations to this library?
The Swift Sequence
is lazy evaluated, and as a result the various operations (take, skip, contains, ...) can be written in such as way that they do not have to evaluate the entire sequence to return their value.
I've implemented a few operations here:
https://github.com/ColinEberhardt/ExSwift/blob/sequence-operations/ExSwift/Sequence.swift
With tests here:
Unfortunately because you cannot extend protocols, the only way I can find to add sequence operations is to extend SequenceOf
, which as far as a I can tell adapts a Sequence
returning a concrete type rather than a protocol.
Anyhow, just wanted to get your thoughts before I get too stuck in to the implementation. If I add a decent suite of Sequence methods, would you want to include them in ExSwift?
The dateByAddingUnit()
function is only supported in ios 8 and above, which is what is used in this project.
Using Xcode 6.3 beta and Cocoapods (pod 'ExSwift', :git => 'https://github.com/pNre/ExSwift.git', :branch => 'Swift-1.2') to install the Swift-1.2 branch into my somewhat large project, I am greeted with a segmentation fault: 11 error when compiling.
Not sure if this can be somehow fixed here, of should I file a bug to Apple. Thanks.
Your Array.indexOf doesn't work with array of type UInt, in which case it will always return nil.
It cant run in Xcode 6.3 ?
I have a few question about ExSwift library and swift projects in general:
Would it simply require the regex:
let pattern = "^[-+]?[0-9]*\\.?[0-9]+$"
in the String extension be expanded a little to allow 'scientific' notation?
The code for me in ExSwiftArrayTests:
for i in 1..100 {
...
}
breaks with "HalfOpenInterval does not conform to protocol SequenceType"
Would it be possible to use the built-in contains
function as the basis for the contains
method extensions? I've tried it out myself but it seems limited by the fact that the built-in contains
function expects values to be Equatable
while the generic Array, etc. can make no such guarantees.
Perhaps you have more insight?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.