From ddb81086a93b42ac724751675512387865dd52c2 Mon Sep 17 00:00:00 2001 From: Ishan Chhabra <32290367+ishan-chhabra@users.noreply.github.com> Date: Sun, 27 Jan 2019 08:16:52 +0530 Subject: [PATCH] Add Generics Section (#33367) * Add Generics Section * fix: added front matter block --- guide/english/swift/generics/index.md | 46 +++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 guide/english/swift/generics/index.md diff --git a/guide/english/swift/generics/index.md b/guide/english/swift/generics/index.md new file mode 100644 index 00000000000..afadc3586e0 --- /dev/null +++ b/guide/english/swift/generics/index.md @@ -0,0 +1,46 @@ +--- +title: Generics +--- + +# Generics + +Write a name inside angle brackets to make a generic function or type. +```Swift +func makeArray(repeating item: Item, numberOfTimes: Int) -> [Item] { + var result = [Item]() + for _ in 0.. { + case none + case some(Wrapped) + } + var possibleInteger: OptionalValue = .none + possibleInteger = .some(100) +``` + +Use `where` right before the body to specify a list of requirements—for example, to require the type to implement a protocol, to require two types to be the same, or to require a class to have a particular superclass. + +```swift +func anyCommonElements(_ lhs: T, _ rhs: U) -> Bool +where T.Element: Equatable, T.Element == U.Element +{ + for lhsItem in lhs { + for rhsItem in rhs { + if lhsItem == rhsItem { + return true + } + } + } +return false +} +anyCommonElements([1, 2, 3], [3])