Last active
August 29, 2015 14:02
-
-
Save cwagdev/7e0c7d8e2d2c9808be92 to your computer and use it in GitHub Desktop.
Swift Array.firstObject() and Array.lastObject() Extensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Array { | |
func firstObject() -> T! { | |
var firstItem: T! | |
if !self.isEmpty { | |
firstItem = self[0] | |
} | |
return firstItem | |
} | |
func lastObject() -> T! { | |
var lastItem: T! | |
if !self.isEmpty { | |
lastItem = self[self.count-1] | |
} | |
return lastItem | |
} | |
} | |
var foo = [1,2,3] | |
var firstObject = foo.firstObject() // should return 1 | |
var lastObject = foo.lastObject() // should return 3 | |
firstObject == foo[0] // verify they equal | |
var bar: Int[] = [] // empty array | |
bar.firstObject() // should be nil | |
bar.lastObject() // should be nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What made you choose not to have the methods return
T!
instead ofT?