Skip to content

Instantly share code, notes, and snippets.

@shoheiyokoyama
Last active September 28, 2016 09:25
Show Gist options
  • Select an option

  • Save shoheiyokoyama/086ee9300bdb40643fe9dd111434f3d8 to your computer and use it in GitHub Desktop.

Select an option

Save shoheiyokoyama/086ee9300bdb40643fe9dd111434f3d8 to your computer and use it in GitHub Desktop.
Swiftらしいコーディングを学ぶ 「Generics」 ref: http://qiita.com/shoheiyokoyama/items/31eca0d4b27bc9608eb8
class ClassName<TypeParameter> {
//Class statements
}
var class = ClassName<TypeParameter>()
func functionName<PlaceholderTypeName,..>(paramerters:PlaceholderTypeName,...)
func swapTwoInts(inout a: Int, inout _ b: Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// Prints "someInt is now 107, and anotherInt is now 3"
//他の型で使用するためには、それぞれの型を指定しなければならない
func swapTwoInts(inout a: Int, inout _ b: Int)
func swapTwoDouble(inout a: Double, inout _ b: Double)
func swapTwoString(inout a: String, inout _ b: String)
func swapTwoValues<T>(inout a: T, inout _ b: T) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoValues(&someInt, &anotherInt)
print("someInt is \(someInt), anotherInt is \(anotherInt)")
// someInt is 107, anotherInt is 3
var someString = "hello"
var anotherString = "world"
swapTwoValues(&someString, &anotherString)
print("someString is \(someString), anotherString is \(anotherString)")
//someString is world, anotherString is hello
var someDouble: Double = 2.5
var someFloat: Float = 3.54
swapTwoValues(&someDouble, &someFloat)
//Cannot convert value of type 'inout Double' to expected argument type 'inout _'
func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
// function body goes here
}
func findLargestInArray<T>(array: [T]) -> T? {
if array.isEmpty { return nil }
var largestValue = array.first
array.forEach { val in
//Compiler Error
largestValue = val > largestValue ? val : largestValue
}
return largestValue
}
func findLargestInArray<T: Comparable>(array: [T]) -> T? {
if array.isEmpty { return nil }
var largestValue = array.first
array.forEach { val in
largestValue = val > largestValue ? val : largestValue
}
return largestValue
}
let array = [1, 2, 3, 5, 7, 10]
let largestValue = findLargestInArray(array)
print(largestValue)//10
struct Queue<Element> {
private var elements = [Element]()
mutating func enqueue(newElement: Element) {
elements.append(newElement)
}
mutating func dequeue() -> Element? {
guard !elements.isEmpty else { return nil }
return elements.removeAtIndex(0)
}
}
var intQueue = Queue<Int>()
intQueue.enqueue(3)//[3]
intQueue.enqueue(5)//[3, 5]
intQueue.dequeue()//3 elements=>[5]
intQueue.dequeue()//5 elements=>[]
intQueue.dequeue()//nil
var stringQueue = Queue<String>()
stringQueue.enqueue("Generics")//["Generics"]
stringQueue.enqueue("Generic Types")//["Generics", "Generic Types"]
protocol Container {
associatedtype ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
func allItemsMatch<C1: Container, C2: Container
where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
(someContainer: C1, _ anotherContainer: C2) -> Bool {
if someContainer.count != anotherContainer.count {
return false
}
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
return true
}
extension CollectionType where Self.Generator.Element: Comparable {
func largestValue() -> Generator.Element? {
guard var largestValue = first else { return nil }
for item in self {
if item > largestValue {
largestValue = item
}
}
return largestValue
}
}
where Self.Generator.Element: Comparable
[1, 2, 3, 4, 5].largestValue()//5
"Generics".characters.largestValue()//s
(0..<1000).largestValue()//999
extension Queue {
func peek() -> Element? {
return elements.first
}
}
stringQueue.peek()//"Generics"
class BaseClass<T> {}
class InheritClass<T>: Box<T> {}
//TypeParameterの名前は変えられるが、親クラスと揃える必要がある
class InheritClass<U>: Box<U> {}//○
class InheritClass<U>: Box<T> {}//×
class StringClass: BaseClass<String> {}
protocol Container {
associatedtype ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
struct IntStack: Container {
var items = [Int]()
typealias ItemType = Int
mutating func append(item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
var count: Int {
return items.count
}
subscript(i: Int) -> Int {
return items[i]
}
}
var intStack = IntStack()
intStack.append(2)
intStack.append(3)
intStack.append(4)
intStack.count//3
intStack[2]//4
struct Queue<Element>: Container {
private var elements = [Element]()
mutating func enqueue(newElement: Element) {
elements.append(newElement)
}
mutating func dequeue() -> Element? {
guard !elements.isEmpty else { return nil }
return elements.removeAtIndex(0)
}
mutating func append(item: Element) {
enqueue(item)
}
var count: Int {
return elements.count
}
subscript(i: Int) -> Element {
return elements[i]
}
}
var intQueue = Queue<Int>()
intQueue.append(3)//[3]
intQueue.append(5)//[3, 5]
intQueue[1]//5
intQueue.count//2
var stringQueue = Queue<String>()
stringQueue.append("Generics")//["Generics"]
stringQueue.append("Generic Types")//["Generics", "Generic Types"]
stringQueue[0]//"Generics"
stringQueue.count//2
protocol GeneratorType {
typealias Element
func next() -> Element?
}
struct StructName<TypeParameter> {
//struct statements
}
var struct = StructName<TypeParameter>()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment