Rectangle 27 49

1. Merge two arrays into a new array with Swift standard library's +(_...

With Swift 3, according to your needs and tastes, you may choose one of the five following ways to concatenate/merge two arrays.

Swift standard library defines a +(_:_:) generic operator. +(_:_:) has the following declaration:

func +<RRC1 : RangeReplaceableCollection, RRC2 : RangeReplaceableCollection where RRC1.Iterator.Element == RRC2.Iterator.Element>(lhs: RRC1, rhs: RRC2) -> RRC1

Creates a new collection by concatenating the elements of two collections.

append(contentsOf:)
public mutating func append<S>(contentsOf newElements: S) where S : Sequence, S.Iterator.Element == Element)

Adds the elements of a sequence or collection to the end of this collection.

var array1 = [1, 2, 3]
let array2 = [4, 5, 6]

array1.append(contentsOf: array2)
print(array1) // prints [1, 2, 3, 4, 5, 6]

Swift provides a flatMap(_:) method for all types that conform to Sequence protocol (including Array). flatMap(_:) has the following declaration:

func flatMap<SegmentOfResult : Sequence>(_ transform: (Self.Iterator.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Iterator.Element]

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

let flattenArray = [array1, array2].flatMap({ (element: [Int]) -> [Int] in
    return element
})
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]

Swift provides a joined() method for all types that conform to Sequence protocol (including Array). joined() has the following declaration:

func joined() -> FlattenSequence<Self>

Returns the elements of this sequence of sequences, concatenated.

Besides, Swift Array has a init(_:) initializer. init(_:) has the following declaration:

init<S : Sequence where S.Iterator.Element == Element>(_ s: S)

Creates an array containing the elements of a sequence.

Therefore, the following Playground code shows how to merge two arrays of type [Int] into a new array using joined() method and init(_:) initializer:

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

let flattenCollection = [array1, array2].joined() // type: FlattenBidirectionalCollection<[Array<Int>]>
let flattenArray = Array(flattenCollection)
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]
Array
reduce(_:_:)
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

Returns the result of calling the given combining closure with each element of this sequence and an accumulating value.

The following Playground code shows how to merge two arrays of type [Int] into a new array using reduce(_:_:) method:

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

let flattenArray = [array1, array2].reduce([], { (result: [Int], element: [Int]) -> [Int] in
    return result + element
})
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]

ios - How do I concatenate or merge arrays in Swift? - Stack Overflow

ios arrays merge swift append
Rectangle 27 142

For extending typed arrays with classes, the below works for me (Swift 2.2). For example, sorting a typed array:

class HighScoreEntry {
    let score:Int
}

extension Array where Element:HighScoreEntry {
    func sort() -> [HighScoreEntry] {
      return sort { $0.score < $1.score }
    }
}

Trying to do this with a struct or typealias will give an error:

Type 'Element' constrained to a non-protocol type 'HighScoreEntry'

To extend typed arrays with non-classes use the following approach:

typealias HighScoreEntry = (Int)

extension SequenceType where Generator.Element == HighScoreEntry {
    func sort() -> [HighScoreEntry] {
      return sort { $0 < $1 }
    }
}
extension Sequence where Iterator.Element == HighScoreEntry 
{
    // ...
}

This should be the accepted answer!

It no longer works in Swift 3

Why you didn't use Iterator.Element in return type [Iterator.Element]?

How can I extend typed Arrays in Swift? - Stack Overflow

arrays swift
Rectangle 27 315

Counting characters in Swift

For Swift 2.0 and 3.0, use test1.characters.count. But, there are a few things you should know. So, read on.

Before Swift 2.0, count was a global function. As of Swift 2.0, it can be called as a member function.

test1.characters.count

It will return the actual number of Unicode characters in a String, so it's the most correct alternative in the sense that, if you'd print the string and count characters by hand, you'd get the same result.

However, because of the way Strings are implemented in Swift, characters don't always take up the same amount of memory, so be aware that this behaves quite differently than the usual character count methods in other languages.

test1.utf16.count

But, as noted below, the returned value is not guaranteed to be the same as that of calling count on characters.

Extended grapheme clusters can be composed of one or more Unicode scalars. This means that different charactersand different representations of the same charactercan require different amounts of memory to store. Because of this, characters in Swift do not each take up the same amount of memory within a strings representation. As a result, the number of characters in a string cannot be calculated without iterating through the string to determine its extended grapheme cluster boundaries. If you are working with particularly long string values, be aware that the characters property must iterate over the Unicode scalars in the entire string in order to determine the characters for that string.

The count of the characters returned by the characters property is not always the same as the length property of an NSString that contains the same characters. The length of an NSString is based on the number of 16-bit code units within the strings UTF-16 representation and not the number of Unicode extended grapheme clusters within the string.

An example that perfectly illustrates the situation described above is that of checking the length of a string containing a single emoji character, as pointed out by n00neimp0rtant in the comments.

var emoji = ""
emoji.characters.count             //returns 1
emoji.utf16.count                  //returns 2

I appreciate your detailed and cautionary answer, but I have to admit it's left me uneasy. You gave me 3 ways to get the length of a string, all with the disclaimer that the answers they give might not be what you expect. Is there truly no reliable way built into Swift to get an accurate, reliable length value of a string?

@n00neimp0rtant. Sorry if I did not make it clear. The first solution (countElements())gets the exact number of characters in the String. It might be different from what you'd get from calling [str length] in Objective-C, because the length method assumes all characters in the string are composed of 16-bit code units, while countElements() gets the actual number of Unicode characters. However, most of the time all of the above alternatives will return the same results, specially if you're are working with English language common characters.

I see what you mean now. I just tried getting the length of a string containing a single Emoji character; Objective-C gave me a value of 4, and Swift gave me a value of 1. So it actually seems more accurate (and therefore, ironically "not what I'd expect" =P). Thanks for the clarification!

swift - Get the length of a String - Stack Overflow

swift string
Rectangle 27 334

componentArray = Array(dict.keys) // for Dictionary

componentArray = dict.allKeys // for NSDictionary

Interestingly, in a for loop - for name in dict.allKeys - 'name' becomes a string and can be printed and otherwise processed.

dict does not have a keys method. It's an instance of NSDictionary, not a Dictionary.

ios - Array from dictionary keys in swift - Stack Overflow

ios arrays xcode dictionary swift
Rectangle 27 320

componentArray = Array(dict.keys) // for Dictionary

componentArray = dict.allKeys // for NSDictionary

Interestingly, in a for loop - for name in dict.allKeys - 'name' becomes a string and can be printed and otherwise processed.

dict does not have a keys method. It's an instance of NSDictionary, not a Dictionary.

ios - Array from dictionary keys in swift - Stack Overflow

ios arrays xcode dictionary swift
Rectangle 27 527

Swift 1.2 - 2.x (Introduced with Xcode 6.3)

The other solution is correct in that it will get you a reference to the application's delegate, but this will not allow you to access any methods or variables added by your subclass of UIApplication, like your managed object context. To resolve this, simply downcast to "AppDelegate" or what ever your UIApplication subclass happens to be called. Like so:

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let aVariable = appDelegate.someVariable

In case anyone is still having problems, targeting OS X requires you to import Cocoa for this to work for NSApplication.sharedApplication(). I'd guess that iOS would need the equivalent.

This is the more useful of the two answers.

@zacjordaan Using that method, you will get autocompletion for the property, but it won't actually work. That way will create a new instance of the AppDelegate class every time you use it. You're better off using the delegate accessible through the sharedApplication singleton. And as far as your second question goes, yes you probably want to use a constant. Even though, you may be changing the AppDelegate's properties, you probably won't be reassigning the pointer to anything else, in which case, there's no need for a variable. This is completely up to you though. Do what suits your needs.

Excellent advice! I had mistakenly thought that AppDelegate() was singleton but after thinking about what you've said I've realized that if it was then there wouldn't be a sharedApplication pattern for us to use in this way. Of course I don't want to spawn unnecessary instances if I don't have to, so your constant declaration will suit perfectly; Thank you.

"cleaning" the project and rebuilding resolved this for me. Thanks for the help.

How do I get a reference to the app delegate in Swift? - Stack Overflo...

swift
Rectangle 27 825

In Swift 2.2 (Xcode 7.3) and later (including Swift 3 / Xcode 8 and Sw...

Swift itself doesn't use selectors several design patterns that in Objective-C make use of selectors work differently in Swift. (For example, use optional chaining on protocol types or is/as tests instead of respondsToSelector:, and use closures wherever you can instead of performSelector: for better type/memory safety.)

But there are still a number of important ObjC-based APIs that use selectors, including timers and the target/action pattern. Swift provides the Selector type for working with these. (Swift automatically uses this in place of ObjC's SEL type.)

You can construct a Selector from a Swift function type using the #selector expression.

let timer = Timer(timeInterval: 1, target: object,
                  selector: #selector(MyClass.test),
                  userInfo: nil, repeats: false)
button.addTarget(object, action: #selector(MyClass.buttonTapped),
                 for: .touchUpInside)
view.perform(#selector(UIView.insertSubview(_:aboveSubview:)),
             with: button, with: otherButton)

The great thing about this approach? A function reference is checked by the Swift compiler, so you can use the #selector expression only with class/method pairs that actually exist and are eligible for use as selectors (see "Selector availability" below). You're also free to make your function reference only as specific as you need, as per the Swift 2.2+ rules for function-type naming.

(This is actually an improvement over ObjC's @selector() directive, because the compiler's -Wundeclared-selector check verifies only that the named selector exists. The Swift function reference you pass to #selector checks existence, membership in a class, and type signature.)

There are a couple of extra caveats for the function references you pass to the #selector expression:

  • Multiple functions with the same base name can be differentiated by their parameter labels using the aforementioned syntax for function references (e.g. insertSubview(_:at:) vs insertSubview(_:aboveSubview:)). But if a function has no parameters, the only way to disambiguate it is to use an as cast with the function's type signature (e.g. foo as () -> () vs foo(_:)).
var foo: Int
#selector(getter: MyClass.foo)
#selector(setter: MyClass.foo)

Cases where #selector doesn't work, and naming: Sometimes you don't have a function reference to make a selector with (for example, with methods dynamically registered in the ObjC runtime). In that case, you can construct a Selector from a string: e.g. Selector("dynamicMethod:") though you lose the compiler's validity checking. When you do that, you need to follow ObjC naming rules, including colons (:) for each parameter.

Selector availability: The method referenced by the selector must be exposed to the ObjC runtime. In Swift 4, every method exposed to ObjC must have its declaration prefaced with the @objc attribute. (In previous versions you got that attribute for free in some cases, but now you have to explicitly declare it.)

Remember that private symbols aren't exposed to the runtime, too your method needs to have at least internal visibility.

Key paths: These are related to but not quite the same as selectors. There's a special syntax for these in Swift 3, too: e.g. chris.valueForKeyPath(#keyPath(Person.friends.firstName)). See SE-0062 for details. And even more KeyPath stuff in Swift 4, so make sure you're using the right KeyPath-based API instead of selectors if appropriate.

Selector
StringLiteralConvertible
#selector

Putting a string with the function name worked, NSSelectorFromString() works also.

I'd like to mention that while "Interacting with Objective-C APIs" is on the website, it is NOT in 'The Swift Programming Language' book.

This should probably mention that the selector needs a ":" at the end if it takes an argument. (E.g. test() -> "test" & test(this:String) -> "test:")

It should also be pointed out that the Cocoa frameworks expect an Objective-C style method name. If your method takes an argument you will need a ':' if it takes 2 arguments, size:andShape:, if the first argument is named you may need a With, i.e. initWithData: for func init(Data data: NSData)

Is there anyway to add validation around passing the "selector" as a string? IE compiler warn us when we misspell, etc.

@selector() in Swift? - Stack Overflow

swift selector nstimer
Rectangle 27 814

In Swift 2.2 (Xcode 7.3) and later (including Swift 3 / Xcode 8 and Sw...

Swift itself doesn't use selectors several design patterns that in Objective-C make use of selectors work differently in Swift. (For example, use optional chaining on protocol types or is/as tests instead of respondsToSelector:, and use closures wherever you can instead of performSelector: for better type/memory safety.)

But there are still a number of important ObjC-based APIs that use selectors, including timers and the target/action pattern. Swift provides the Selector type for working with these. (Swift automatically uses this in place of ObjC's SEL type.)

You can construct a Selector from a Swift function type using the #selector expression.

let timer = Timer(timeInterval: 1, target: object,
                  selector: #selector(MyClass.test),
                  userInfo: nil, repeats: false)
button.addTarget(object, action: #selector(MyClass.buttonTapped),
                 for: .touchUpInside)
view.perform(#selector(UIView.insertSubview(_:aboveSubview:)),
             with: button, with: otherButton)

The great thing about this approach? A function reference is checked by the Swift compiler, so you can use the #selector expression only with class/method pairs that actually exist and are eligible for use as selectors (see "Selector availability" below). You're also free to make your function reference only as specific as you need, as per the Swift 2.2+ rules for function-type naming.

(This is actually an improvement over ObjC's @selector() directive, because the compiler's -Wundeclared-selector check verifies only that the named selector exists. The Swift function reference you pass to #selector checks existence, membership in a class, and type signature.)

There are a couple of extra caveats for the function references you pass to the #selector expression:

  • Multiple functions with the same base name can be differentiated by their parameter labels using the aforementioned syntax for function references (e.g. insertSubview(_:at:) vs insertSubview(_:aboveSubview:)). But if a function has no parameters, the only way to disambiguate it is to use an as cast with the function's type signature (e.g. foo as () -> () vs foo(_:)).
var foo: Int
#selector(getter: MyClass.foo)
#selector(setter: MyClass.foo)

Cases where #selector doesn't work, and naming: Sometimes you don't have a function reference to make a selector with (for example, with methods dynamically registered in the ObjC runtime). In that case, you can construct a Selector from a string: e.g. Selector("dynamicMethod:") though you lose the compiler's validity checking. When you do that, you need to follow ObjC naming rules, including colons (:) for each parameter.

Selector availability: The method referenced by the selector must be exposed to the ObjC runtime. In Swift 4, every method exposed to ObjC must have its declaration prefaced with the @objc attribute. (In previous versions you got that attribute for free in some cases, but now you have to explicitly declare it.)

Remember that private symbols aren't exposed to the runtime, too your method needs to have at least internal visibility.

Key paths: These are related to but not quite the same as selectors. There's a special syntax for these in Swift 3, too: e.g. chris.valueForKeyPath(#keyPath(Person.friends.firstName)). See SE-0062 for details. And even more KeyPath stuff in Swift 4, so make sure you're using the right KeyPath-based API instead of selectors if appropriate.

Selector
StringLiteralConvertible
#selector

Putting a string with the function name worked, NSSelectorFromString() works also.

I'd like to mention that while "Interacting with Objective-C APIs" is on the website, it is NOT in 'The Swift Programming Language' book.

This should probably mention that the selector needs a ":" at the end if it takes an argument. (E.g. test() -> "test" & test(this:String) -> "test:")

It should also be pointed out that the Cocoa frameworks expect an Objective-C style method name. If your method takes an argument you will need a ':' if it takes 2 arguments, size:andShape:, if the first argument is named you may need a With, i.e. initWithData: for func init(Data data: NSData)

Is there anyway to add validation around passing the "selector" as a string? IE compiler warn us when we misspell, etc.

@selector() in Swift? - Stack Overflow

swift selector nstimer
Rectangle 27 810

In Swift 2.2 (Xcode 7.3) and later (including Swift 3 / Xcode 8 and Sw...

Swift itself doesn't use selectors several design patterns that in Objective-C make use of selectors work differently in Swift. (For example, use optional chaining on protocol types or is/as tests instead of respondsToSelector:, and use closures wherever you can instead of performSelector: for better type/memory safety.)

But there are still a number of important ObjC-based APIs that use selectors, including timers and the target/action pattern. Swift provides the Selector type for working with these. (Swift automatically uses this in place of ObjC's SEL type.)

You can construct a Selector from a Swift function type using the #selector expression.

let timer = Timer(timeInterval: 1, target: object,
                  selector: #selector(MyClass.test),
                  userInfo: nil, repeats: false)
button.addTarget(object, action: #selector(MyClass.buttonTapped),
                 for: .touchUpInside)
view.perform(#selector(UIView.insertSubview(_:aboveSubview:)),
             with: button, with: otherButton)

The great thing about this approach? A function reference is checked by the Swift compiler, so you can use the #selector expression only with class/method pairs that actually exist and are eligible for use as selectors (see "Selector availability" below). You're also free to make your function reference only as specific as you need, as per the Swift 2.2+ rules for function-type naming.

(This is actually an improvement over ObjC's @selector() directive, because the compiler's -Wundeclared-selector check verifies only that the named selector exists. The Swift function reference you pass to #selector checks existence, membership in a class, and type signature.)

There are a couple of extra caveats for the function references you pass to the #selector expression:

  • Multiple functions with the same base name can be differentiated by their parameter labels using the aforementioned syntax for function references (e.g. insertSubview(_:at:) vs insertSubview(_:aboveSubview:)). But if a function has no parameters, the only way to disambiguate it is to use an as cast with the function's type signature (e.g. foo as () -> () vs foo(_:)).
var foo: Int
#selector(getter: MyClass.foo)
#selector(setter: MyClass.foo)

Cases where #selector doesn't work, and naming: Sometimes you don't have a function reference to make a selector with (for example, with methods dynamically registered in the ObjC runtime). In that case, you can construct a Selector from a string: e.g. Selector("dynamicMethod:") though you lose the compiler's validity checking. When you do that, you need to follow ObjC naming rules, including colons (:) for each parameter.

Selector availability: The method referenced by the selector must be exposed to the ObjC runtime. In Swift 4, every method exposed to ObjC must have its declaration prefaced with the @objc attribute. (In previous versions you got that attribute for free in some cases, but now you have to explicitly declare it.)

Remember that private symbols aren't exposed to the runtime, too your method needs to have at least internal visibility.

Key paths: These are related to but not quite the same as selectors. There's a special syntax for these in Swift 3, too: e.g. chris.valueForKeyPath(#keyPath(Person.friends.firstName)). See SE-0062 for details. And even more KeyPath stuff in Swift 4, so make sure you're using the right KeyPath-based API instead of selectors if appropriate.

Selector
StringLiteralConvertible
#selector

Putting a string with the function name worked, NSSelectorFromString() works also.

I'd like to mention that while "Interacting with Objective-C APIs" is on the website, it is NOT in 'The Swift Programming Language' book.

This should probably mention that the selector needs a ":" at the end if it takes an argument. (E.g. test() -> "test" & test(this:String) -> "test:")

It should also be pointed out that the Cocoa frameworks expect an Objective-C style method name. If your method takes an argument you will need a ':' if it takes 2 arguments, size:andShape:, if the first argument is named you may need a With, i.e. initWithData: for func init(Data data: NSData)

Is there anyway to add validation around passing the "selector" as a string? IE compiler warn us when we misspell, etc.

@selector() in Swift? - Stack Overflow

swift selector nstimer
Rectangle 27 429

shuffle as a function

This answer details how to add a Fisher-Yates (fast an uniform) shuffle in the various versions of Swift. The Swift 3 & 4 versions are the most permissive, but they all at least work for arrays. The naming and behavior for each Swift version matches the mutating and nonmutating sorting methods for that version.

extension MutableCollection {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            let i = index(firstUnshuffled, offsetBy: d)
            swapAt(firstUnshuffled, i)
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}

let x = [1, 2, 3].shuffled()
// x == [2, 3, 1]

let fiveStrings = stride(from: 0, through: 100, by: 5).map(String.init).shuffled()
// fiveStrings == ["20", "45", "70", "30", ...]

var numbers = [1, 2, 3, 4]
numbers.shuffle()
// numbers == [3, 2, 1, 4]

These extensions add a shuffle() method to any mutable collection and a shuffled() method to any sequence:

extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Iterator.Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}

let x = [1, 2, 3].shuffled()
// x == [2, 3, 1]

let fiveStrings = stride(from: 0, through: 100, by: 5).map(String.init).shuffled()
// fiveStrings == ["20", "45", "70", "30", ...]

var numbers = [1, 2, 3, 4]
numbers.shuffle()
// numbers == [3, 2, 1, 4]
extension MutableCollectionType where Index == Int {
    /// Shuffle the elements of `self` in-place.
    mutating func shuffleInPlace() {
        // empty and single-element collections don't shuffle
        if count < 2 { return }

        for i in startIndex ..< endIndex - 1 {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            guard i != j else { continue }
            swap(&self[i], &self[j])
        }
    }
}

extension CollectionType {
    /// Return a copy of `self` with its elements shuffled.
    func shuffle() -> [Generator.Element] {
        var list = Array(self)
        list.shuffleInPlace()
        return list
    }
}

[1, 2, 3].shuffle()
// [2, 3, 1]

let fiveStrings = 0.stride(through: 100, by: 5).map(String.init).shuffle()
// ["20", "45", "70", "30", ...]

var numbers = [1, 2, 3, 4]
numbers.shuffleInPlace()
// [3, 2, 1, 4]

This is the simplest version: add this function anywhere at the top level and you'll be able to shuffle arrays and slices:

func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C {
    let c = count(list)
    if c < 2 { return list }
    for i in 0..<(c - 1) {
        let j = Int(arc4random_uniform(UInt32(c - i))) + i
        swap(&list[i], &list[j])
    }
    return list
}
shuffle([1, 2, 3, 4, 5, 6, 7, 8])        // e.g., [6, 1, 8, 3, 2, 4, 7, 5]
shuffle(["hello", "goodbye", "ciao"])    // e.g., ["ciao", "goodbye", "hello"]

This extension will let you shuffle a mutable Array instance in place:

extension Array {
    mutating func shuffle() {
        if count < 2 { return }
        for i in 0..<(count - 1) {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            swap(&self[i], &self[j])
        }
    }
}
var numbers = [1, 2, 3, 4, 5, 6, 7, 8]
numbers.shuffle()                     // e.g., numbers == [6, 1, 8, 3, 2, 4, 7, 5]

This extension will let you retrieve a shuffled copy of an Array instance:

extension Array {
    func shuffled() -> [T] {
        if count < 2 { return self }
        var list = self
        for i in 0..<(list.count - 1) {
            let j = Int(arc4random_uniform(UInt32(list.count - i))) + i
            swap(&list[i], &list[j])
        }
        return list
    }
}
let numbers = [1, 2, 3, 4, 5, 6, 7, 8]
let mixedup = numbers.shuffled()     // e.g., mixedup == [6, 1, 8, 3, 2, 4, 7, 5]

@RobertBrax Good question - updated the answer!

In case you want the function version in Swift 1.2, it needs a bit of updating as countElements is gone, and its replacement, count, now returns a T.Index.Distance so the constraint needs to be on C.Index.Distance == Int. This version should work: gist.github.com/airspeedswift/03d07a9dc86fabdc370f

Those are the actual outputFisher-Yates should return an unbiased random permutation of the source, so there's no requirement that a particular element should move. There is a guarantee that no element moves more than once, but sometimes the "move" is to the same index. The simplest case is to think about [1, 2].shuffled()should that return [2, 1] every time?

@Jan: Yes, add guard i != j else { continue } before the swap. I filed a radar, but the new behavior is intentional.

Actually shuffleInPlace can crash if the collection indices do not start at zero, e.g. for an array slice. for i in 0..<count - 1 should be for i in startIndex ..< endIndex - 1 (and then the conversion to Swift 3 becomes almost trivial).

How do I shuffle an array in Swift? - Stack Overflow

swift
Rectangle 27 434

You can concatenate the arrays with +, building a new array

let c = a + b
print(c) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

or append one array to the other with += (or extend):

a += b

// Or:
a.extend(b) // Swift 1.2
a.appendContentsOf(b) // Swift 2
a.append(contentsOf: b) // Swift 3

print(a) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

Thanks! The += does not work with [UIView] though. Is it normal or should I file a bug report?

@Hristo: Can you give a concrete example which does not work? I cannot reproduce the problem.

Sorry, I just restarted Xcode and it started working, both in the project and the playground :) Perhaps it was some random unintended error that swift reported

Khunshan: AnyObject indicates an object, which as I understand means something that is instantiated from a class type. CGFloat is not an object, it is a scalar value. As I understand it, arrays can contain scalars, unless it is defined as containing AnyObject or are further refined. However, I suspect here the problem is that the array is wrapped in an optional, so you have to unwrap it with ! or ? first.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

ios - How do I concatenate or merge arrays in Swift? - Stack Overflow

ios arrays merge swift append
Rectangle 27 61

After a while trying different things the solution seems to remove the <T> from the signature like:

extension Array {
    func find(fn: (T) -> Bool) -> [T] {
        var to = [T]()
        for x in self {
            let t = x as T;
            if fn(t) {
                to += t
            }
        }
        return to
    }
}

Which now works as intended without build errors:

["A","B","C"].find { $0.compare("A") > 0 }
filter
let x = ["A","B","C","X].filter { $0.compare("A") > 0 }

I see. Double filtering seems rather buggy to me... But it still holds that the filter is functionally equivalent to your find, i.e. the result of the function is the same. If your filter closure has side-effects, you might not like the results, for sure.

@Palimondo Exactly, the default filter has unexpected behavior whereas the above find impl works as expected (and why it exists). It's not functionally equivalent if it executes the closure twice, which can potentially mutate scoped variables (that happened to be bug I ran into, hence the question on its behavior). Also note the question specifically mentions wanting to replace Swift's built-in filter.

We seem to be arguing over the definition of the word functional. Customarily, in functional programming paradigm where the filter, map and reduce functions originate from, functions are executed for their return values. To contrast, the each function you define above is an example of a function executed for its side-effect, because it returns nothing. I guess we can agree that the current Swift implementation is not ideal and the documentation does not state anything about its runtime characteristics.

How can I extend typed Arrays in Swift? - Stack Overflow

arrays swift
Rectangle 27 1105

Using Objective-C Classes in Swift

** If you have an existing class that you'd like to use, perform Step 2 and then skip to Step 5. (For some cases, I had to add an explicit #import <Foundation/Foundation.h to an older Objective-C File.) **

Add a .m file to your class, and name it CustomObject.m.

When adding your .m file, you'll likely be hit with a prompt that looks like this:

If you did not see the prompt, or accidentally deleted your bridging header, add a new .h file to your project and name it <#YourProjectName#>-Bridging-Header.h.

In some situations, particularly when working with Objective-C frameworks, you don't add an Objective-C class explicitly and Xcode can't find the linker. In this case, create your .h file named as mentioned above, then make sure you link its path in your target's project settings like so:

It's best practice to link your project using the $(SRCROOT) macro so that if you move your project, or work on it with others using a remote repository, it will still work. $(SRCROOT) can be thought of as the directory that contains your .xcodeproj file. It might look like this:

$(SRCROOT)/Folder/Folder/<#YourProjectName#>-Bridging-Header.h

Add another .h file and name it CustomObject.h.

CustomObject.h
#import <Foundation/Foundation.h>

@interface CustomObject : NSObject

@property (strong, nonatomic) id someProperty;

- (void) someMethod;

@end
CustomObject.m
#import "CustomObject.h"

@implementation CustomObject 

- (void) someMethod {
    NSLog(@"SomeMethod Ran");
}

@end
YourProject-Bridging-Header.h
#import "CustomObject.h"
SomeSwiftFile.swift
var instanceOfCustomObject: CustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello World"
println(instanceOfCustomObject.someProperty)
instanceOfCustomObject.someMethod()

There is no need to import explicitly; that's what the bridging header is for.

Add a .swift file to your project, and name it MySwiftObject.swift.

MySwiftObject.swift
import Foundation

class MySwiftObject : NSObject {

    var someProperty: AnyObject = "Some Initializer Val"

    init() {}

    func someFunction(someArg:AnyObject) -> String {
        var returnVal = "You sent me \(someArg)"
        return returnVal
    }   
}
SomeRandomClass.m
#import "<#YourProjectName#>-Swift.h"

The file:<#YourProjectName#>-Swift.h should already be created automatically in your project, even if you can not see it.

MySwiftObject * myOb = [MySwiftObject new];
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
myOb.someProperty = @"Hello World";
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
NSString * retString = [myOb someFunction:@"Arg"];
NSLog(@"RetString: %@", retString);

1. CodeCompletion wasn't behaving as accurately as I'd like it to. On my system, running a quick build with "cmd + r" seemed to help Swift find some of the Objective-C code and vice versa.

.swift
dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib

3. While it was originally possible to use pure Swift classes in Objective-C by using the @objc prefix, after Swift 2.0, this is no longer possible. See edit history for original explanation. If this functionality is reenabled in future Swift versions, the answer will be updated accordingly.

It is important you need to annotate methods with @objc or Swift methods won't be visible from Objective-C.

You are right. You only need to specify it if you don't use Cocoa objects. To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked @objc.

See also: WWDC 2014 Session 406: Integrating Swift with Objective-C

If importing a Objective C framework into Swift, make sure to import all frameworks that the Obj C framework depends on into your project (in Build Phases -> Link Binary With Libraries), then add #import's for those to a prefix header file, which must be added to your project in build settings (in the Prefix Header field). This includes frameworks like UIKit and Foundation, even if those are already used from within Swift. This tripped me up for hours, and no one seems to have documented these steps.

How to call Objective-C code from Swift - Stack Overflow

objective-c swift
Rectangle 27 1105

Using Objective-C Classes in Swift

** If you have an existing class that you'd like to use, perform Step 2 and then skip to Step 5. (For some cases, I had to add an explicit #import <Foundation/Foundation.h to an older Objective-C File.) **

Add a .m file to your class, and name it CustomObject.m.

When adding your .m file, you'll likely be hit with a prompt that looks like this:

If you did not see the prompt, or accidentally deleted your bridging header, add a new .h file to your project and name it <#YourProjectName#>-Bridging-Header.h.

In some situations, particularly when working with Objective-C frameworks, you don't add an Objective-C class explicitly and Xcode can't find the linker. In this case, create your .h file named as mentioned above, then make sure you link its path in your target's project settings like so:

It's best practice to link your project using the $(SRCROOT) macro so that if you move your project, or work on it with others using a remote repository, it will still work. $(SRCROOT) can be thought of as the directory that contains your .xcodeproj file. It might look like this:

$(SRCROOT)/Folder/Folder/<#YourProjectName#>-Bridging-Header.h

Add another .h file and name it CustomObject.h.

CustomObject.h
#import <Foundation/Foundation.h>

@interface CustomObject : NSObject

@property (strong, nonatomic) id someProperty;

- (void) someMethod;

@end
CustomObject.m
#import "CustomObject.h"

@implementation CustomObject 

- (void) someMethod {
    NSLog(@"SomeMethod Ran");
}

@end
YourProject-Bridging-Header.h
#import "CustomObject.h"
SomeSwiftFile.swift
var instanceOfCustomObject: CustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello World"
println(instanceOfCustomObject.someProperty)
instanceOfCustomObject.someMethod()

There is no need to import explicitly; that's what the bridging header is for.

Add a .swift file to your project, and name it MySwiftObject.swift.

MySwiftObject.swift
import Foundation

class MySwiftObject : NSObject {

    var someProperty: AnyObject = "Some Initializer Val"

    init() {}

    func someFunction(someArg:AnyObject) -> String {
        var returnVal = "You sent me \(someArg)"
        return returnVal
    }   
}
SomeRandomClass.m
#import "<#YourProjectName#>-Swift.h"

The file:<#YourProjectName#>-Swift.h should already be created automatically in your project, even if you can not see it.

MySwiftObject * myOb = [MySwiftObject new];
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
myOb.someProperty = @"Hello World";
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
NSString * retString = [myOb someFunction:@"Arg"];
NSLog(@"RetString: %@", retString);

1. CodeCompletion wasn't behaving as accurately as I'd like it to. On my system, running a quick build with "cmd + r" seemed to help Swift find some of the Objective-C code and vice versa.

.swift
dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib

3. While it was originally possible to use pure Swift classes in Objective-C by using the @objc prefix, after Swift 2.0, this is no longer possible. See edit history for original explanation. If this functionality is reenabled in future Swift versions, the answer will be updated accordingly.

It is important you need to annotate methods with @objc or Swift methods won't be visible from Objective-C.

You are right. You only need to specify it if you don't use Cocoa objects. To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked @objc.

See also: WWDC 2014 Session 406: Integrating Swift with Objective-C

If importing a Objective C framework into Swift, make sure to import all frameworks that the Obj C framework depends on into your project (in Build Phases -> Link Binary With Libraries), then add #import's for those to a prefix header file, which must be added to your project in build settings (in the Prefix Header field). This includes frameworks like UIKit and Foundation, even if those are already used from within Swift. This tripped me up for hours, and no one seems to have documented these steps.

How to call Objective-C code from Swift - Stack Overflow

objective-c swift
Rectangle 27 12

Valid in Swift 2

Even though this has been answered plenty of times already, I'd like to present an answer more in line in where the fashion of Swift programming is going, which in Crusty's words is: "Think protocols first"

nil
Array
subscript
struct Array
Swift
protocol CollectionType
protocol Indexable
Int
count
extension Indexable {
    public subscript(safe safeIndex: Index) -> _Element? {
        return safeIndex.distanceTo(endIndex) > 0 ? self[safeIndex] : nil
    }
}

: not true, but it gives the idea

As a Swift newbie I don't understand this answer. What does the code at the end represent? Is that a solution, and if so, how do I actually use it?

Sorry, this answer isn't valid anymore for Swift 3, but the process certainly is. The only difference is that now you should stop at Collection probably :)

xcode - Safe (bounds-checked) array lookup in Swift, through optional ...

xcode swift
Rectangle 27 12

Valid in Swift 2

Even though this has been answered plenty of times already, I'd like to present an answer more in line in where the fashion of Swift programming is going, which in Crusty's words is: "Think protocols first"

nil
Array
subscript
struct Array
Swift
protocol CollectionType
protocol Indexable
Int
count
extension Indexable {
    public subscript(safe safeIndex: Index) -> _Element? {
        return safeIndex.distanceTo(endIndex) > 0 ? self[safeIndex] : nil
    }
}

: not true, but it gives the idea

As a Swift newbie I don't understand this answer. What does the code at the end represent? Is that a solution, and if so, how do I actually use it?

Sorry, this answer isn't valid anymore for Swift 3, but the process certainly is. The only difference is that now you should stop at Collection probably :)

xcode - Safe (bounds-checked) array lookup in Swift, through optional ...

xcode swift
Rectangle 27 1102

Using Objective-C Classes in Swift

** If you have an existing class that you'd like to use, perform Step 2 and then skip to Step 5. (For some cases, I had to add an explicit #import <Foundation/Foundation.h to an older Objective-C File.) **

Add a .m file to your class, and name it CustomObject.m.

When adding your .m file, you'll likely be hit with a prompt that looks like this:

If you did not see the prompt, or accidentally deleted your bridging header, add a new .h file to your project and name it <#YourProjectName#>-Bridging-Header.h.

In some situations, particularly when working with Objective-C frameworks, you don't add an Objective-C class explicitly and Xcode can't find the linker. In this case, create your .h file named as mentioned above, then make sure you link its path in your target's project settings like so:

It's best practice to link your project using the $(SRCROOT) macro so that if you move your project, or work on it with others using a remote repository, it will still work. $(SRCROOT) can be thought of as the directory that contains your .xcodeproj file. It might look like this:

$(SRCROOT)/Folder/Folder/<#YourProjectName#>-Bridging-Header.h

Add another .h file and name it CustomObject.h.

CustomObject.h
#import <Foundation/Foundation.h>

@interface CustomObject : NSObject

@property (strong, nonatomic) id someProperty;

- (void) someMethod;

@end
CustomObject.m
#import "CustomObject.h"

@implementation CustomObject 

- (void) someMethod {
    NSLog(@"SomeMethod Ran");
}

@end
YourProject-Bridging-Header.h
#import "CustomObject.h"
SomeSwiftFile.swift
var instanceOfCustomObject: CustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello World"
println(instanceOfCustomObject.someProperty)
instanceOfCustomObject.someMethod()

There is no need to import explicitly; that's what the bridging header is for.

Add a .swift file to your project, and name it MySwiftObject.swift.

MySwiftObject.swift
import Foundation

class MySwiftObject : NSObject {

    var someProperty: AnyObject = "Some Initializer Val"

    init() {}

    func someFunction(someArg:AnyObject) -> String {
        var returnVal = "You sent me \(someArg)"
        return returnVal
    }   
}
SomeRandomClass.m
#import "<#YourProjectName#>-Swift.h"

The file:<#YourProjectName#>-Swift.h should already be created automatically in your project, even if you can not see it.

MySwiftObject * myOb = [MySwiftObject new];
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
myOb.someProperty = @"Hello World";
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
NSString * retString = [myOb someFunction:@"Arg"];
NSLog(@"RetString: %@", retString);

1. CodeCompletion wasn't behaving as accurately as I'd like it to. On my system, running a quick build with "cmd + r" seemed to help Swift find some of the Objective-C code and vice versa.

.swift
dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib

3. While it was originally possible to use pure Swift classes in Objective-C by using the @objc prefix, after Swift 2.0, this is no longer possible. See edit history for original explanation. If this functionality is reenabled in future Swift versions, the answer will be updated accordingly.

It is important you need to annotate methods with @objc or Swift methods won't be visible from Objective-C.

You are right. You only need to specify it if you don't use Cocoa objects. To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked @objc.

See also: WWDC 2014 Session 406: Integrating Swift with Objective-C

If importing a Objective C framework into Swift, make sure to import all frameworks that the Obj C framework depends on into your project (in Build Phases -> Link Binary With Libraries), then add #import's for those to a prefix header file, which must be added to your project in build settings (in the Prefix Header field). This includes frameworks like UIKit and Foundation, even if those are already used from within Swift. This tripped me up for hours, and no one seems to have documented these steps.

How to call Objective-C code from Swift - Stack Overflow

objective-c swift
Rectangle 27 1106

Using Objective-C Classes in Swift

** If you have an existing class that you'd like to use, perform Step 2 and then skip to Step 5. (For some cases, I had to add an explicit #import <Foundation/Foundation.h to an older Objective-C File.) **

Add a .m file to your class, and name it CustomObject.m.

When adding your .m file, you'll likely be hit with a prompt that looks like this:

If you did not see the prompt, or accidentally deleted your bridging header, add a new .h file to your project and name it <#YourProjectName#>-Bridging-Header.h.

In some situations, particularly when working with Objective-C frameworks, you don't add an Objective-C class explicitly and Xcode can't find the linker. In this case, create your .h file named as mentioned above, then make sure you link its path in your target's project settings like so:

It's best practice to link your project using the $(SRCROOT) macro so that if you move your project, or work on it with others using a remote repository, it will still work. $(SRCROOT) can be thought of as the directory that contains your .xcodeproj file. It might look like this:

$(SRCROOT)/Folder/Folder/<#YourProjectName#>-Bridging-Header.h

Add another .h file and name it CustomObject.h.

CustomObject.h
#import <Foundation/Foundation.h>

@interface CustomObject : NSObject

@property (strong, nonatomic) id someProperty;

- (void) someMethod;

@end
CustomObject.m
#import "CustomObject.h"

@implementation CustomObject 

- (void) someMethod {
    NSLog(@"SomeMethod Ran");
}

@end
YourProject-Bridging-Header.h
#import "CustomObject.h"
SomeSwiftFile.swift
var instanceOfCustomObject: CustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello World"
println(instanceOfCustomObject.someProperty)
instanceOfCustomObject.someMethod()

There is no need to import explicitly; that's what the bridging header is for.

Add a .swift file to your project, and name it MySwiftObject.swift.

MySwiftObject.swift
import Foundation

class MySwiftObject : NSObject {

    var someProperty: AnyObject = "Some Initializer Val"

    init() {}

    func someFunction(someArg:AnyObject) -> String {
        var returnVal = "You sent me \(someArg)"
        return returnVal
    }   
}
SomeRandomClass.m
#import "<#YourProjectName#>-Swift.h"

The file:<#YourProjectName#>-Swift.h should already be created automatically in your project, even if you can not see it.

MySwiftObject * myOb = [MySwiftObject new];
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
myOb.someProperty = @"Hello World";
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
NSString * retString = [myOb someFunction:@"Arg"];
NSLog(@"RetString: %@", retString);

1. CodeCompletion wasn't behaving as accurately as I'd like it to. On my system, running a quick build with "cmd + r" seemed to help Swift find some of the Objective-C code and vice versa.

.swift
dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib

3. While it was originally possible to use pure Swift classes in Objective-C by using the @objc prefix, after Swift 2.0, this is no longer possible. See edit history for original explanation. If this functionality is reenabled in future Swift versions, the answer will be updated accordingly.

It is important you need to annotate methods with @objc or Swift methods won't be visible from Objective-C.

You are right. You only need to specify it if you don't use Cocoa objects. To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked @objc.

See also: WWDC 2014 Session 406: Integrating Swift with Objective-C

If importing a Objective C framework into Swift, make sure to import all frameworks that the Obj C framework depends on into your project (in Build Phases -> Link Binary With Libraries), then add #import's for those to a prefix header file, which must be added to your project in build settings (in the Prefix Header field). This includes frameworks like UIKit and Foundation, even if those are already used from within Swift. This tripped me up for hours, and no one seems to have documented these steps.

How to call Objective-C code from Swift - Stack Overflow

objective-c swift
Rectangle 27 17

Swift 3 with Swift FacebookSDK

pod 'FacebookCore'
pod 'FacebookLogin'
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>fb$(YOUR_FB_APP_ID)</string>
        </array>
    </dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fb-messenger-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
</array>
<key>FacebookAppID</key>
<string>$(YOUR_FB_APP_ID)</string>
<key>FacebookDisplayName</key>
<string>$(YOUR_APP_NAME)</string>
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
    ...
}

func applicationDidBecomeActive(_ application: UIApplication) {
    AppEventsLogger.activate(application)
}

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let appId = SDKSettings.appId
    if url.scheme != nil && url.scheme!.hasPrefix("fb\(appId)") && url.host ==  "authorize" { // facebook
        return SDKApplicationDelegate.shared.application(app, open: url, options: options)
    }
    return false
}

...
let facebookManager = LoginManager(loginBehavior: .systemAccount, defaultAudience: .everyone)
func loginWithFacebook() {
    self.facebookManager.logIn(HAAccountManager.shared.facebookPermissions, viewController: self) { (result) in
        switch result {
        case .failed(let error):
            self.showAlert(forError: error as NSError)
        case .cancelled:
            print("FB login cancelled")
        case .success(let grantedPermissions, let deniedPermissions, let accessToken):
            if grantedPermissions.contains(Permission(name: "email")) == true {
                ApiClient.shared.facebookSignIn(authToken: accessToken.authenticationToken, completion: { (err, user) in
                    if err == nil {
                        // success
                    }
                    else {
                        self.showAlert(forError: err!)
                    }
                })
            }
            else {
                self.showAlert(forError: HAError(title: String(format: String.somethingError, String.signIn), message: grantedPermissions.contains(Permission(name: "email")) == true ? String.noAccountFound : String.missingEmailForSignUp))
            }
        }
    }
}
// custom ex
AppEventsLogger.log(AppEvent(name: "open_app", parameters: ["logged_in": NSNumber(value: HAAccountManager.shared.isUserLoggedIn())], valueToSum: nil))

// purchase ex
AppEventsLogger.log(
    AppEvent.purchased(
        amount: Double(revenue),
        currency: currency,
        extraParameters: [
            AppEventParameterName.contentId : orderId,
            AppEventParameterName.itemCount : order.orderItems.count.nsNumber()
        ])
)

it works. but seems it is different from the official documentation: developers.facebook.com/quickstarts/873570042741264/ - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation

yeah the check for the "fb" is to support other frameworks (braintree and branch for my app) @User9527

ios - Integration new facebook SDK by swift - Stack Overflow

ios objective-c iphone facebook swift
Rectangle 27 129

The let keyword is for declaring constants that can't be changed. If you want to modify a variable you should use var instead, e.g:

var animals = ["cats", "dogs", "chimps", "moose"]

animals.remove(at: 2)  //["cats", "dogs", "moose"]

A non-mutating alternative that will keep the original collection unchanged is to use filter to create a new collection without the elements you want removed, e.g:

let pets = animals.filter { $0 != "chimps" }

How to remove an element from an array in Swift - Stack Overflow

arrays swift