repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
haikieu/iOS-ViewController-Presentation-Sample
|
PresentAndWindow/PresentAndWindow/MainViewController.swift
|
1
|
6794
|
//
// ViewController.swift
// PresentAndWindow
//
// Created by Kieu, Hai N on 4/10/17.
// Copyright © 2017 Hai Kieu. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if self.isPresented {
let dismissBtn = UIBarButtonItem.init(title: "Dismiss", style: .plain, target: self, action: #selector(MainViewController.dismissVC))
self.navigationItem.leftBarButtonItem = dismissBtn
self.title = "Level #\(self.currentPresentLevel)"
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var vcSegment: UISegmentedControl!
@IBOutlet weak var transitionStyleSegment: UISegmentedControl!
@IBAction func transitionStyleChanged(_ sender: Any) {
tableView.reloadData()
}
internal var isSelectedPartialCurl : Bool {
let selectedTransion = UIModalTransitionStyle.init(rawValue: transitionStyleSegment.selectedSegmentIndex)
return selectedTransion == .partialCurl
}
internal func dismissVC() {
self.dismiss(animated: true, completion: nil)
}
@IBAction func pushViewController(_ sender: Any) {
let vcType = "MainViewController"
guard let viewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MainViewController") as? MainViewController else {
self.alert(withTitle: "Not found This Kind of \(vcType)")
return
}
guard let navigationController = self.navigationController else {
self.alert(withTitle: "Cannot keep pushing vc because there's no navigation vc")
return
}
navigationController.pushViewController(viewController, animated: true)
}
@IBAction func presentPopover(_ sender: Any) {
let vcType = "NavigationController"
guard let presentedVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NavigationController") as? UINavigationController else {
self.alert(withTitle: "Not found This Kind of \(vcType)")
return
}
var presentingVC : UIViewController = self
if vcSegment.selectedSegmentIndex == 1 {
//From root view controller
presentingVC = (UIApplication.shared.keyWindow?.rootViewController)!
}
presentedVC.modalPresentationStyle = .popover
let popOverController = presentedVC.popoverPresentationController
popOverController?.permittedArrowDirections = .any
popOverController?.barButtonItem = self.navigationItem.rightBarButtonItem
presentingVC.present(presentedVC, animated: true) {
//Do something
}
}
}
extension MainViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vcType = "RootViewController"
guard let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NavigationController") as? NavigationController else {
self.alert(withTitle: "Not found This Kind of \(vcType)")
return
}
var presentStyle = UIModalPresentationStyle.fullScreen
if isSelectedPartialCurl == false {
switch indexPath.row {
case 0:
presentStyle = UIModalPresentationStyle.fullScreen
case 1:
presentStyle = UIModalPresentationStyle.pageSheet
case 2:
presentStyle = UIModalPresentationStyle.formSheet
case 3:
presentStyle = UIModalPresentationStyle.currentContext
case 4:
presentStyle = UIModalPresentationStyle.custom
case 5:
presentStyle = UIModalPresentationStyle.overFullScreen
case 6:
presentStyle = UIModalPresentationStyle.overCurrentContext
default:
presentStyle = UIModalPresentationStyle.none
}
}
vc.modalPresentationStyle = presentStyle
vc.modalTransitionStyle = UIModalTransitionStyle.init(rawValue: transitionStyleSegment.selectedSegmentIndex)!
if vcSegment.selectedSegmentIndex == 0 {
//From current VC
self.present(vc, animated: true)
} else {
//From root view controller
UIApplication.shared.keyWindow?.rootViewController?.present(vc, animated: true)
}
}
}
extension MainViewController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSelectedPartialCurl {
return 1
}
return 7
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var acell = tableView.dequeueReusableCell(withIdentifier: "cell")
if acell == nil {
acell = UITableViewCell.init(style: .default, reuseIdentifier: "cell")
}
guard let cell = acell else {
return UITableViewCell.init()
}
var text = UIModalPresentationStyle.fullScreen.stringValue
switch indexPath.row {
case 0:
text = UIModalPresentationStyle.fullScreen.stringValue
case 1:
text = UIModalPresentationStyle.pageSheet.stringValue
case 2:
text = UIModalPresentationStyle.formSheet.stringValue
case 3:
text = UIModalPresentationStyle.currentContext.stringValue
case 4:
text = UIModalPresentationStyle.custom.stringValue
case 5:
text = UIModalPresentationStyle.overFullScreen.stringValue
case 6:
text = UIModalPresentationStyle.overCurrentContext.stringValue
case 7:
fallthrough
default:
text = "none"
}
cell.textLabel?.text = text
return cell
}
}
|
mit
|
ab0e03577a8fe07cc4883d92b42ce1f3
| 34.941799 | 176 | 0.629766 | 5.964004 | false | false | false | false |
HTWDD/HTWDresden-iOS
|
HTWDD/Components/Canteen/Models/CanteenDetail.swift
|
1
|
479
|
//
// CanteenDetails.swift
// HTWDD
//
// Created by Mustafa Karademir on 11.07.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import Foundation
// MARK: - Canteen Details
struct CanteenDetail {
let canteen: Canteen
let meals: [Meal]
}
// MARK: - Equatable
extension CanteenDetail: Equatable {
static func ==(lhs: CanteenDetail, rhs: CanteenDetail) -> Bool {
return lhs.canteen == rhs.canteen && lhs.meals == rhs.meals
}
}
|
gpl-2.0
|
afb809118bbae5d6af12b6366ee3c599
| 18.916667 | 68 | 0.650628 | 3.463768 | false | false | false | false |
ivanbruel/Moya-ObjectMapper
|
Sample/Common/Model/Repository.swift
|
1
|
5542
|
//
// Repository.swift
// Demo
//
// Created by Ivan Bruel on 28/06/16.
// Copyright © 2016 Ash Furrow. All rights reserved.
//
import Foundation
import ObjectMapper
struct Repository: ImmutableMappable {
var keysURL: String
var statusesURL: String
var issuesURL: String
var defaultBranch: String
var issueEventsURL: String?
var id: Int
var owner: Owner
var eventsURL: String
var subscriptionURL: String
var watchers: Int
var gitCommitsURL: String
var subscribersURL: String
var cloneURL: String
var hasWiki: Bool
var URL: String
var pullsURL: String
var fork: Bool
var notificationsURL: String
var description: String
var collaboratorsURL: String
var deploymentsURL: String
var languagesURL: String
var hasIssues: Bool
var commentsURL: String
var isPrivate: Bool
var size: Int
var gitTagsURL: String
var updatedAt: String
var sshURL: String
var name: String
var contentsURL: String
var archiveURL: String
var milestonesURL: String
var blobsURL: String
var contributorsURL: String
var openIssuesCount: Int
var forksCount: Int
var treesURL: String
var svnURL: String
var commitsURL: String
var createdAt: String
var forksURL: String
var hasDownloads: Bool
var mirrorURL: String?
var homepage: String
var teamsURL: String
var branchesURL: String
var issueCommentURL: String
var mergesURL: String
var gitRefsURL: String
var gitURL: String
var forks: Int
var openIssues: Int
var hooksURL: String
var htmlURL: String
var stargazersURL: String
var assigneesURL: String
var compareURL: String
var fullName: String
var tagsURL: String
var releasesURL: String
var pushedAt: String?
var labelsURL: String
var downloadsURL: String
var stargazersCount: Int
var watchersCount: Int
var language: String
var hasPages: Bool
init(map: Map) {
keysURL = (try? map.value("keys_url")) ?? ""
statusesURL = (try? map.value("statuses_url")) ?? ""
issuesURL = (try? map.value("issues_url")) ?? ""
defaultBranch = (try? map.value("default_branch")) ?? ""
issueEventsURL = (try? map.value("issues_events_url")) ?? ""
id = try! map.value("id")
owner = try! map.value("owner")
eventsURL = (try? map.value("events_url")) ?? ""
subscriptionURL = (try? map.value("subscription_url")) ?? ""
watchers = (try? map.value("watchers")) ?? 0
gitCommitsURL = (try? map.value("git_commits_url")) ?? ""
subscribersURL = (try? map.value("subscribers_url")) ?? ""
cloneURL = (try? map.value("clone_url")) ?? ""
hasWiki = (try? map.value("has_wiki")) ?? false
URL = (try? map.value("url")) ?? ""
pullsURL = (try? map.value("pulls_url")) ?? ""
fork = (try? map.value("fork")) ?? false
notificationsURL = (try? map.value("notifications_url")) ?? ""
description = (try? map.value("description")) ?? ""
collaboratorsURL = (try? map.value("collaborators_url")) ?? ""
deploymentsURL = (try? map.value("deployments_url")) ?? ""
languagesURL = (try? map.value("languages_url")) ?? ""
hasIssues = (try? map.value("has_issues")) ?? false
commentsURL = (try? map.value("comments_url")) ?? ""
isPrivate = (try? map.value("private")) ?? false
size = (try? map.value("size")) ?? 0
gitTagsURL = (try? map.value("git_tags_url")) ?? ""
updatedAt = (try? map.value("updated_at")) ?? ""
sshURL = (try? map.value("ssh_url")) ?? ""
name = (try? map.value("name")) ?? ""
contentsURL = (try? map.value("contents_url")) ?? ""
archiveURL = (try? map.value("archive_url")) ?? ""
milestonesURL = (try? map.value("milestones_url")) ?? ""
blobsURL = (try? map.value("blobs_url")) ?? ""
contributorsURL = (try? map.value("contributors_url")) ?? ""
openIssuesCount = (try? map.value("open_issues_count")) ?? 0
forksCount = (try? map.value("forks_count")) ?? 0
treesURL = (try? map.value("trees_url")) ?? ""
svnURL = (try? map.value("svn_url")) ?? ""
commitsURL = (try? map.value("commits_url")) ?? ""
createdAt = (try? map.value("created_at")) ?? ""
forksURL = (try? map.value("forks_url")) ?? ""
hasDownloads = (try? map.value("has_downloads")) ?? false
mirrorURL = try? map.value("mirror_url")
homepage = (try? map.value("homepage")) ?? ""
teamsURL = (try? map.value("teams_url")) ?? ""
branchesURL = (try? map.value("branches_url")) ?? ""
issueCommentURL = (try? map.value("issue_comment_url")) ?? ""
mergesURL = (try? map.value("merges_url")) ?? ""
gitRefsURL = (try? map.value("git_refs_url")) ?? ""
gitURL = (try? map.value("git_url")) ?? ""
forks = (try? map.value("forks")) ?? 0
openIssues = (try? map.value("open_issues")) ?? 0
hooksURL = (try? map.value("hooks_url")) ?? ""
htmlURL = (try? map.value("html_url")) ?? ""
stargazersURL = (try? map.value("stargazers_url")) ?? ""
assigneesURL = (try? map.value("assignees_url")) ?? ""
compareURL = (try? map.value("compare_url")) ?? ""
fullName = (try? map.value("full_name")) ?? ""
tagsURL = (try? map.value("tags_url")) ?? ""
releasesURL = (try? map.value("releases_url")) ?? ""
pushedAt = (try? map.value("pushed_at"))
labelsURL = (try? map.value("labels_url")) ?? ""
downloadsURL = (try? map.value("downloads_url")) ?? ""
stargazersCount = (try? map.value("stargazers_count")) ?? 0
watchersCount = (try? map.value("watchers_count")) ?? 0
language = (try? map.value("language")) ?? ""
hasPages = (try? map.value("has_pages")) ?? false
}
}
|
mit
|
8d0750a05a7fa7e0d522544d06165807
| 35.453947 | 66 | 0.629128 | 3.471805 | false | false | false | false |
kstaring/swift
|
test/NameBinding/reference-dependencies.swift
|
1
|
15071
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: cp %s %t/main.swift
// RUN: %target-swift-frontend -parse -primary-file %t/main.swift %S/Inputs/reference-dependencies-helper.swift -emit-reference-dependencies-path - > %t.swiftdeps
// RUN: %FileCheck %s < %t.swiftdeps
// RUN: %FileCheck -check-prefix=NEGATIVE %s < %t.swiftdeps
// CHECK-LABEL: {{^provides-top-level:$}}
// CHECK-NEXT: "IntWrapper"
// CHECK-NEXT: "=="
// CHECK-NEXT: "<"
// CHECK-NEXT: "***"
// CHECK-NEXT: "^^^"
// CHECK-NEXT: "Subclass"
// CHECK-NEXT: "MyArray"
// CHECK-NEXT: "someGlobal"
// CHECK-NEXT: "ExpressibleByExtraFloatLiteral"
// CHECK-NEXT: "~~~"
// CHECK-NEXT: "ThreeTilde"
// CHECK-NEXT: "overloadedOnProto"
// CHECK-NEXT: "overloadedOnProto"
// CHECK-NEXT: "~~~~"
// CHECK-NEXT: "FourTilde"
// CHECK-NEXT: "FourTildeImpl"
// CHECK-NEXT: "FiveTildeImpl"
// CHECK-NEXT: "topLevelComputedProperty"
// CHECK-NEXT: "lookUpManyTopLevelNames"
// CHECK-NEXT: "testOperators"
// CHECK-NEXT: "TopLevelForMemberLookup"
// CHECK-NEXT: "lookUpMembers"
// CHECK-NEXT: "publicUseOfMember"
// CHECK-NEXT: "Outer"
// CHECK: "eof"
// CHECK-NEXT: "~~~"
// CHECK-NEXT: "~~~~"
// CHECK-NEXT: "~~~~"
// CHECK-NEXT: "~~~~~"
// CHECK-LABEL: {{^provides-nominal:$}}
// CHECK-NEXT: "V4main10IntWrapper"
// CHECK-NEXT: "VV4main10IntWrapper16InnerForNoReason"
// CHECK-NEXT: "C4main8Subclass"
// CHECK-NEXT: "VE4mainSb11InnerToBool"
// CHECK: "V4main9Sentinel1"
// CHECK-NEXT: "V4main9Sentinel2"
// CHECK-LABEL: {{^provides-member:$}}
// CHECK-NEXT: - ["V4main10IntWrapper", ""]
// CHECK-NEXT: - ["VV4main10IntWrapper16InnerForNoReason", ""]
// CHECK-NEXT: - ["C4main8Subclass", ""]
// CHECK-NEXT: - ["Ps25ExpressibleByArrayLiteral", ""]
// CHECK-NEXT: - ["Sb", ""]
// CHECK-NEXT: - ["VE4mainSb11InnerToBool", ""]
// CHECK: - ["V4main9Sentinel1", ""]
// CHECK-NEXT: - ["V4main9Sentinel2", ""]
// CHECK: - ["Ps25ExpressibleByArrayLiteral", "useless"]
// CHECK-NEXT: - ["Ps25ExpressibleByArrayLiteral", "useless2"]
// CHECK-NEXT: - ["Sb", "InnerToBool"]
// CHECK-NEXT: - ["{{.*[0-9]}}FourTildeImpl", "~~~~"]
// CHECK-NEXT: - ["{{.*[0-9]}}FiveTildeImpl", "~~~~~"]
// CHECK-LABEL: {{^depends-top-level:$}}
// CHECK-DAG: - "Comparable"
struct IntWrapper: Comparable {
// CHECK-DAG: - "Int"
var value: Int
struct InnerForNoReason {}
// CHECK-DAG: - "TypeReferencedOnlyBySubscript"
subscript(_: TypeReferencedOnlyBySubscript) -> Void { return () }
// CHECK-DAG: - "TypeReferencedOnlyByPrivateSubscript"
// FIXME: This should be marked "!private".
private subscript(_: TypeReferencedOnlyByPrivateSubscript) -> Void { return () }
}
// CHECK-DAG: "IntWrapper"
// CHECK-DAG: "Bool"
func ==(lhs: IntWrapper, rhs: IntWrapper) -> Bool {
// CHECK-DAG: "=="
return lhs.value == rhs.value
}
func <(lhs: IntWrapper, rhs: IntWrapper) -> Bool {
// CHECK-DAG: "<"
return lhs.value < rhs.value
}
// Test operator lookup without a use of the same operator.
// This is declared in the other file.
// CHECK-DAG: "***"
prefix func ***(lhs: IntWrapper) {}
// This is provided as an operator but not implemented here.
prefix operator ^^^
// CHECK-DAG: "ClassFromOtherFile"
class Subclass : ClassFromOtherFile {}
// CHECK-DAG: "Array"
typealias MyArray = Array<Bool>
// CHECK-DAG: "ExpressibleByArrayLiteral"
extension ExpressibleByArrayLiteral {
final func useless() {}
}
// CHECK-DAG: OtherFileElementType
extension ExpressibleByArrayLiteral where Element == OtherFileElementType {
final func useless2() {}
}
// CHECK-DAG: "IntegerLiteralType"
let someGlobal = 42
extension Bool {
struct InnerToBool {}
}
// CHECK-DAG: - "ExpressibleByOtherFileAliasForFloatLiteral"
protocol ExpressibleByExtraFloatLiteral
: ExpressibleByOtherFileAliasForFloatLiteral {
}
// CHECK-DAG: !private "ExpressibleByUnicodeScalarLiteral"
private protocol ExpressibleByExtraCharLiteral : ExpressibleByUnicodeScalarLiteral {
}
prefix operator ~~~
protocol ThreeTilde {
prefix static func ~~~(lhs: Self)
}
private struct ThreeTildeTypeImpl : ThreeTilde {
}
func overloadedOnProto<T>(_: T) {}
func overloadedOnProto<T: ThreeTilde>(_: T) {}
// CHECK-DAG: - "~~~"
private prefix func ~~~(_: ThreeTildeTypeImpl) {}
// CHECK-DAG: - "~~~~"
prefix operator ~~~~
protocol FourTilde {
prefix static func ~~~~(arg: Self)
}
struct FourTildeImpl : FourTilde {}
extension FourTildeImpl {
prefix static func ~~~~(arg: FourTildeImpl) {}
}
// CHECK-DAG: - "~~~~~"
// ~~~~~ is declared in the other file.
struct FiveTildeImpl {}
extension FiveTildeImpl {
prefix static func ~~~~~(arg: FiveTildeImpl) {}
}
var topLevelComputedProperty: Bool {
return true
}
func lookUpManyTopLevelNames() {
// CHECK-DAG: !private "Dictionary"
let _: Dictionary = [1:1]
// CHECK-DAG: !private "UInt"
// CHECK-DAG: !private "+"
let _: UInt = [1, 2].reduce(0, +)
// CHECK-DAG: !private "-"
let _: UInt = 3 - 2 - 1
// CHECK-DAG: !private "AliasFromOtherFile"
let _: AliasFromOtherFile = 1
// CHECK-DAG: !private "funcFromOtherFile"
funcFromOtherFile()
// "CInt" is not used as a top-level name here.
// CHECK-DAG: !private "StringLiteralType"
// NEGATIVE-NOT: "CInt"
_ = "abc"
// NEGATIVE-NOT: - "max"
print(Int.max)
// NEGATIVE-NOT: - "Stride"
let _: Int.Stride = 0
// CHECK-DAG: !private "OtherFileOuterType"
_ = OtherFileOuterType.InnerType.sharedConstant
_ = OtherFileOuterType.InnerType()
// CHECK-DAG: !private "OtherFileAliasForSecret"
_ = OtherFileAliasForSecret.constant
// CHECK-DAG: !private "otherFileUse"
// CHECK-DAG: !private "otherFileGetImpl"
otherFileUse(otherFileGetImpl())
// CHECK-DAG: !private "otherFileUseGeneric"
// CHECK-DAG: !private "otherFileGetImpl2"
otherFileUseGeneric(otherFileGetImpl2())
// CHECK-DAG: !private "getOtherFileIntArray"
for _ in getOtherFileIntArray() {}
// CHECK-DAG: !private "getOtherFileEnum"
switch getOtherFileEnum() {
case .Value:
break
}
_ = .Value as OtherFileEnumWrapper.Enum
let _: OtherFileEnumWrapper.Enum = .Value
_ = OtherFileEnumWrapper.Enum.Value
_ = { (_: PrivateTopLevelStruct.ValueType) -> PrivateTopLevelStruct2.ValueType? in
return nil
}
typealias X = OtherFileEnumWrapper.Enum
let value: Any = .Value as X
switch value {
case is OtherFileEnumWrapper.Enum:
break
}
// CHECK-DAG: !private "~="
switch 42 {
case 50:
break
}
for _: OtherFileEnumWrapper.Enum in EmptyIterator<X>() {}
// CHECK-DAG: !private "otherFileGetNonImpl"
overloadedOnProto(otherFileGetNonImpl())
}
func testOperators<T: Starry>(generic: T, specific: Flyswatter) {
// CHECK-DAG: !private "****"
// CHECK-DAG: !private "*****"
// CHECK-DAG: !private "******"
****generic
generic*****0
0******generic
****specific
specific*****0
0******specific
}
struct TopLevelForMemberLookup {
static func m1() {}
static func m2() {}
static func m3() {}
}
func lookUpMembers() {
TopLevelForMemberLookup.m1()
TopLevelForMemberLookup.m3()
}
public let publicUseOfMember: () = TopLevelForMemberLookup.m2()
struct Outer {
struct Inner {
func method() {
// CHECK-DAG: !private "CUnsignedInt"
let _: CUnsignedInt = 5
}
}
}
// CHECK-DAG: !private "privateFunc"
private func privateFunc() {}
// CHECK-DAG: - "topLevel1"
var use1 = topLevel1()
// CHECK-DAG: - "topLevel2"
var use2 = { topLevel2() }
// CHECK-DAG: - "topLevel3"
var use3 = { ({ topLevel3() })() }
// CHECK-DAG: - "topLevel4"
// CHECK-DAG: - "TopLevelProto1"
struct Use4 : TopLevelProto1 {
var use4 = topLevel4()
}
// CHECK-DAG: - "*"
_ = 42 * 30
// FIXME: Incorrectly marked non-private dependencies
// CHECK-DAG: - "topLevel6"
_ = topLevel6()
// CHECK-DAG: - "topLevel7"
private var use7 = topLevel7()
// CHECK-DAG: - "topLevel8"
var use8: Int = topLevel8()
// CHECK-DAG: - "topLevel9"
var use9 = { () -> Int in return topLevel9() }
// CHECK-DAG: - "TopLevelTy1"
func useTy1(_ x: TopLevelTy1) {}
// CHECK-DAG: - "TopLevelTy2"
func useTy2() -> TopLevelTy2 {}
// CHECK-DAG: - "TopLevelTy3"
// CHECK-DAG: - "TopLevelProto2"
extension Use4 : TopLevelProto2 {
var useTy3: TopLevelTy3? { return nil }
}
// CHECK-DAG: - "TopLevelStruct"
// CHECK-DAG: - "TopLevelStruct2"
let useTy4 = { (_: TopLevelStruct.ValueType) -> TopLevelStruct2.ValueType? in
return nil
}
// CHECK-DAG: - "TopLevelStruct3"
// CHECK-DAG: - "TopLevelStruct4"
typealias useTy5 = TopLevelStruct3.ValueType
let useTy6: TopLevelStruct4.ValueType = 0
struct StructForDeclaringProperties {
// CHECK-DAG: - "TopLevelStruct5"
var prop: TopLevelStruct5.ValueType { return 0 }
}
// CHECK-DAG: !private "privateTopLevel1"
func private1(_ a: Int = privateTopLevel1()) {}
// CHECK-DAG: !private "privateTopLevel2"
// CHECK-DAG: !private "PrivateProto1"
private struct Private2 : PrivateProto1 {
var private2 = privateTopLevel2()
}
// CHECK-DAG: !private "privateTopLevel3"
func outerPrivate3() {
let _ = { privateTopLevel3() }
}
// CHECK-DAG: !private "PrivateTopLevelTy1"
private extension Use4 {
var privateTy1: PrivateTopLevelTy1? { return nil }
}
// CHECK-DAG: !private "PrivateTopLevelTy2"
// CHECK-DAG: "PrivateProto2"
extension Private2 : PrivateProto2 {
// FIXME: This test is supposed to check that we get this behavior /without/
// marking the property private, just from the base type.
private var privateTy2: PrivateTopLevelTy2? { return nil }
}
// CHECK-DAG: !private "PrivateTopLevelTy3"
func outerPrivateTy3() {
func inner(_ a: PrivateTopLevelTy3?) {}
inner(nil)
}
// CHECK-DAG: !private "PrivateTopLevelStruct3"
private typealias PrivateTy4 = PrivateTopLevelStruct3.ValueType
// CHECK-DAG: !private "PrivateTopLevelStruct4"
private func privateTy5(_ x: PrivateTopLevelStruct4.ValueType) -> PrivateTopLevelStruct4.ValueType {
return x
}
// Deliberately empty.
private struct PrivateTy6 {}
// CHECK-DAG: !private "PrivateProto3"
extension PrivateTy6 : PrivateProto3 {}
// CHECK-DAG: - "ProtoReferencedOnlyInGeneric"
func genericTest<T: ProtoReferencedOnlyInGeneric>(_: T) {}
// CHECK-DAG: !private "ProtoReferencedOnlyInPrivateGeneric"
private func privateGenericTest<T: ProtoReferencedOnlyInPrivateGeneric>(_: T) {}
struct PrivateStoredProperty {
// CHECK-DAG: - "TypeReferencedOnlyByPrivateVar"
private var value: TypeReferencedOnlyByPrivateVar
}
class PrivateStoredPropertyRef {
// CHECK-DAG: - "TypeReferencedOnlyByPrivateClassVar"
private var value: TypeReferencedOnlyByPrivateClassVar?
}
struct Sentinel1 {}
private protocol ExtensionProto {}
extension OtherFileTypeToBeExtended : ExtensionProto {
private func foo() {}
}
private extension OtherFileTypeToBeExtended {
var bar: Bool { return false }
}
struct Sentinel2 {}
// CHECK-LABEL: {{^depends-member:$}}
// CHECK-DAG: - ["V4main10IntWrapper", "Int"]
// CHECK-DAG: - ["V4main10IntWrapper", "deinit"]
// CHECK-DAG: - ["Ps10Comparable", ""]
// CHECK-DAG: - ["C4main18ClassFromOtherFile", ""]
// CHECK-DAG: - !private ["Si", "max"]
// CHECK-DAG: - ["Ps25ExpressibleByFloatLiteral", ""]
// CHECK-DAG: - !private ["Ps33ExpressibleByUnicodeScalarLiteral", ""]
// CHECK-DAG: - !private ["Ps10Strideable", "Stride"]
// CHECK-DAG: - !private ["Sa", "reduce"]
// CHECK-DAG: - !private ["Sb", "_getBuiltinLogicValue"]
// CHECK-DAG: - ["Sb", "InnerToBool"]
// CHECK-DAG: - !private ["V4main17OtherFileIntArray", "deinit"]
// CHECK-DAG: - !private ["V4main18OtherFileOuterType", "InnerType"]
// CHECK-DAG: - !private ["VV4main18OtherFileOuterType9InnerType", "init"]
// CHECK-DAG: - !private ["VV4main18OtherFileOuterType9InnerType", "sharedConstant"]
// CHECK-DAG: - !private ["VV4main26OtherFileSecretTypeWrapper10SecretType", "constant"]
// CHECK-DAG: - !private ["V4main25OtherFileProtoImplementor", "deinit"]
// CHECK-DAG: - !private ["V4main26OtherFileProtoImplementor2", "deinit"]
// CHECK-DAG: - !private ["Vs13EmptyIterator", "init"]
// CHECK-DAG: - ["O4main13OtherFileEnum", "Value"]
// CHECK-DAG: - !private ["V4main20OtherFileEnumWrapper", "Enum"]
// CHECK-DAG: - ["V4main14TopLevelStruct", "ValueType"]
// CHECK-DAG: - ["V4main15TopLevelStruct2", "ValueType"]
// CHECK-DAG: - ["V4main15TopLevelStruct3", "ValueType"]
// CHECK-DAG: - ["V4main15TopLevelStruct4", "ValueType"]
// CHECK-DAG: - ["V4main15TopLevelStruct5", "ValueType"]
// CHECK-DAG: - !private ["V4main21PrivateTopLevelStruct", "ValueType"]
// CHECK-DAG: - !private ["V4main22PrivateTopLevelStruct2", "ValueType"]
// CHECK-DAG: - !private ["V4main22PrivateTopLevelStruct3", "ValueType"]
// CHECK-DAG: - !private ["V4main22PrivateTopLevelStruct4", "ValueType"]
// CHECK-DAG: - ["P4main14TopLevelProto1", ""]
// CHECK-DAG: - ["P4main14TopLevelProto2", ""]
// CHECK-DAG: - !private ["P4main13PrivateProto1", ""]
// CHECK-DAG: - !private ["P4main13PrivateProto2", ""]
// CHECK-DAG: - !private ["P4main13PrivateProto3", ""]
// CHECK-LABEL: {{^depends-nominal:$}}
// CHECK-DAG: - "V4main10IntWrapper"
// CHECK-DAG: - "Ps10Comparable"
// CHECK-DAG: - "C4main18ClassFromOtherFile"
// CHECK-DAG: !private "Si"
// CHECK-DAG: - "Ps25ExpressibleByFloatLiteral"
// CHECK-DAG: !private "Ps33ExpressibleByUnicodeScalarLiteral"
// CHECK-DAG: !private "Ps10Strideable"
// CHECK-DAG: !private "Sa"
// CHECK-DAG: - "Sb"
// CHECK-DAG: !private "V4main17OtherFileIntArray"
// CHECK-DAG: !private "V4main18OtherFileOuterType"
// CHECK-DAG: !private "VV4main18OtherFileOuterType9InnerType"
// CHECK-DAG: !private "VV4main26OtherFileSecretTypeWrapper10SecretType"
// CHECK-DAG: !private "V4main25OtherFileProtoImplementor"
// CHECK-DAG: !private "V4main26OtherFileProtoImplementor2"
// CHECK-DAG: !private "Vs13EmptyIterator"
// CHECK-DAG: - "O4main13OtherFileEnum"
// CHECK-DAG: !private "V4main20OtherFileEnumWrapper"
// CHECK-DAG: !private "V4main20OtherFileEnumWrapper"
// CHECK-DAG: !private "V4main20OtherFileEnumWrapper"
// CHECK-DAG: - "V4main23TopLevelForMemberLookup"
// CHECK-DAG: - "V4main14TopLevelStruct"
// CHECK-DAG: - "V4main15TopLevelStruct2"
// CHECK-DAG: - "V4main15TopLevelStruct3"
// CHECK-DAG: - "V4main15TopLevelStruct4"
// CHECK-DAG: - "V4main15TopLevelStruct5"
// CHECK-DAG: !private "V4main21PrivateTopLevelStruct"
// CHECK-DAG: !private "V4main22PrivateTopLevelStruct2"
// CHECK-DAG: !private "V4main22PrivateTopLevelStruct3"
// CHECK-DAG: !private "V4main22PrivateTopLevelStruct4"
// CHECK-DAG: - "P4main14TopLevelProto1"
// CHECK-DAG: - "P4main14TopLevelProto2"
// CHECK-DAG: !private "P4main13PrivateProto1"
// CHECK-DAG: !private "P4main13PrivateProto2"
// CHECK-DAG: !private "P4main13PrivateProto3"
// String is not used anywhere in this file, though a string literal is.
// NEGATIVE-NOT: "String"
// These are used by the other file in this module, but not by this one.
// NEGATIVE-NOT: "ExpressibleByFloatLiteral"
// NEGATIVE-NOT: "Int16"
// NEGATIVE-NOT: "OtherFileProto"
// NEGATIVE-NOT: "OtherFileProtoImplementor"
// NEGATIVE-NOT: "OtherFileProto2"
// NEGATIVE-NOT: "OtherFileProtoImplementor2"
// OtherFileSecretTypeWrapper is never used directly in this file.
// NEGATIVE-NOT: "OtherFileSecretTypeWrapper"
// NEGATIVE-NOT: "V4main26OtherFileSecretTypeWrapper"
let eof: () = ()
|
apache-2.0
|
b7f4bf9d6d794ac04dbdf0a0e2fe83e7
| 29.632114 | 162 | 0.699091 | 3.349856 | false | false | false | false |
J3D1-WARR10R/WikiRaces
|
WKRKit/WKRKit/Other/WKRDurationFormatter.swift
|
2
|
1039
|
//
// WKRDurationFormatter.swift
// WikiRaces
//
// Created by Andrew Finke on 8/5/17.
// Copyright © 2017 Andrew Finke. All rights reserved.
//
import Foundation
public struct WKRDurationFormatter {
private static let maxSeconds: Int = 360
public static func string(for duration: Int?, extended: Bool = false) -> String? {
guard let duration = duration else { return nil }
if duration > maxSeconds {
let suffix = extended ? " Min" : " M"
let time = duration / 60
return time.description + suffix
} else {
let suffix = extended ? " Sec" : " S"
return duration.description + suffix
}
}
public static func resultsString(for duration: Int?) -> String? {
guard let duration = duration else { return nil }
let minutes = duration / 60
let seconds = duration % 60
let secondsString = (seconds < 10 ? "0" : "") + seconds.description
return minutes.description + ":" + secondsString
}
}
|
mit
|
95502a989548595c7b6293c5d26a6a14
| 30.454545 | 86 | 0.602119 | 4.417021 | false | false | false | false |
adamshin/SwiftReorder
|
Source/ReorderController.swift
|
1
|
12697
|
//
// Copyright (c) 2016 Adam Shin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
/**
The style of the reorder spacer cell. Determines whether the cell separator line is visible.
- Automatic: The style is determined based on the table view's style (plain or grouped).
- Hidden: The spacer cell is hidden, and the separator line is not visible.
- Transparent: The spacer cell is given a transparent background color, and the separator line is visible.
*/
public enum ReorderSpacerCellStyle {
case automatic
case hidden
case transparent
}
// MARK: - TableViewReorderDelegate
/**
The delegate of a `ReorderController` must adopt the `TableViewReorderDelegate` protocol. This protocol defines methods for handling the reordering of rows.
*/
public protocol TableViewReorderDelegate: class {
/**
Tells the delegate that the user has moved a row from one location to another. Use this method to update your data source.
- Parameter tableView: The table view requesting this action.
- Parameter sourceIndexPath: The index path of the row to be moved.
- Parameter destinationIndexPath: The index path of the row's new location.
*/
func tableView(_ tableView: UITableView, reorderRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
/**
Asks the reorder delegate whether a given row can be moved.
- Parameter tableView: The table view requesting this information.
- Parameter indexPath: The index path of a row.
*/
func tableView(_ tableView: UITableView, canReorderRowAt indexPath: IndexPath) -> Bool
/**
When attempting to move a row from a sourceIndexPath to a proposedDestinationIndexPath, asks the reorder delegate what the actual targetIndexPath should be. This allows the reorder delegate to selectively allow or modify reordering between sections or groups of rows, for example.
- Parameter tableView: The table view requesting this information.
- Parameter sourceIndexPath: The original index path of the row to be moved.
- Parameter proposedDestinationIndexPath: The potential index path of the row's new location.
*/
func tableView(_ tableView: UITableView, targetIndexPathForReorderFromRowAt sourceIndexPath: IndexPath, to proposedDestinationIndexPath: IndexPath) -> IndexPath
/**
Tells the delegate that the user has begun reordering a row.
- Parameter tableView: The table view providing this information.
- Parameter indexPath: The index path of the selected row.
*/
func tableViewDidBeginReordering(_ tableView: UITableView, at indexPath: IndexPath)
/**
Tells the delegate that the user has finished reordering.
- Parameter tableView: The table view providing this information.
- Parameter initialSourceIndexPath: The initial index path of the selected row, before reordering began.
- Parameter finalDestinationIndexPath: The final index path of the selected row.
*/
func tableViewDidFinishReordering(_ tableView: UITableView, from initialSourceIndexPath: IndexPath, to finalDestinationIndexPath: IndexPath)
}
public extension TableViewReorderDelegate {
func tableView(_ tableView: UITableView, canReorderRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, targetIndexPathForReorderFromRowAt sourceIndexPath: IndexPath, to proposedDestinationIndexPath: IndexPath) -> IndexPath {
return proposedDestinationIndexPath
}
func tableViewDidBeginReordering(_ tableView: UITableView, at indexPath: IndexPath) {
}
func tableViewDidFinishReordering(_ tableView: UITableView, from initialSourceIndexPath: IndexPath, to finalDestinationIndexPath:IndexPath) {
}
}
// MARK: - ReorderController
/**
An object that manages drag-and-drop reordering of table view cells.
*/
public class ReorderController: NSObject {
// MARK: - Public interface
/// The delegate of the reorder controller.
public weak var delegate: TableViewReorderDelegate?
/// Whether reordering is enabled.
public var isEnabled: Bool = true {
didSet { reorderGestureRecognizer.isEnabled = isEnabled }
}
public var longPressDuration: TimeInterval = 0.3 {
didSet {
reorderGestureRecognizer.minimumPressDuration = longPressDuration
}
}
public var cancelsTouchesInView: Bool = false {
didSet {
reorderGestureRecognizer.cancelsTouchesInView = cancelsTouchesInView
}
}
/// The duration of the cell selection animation.
public var animationDuration: TimeInterval = 0.2
/// The opacity of the selected cell.
public var cellOpacity: CGFloat = 1
/// The scale factor for the selected cell.
public var cellScale: CGFloat = 1
/// The shadow color for the selected cell.
public var shadowColor: UIColor = .black
/// The shadow opacity for the selected cell.
public var shadowOpacity: CGFloat = 0.3
/// The shadow radius for the selected cell.
public var shadowRadius: CGFloat = 10
/// The shadow offset for the selected cell.
public var shadowOffset = CGSize(width: 0, height: 3)
/// The spacer cell style.
public var spacerCellStyle: ReorderSpacerCellStyle = .automatic
/// Whether or not autoscrolling is enabled
public var autoScrollEnabled = true
/**
Returns a `UITableViewCell` if the table view should display a spacer cell at the given index path.
Call this method at the beginning of your `tableView(_:cellForRowAt:)`, like so:
```
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let spacer = tableView.reorder.spacerCell(for: indexPath) {
return spacer
}
// ...
}
```
- Parameter indexPath: The index path
- Returns: An optional `UITableViewCell`.
*/
public func spacerCell(for indexPath: IndexPath) -> UITableViewCell? {
if case let .reordering(context) = reorderState, indexPath == context.destinationRow {
return createSpacerCell()
} else if case let .ready(snapshotRow) = reorderState, indexPath == snapshotRow {
return createSpacerCell()
}
return nil
}
// MARK: - Internal state
struct ReorderContext {
var sourceRow: IndexPath
var destinationRow: IndexPath
var snapshotOffset: CGFloat
var touchPosition: CGPoint
}
enum ReorderState {
case ready(snapshotRow: IndexPath?)
case reordering(context: ReorderContext)
}
weak var tableView: UITableView?
var reorderState: ReorderState = .ready(snapshotRow: nil)
var snapshotView: UIView? = nil
var autoScrollDisplayLink: CADisplayLink?
var lastAutoScrollTimeStamp: CFTimeInterval?
lazy var reorderGestureRecognizer: UILongPressGestureRecognizer = {
let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleReorderGesture))
gestureRecognizer.delegate = self
gestureRecognizer.minimumPressDuration = self.longPressDuration
return gestureRecognizer
}()
// MARK: - Lifecycle
init(tableView: UITableView) {
super.init()
self.tableView = tableView
tableView.addGestureRecognizer(reorderGestureRecognizer)
reorderState = .ready(snapshotRow: nil)
}
// MARK: - Reordering
func beginReorder(touchPosition: CGPoint) {
guard case .ready = reorderState,
let delegate = delegate,
let tableView = tableView,
let superview = tableView.superview
else { return }
let tableTouchPosition = superview.convert(touchPosition, to: tableView)
guard let sourceRow = tableView.indexPathForRow(at: tableTouchPosition),
delegate.tableView(tableView, canReorderRowAt: sourceRow)
else { return }
createSnapshotViewForCell(at: sourceRow)
animateSnapshotViewIn()
activateAutoScrollDisplayLink()
tableView.reloadData()
let snapshotOffset = (snapshotView?.center.y ?? 0) - touchPosition.y
let context = ReorderContext(
sourceRow: sourceRow,
destinationRow: sourceRow,
snapshotOffset: snapshotOffset,
touchPosition: touchPosition
)
reorderState = .reordering(context: context)
delegate.tableViewDidBeginReordering(tableView, at: sourceRow)
}
func updateReorder(touchPosition: CGPoint) {
guard case .reordering(let context) = reorderState else { return }
var newContext = context
newContext.touchPosition = touchPosition
reorderState = .reordering(context: newContext)
updateSnapshotViewPosition()
updateDestinationRow()
}
func endReorder() {
guard case .reordering(let context) = reorderState,
let tableView = tableView,
let superview = tableView.superview
else { return }
reorderState = .ready(snapshotRow: context.destinationRow)
let cellRectInTableView = tableView.rectForRow(at: context.destinationRow)
let cellRect = tableView.convert(cellRectInTableView, to: superview)
let cellRectCenter = CGPoint(x: cellRect.midX, y: cellRect.midY)
// If no values change inside a UIView animation block, the completion handler is called immediately.
// This is a workaround for that case.
if snapshotView?.center == cellRectCenter {
snapshotView?.center.y += 0.1
}
UIView.animate(withDuration: animationDuration,
animations: {
self.snapshotView?.center = CGPoint(x: cellRect.midX, y: cellRect.midY)
},
completion: { _ in
if case let .ready(snapshotRow) = self.reorderState, let row = snapshotRow {
self.reorderState = .ready(snapshotRow: nil)
UIView.performWithoutAnimation {
tableView.reloadRows(at: [row], with: .none)
}
self.removeSnapshotView()
}
}
)
animateSnapshotViewOut()
clearAutoScrollDisplayLink()
delegate?.tableViewDidFinishReordering(tableView, from: context.sourceRow, to: context.destinationRow)
}
// MARK: - Spacer cell
private func createSpacerCell() -> UITableViewCell? {
guard let snapshotView = snapshotView else { return nil }
let cell = UITableViewCell()
let height = snapshotView.bounds.height
NSLayoutConstraint(
item: cell,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 0,
constant: height
).isActive = true
let hideCell: Bool
switch spacerCellStyle {
case .automatic: hideCell = tableView?.style == .grouped
case .hidden: hideCell = true
case .transparent: hideCell = false
}
if hideCell {
cell.isHidden = true
} else {
cell.backgroundColor = .clear
}
return cell
}
}
|
mit
|
b8f0d31bf5775defeb1a1a87f4f84e4c
| 36.234604 | 285 | 0.667638 | 5.370981 | false | false | false | false |
alloyapple/Goose
|
Sources/Goose/Requests.swift
|
1
|
15232
|
//
// Created by color on 17-9-26.
//
import Foundation
import CCurl
let progressHandler: @convention(c) (UnsafeMutableRawPointer?, Double, Double, Double, Double) -> Int32 = { (userData, t, d, ultotal, ulnow) in
if let userData = userData {
let request: Request = userData.unretainedValue()
request.progressClosure?(d * 100.0 / t)
}
return 0
}
let writeHandler: @convention(c) (UnsafeMutablePointer<Int8>?, Int, Int, UnsafeMutableRawPointer?) -> Int = { (contents, size, nmemb, userData) in
if let userData = userData, let contents = contents {
let request: Request = userData.unretainedValue()
request.writeData(Data(bytes: contents, count: size * nmemb))
}
return size * nmemb
}
let readHandler: @convention(c) (UnsafeMutablePointer<Int8>?, Int, Int, UnsafeMutableRawPointer?) -> Int = { (dest, size, nmemb, userData) in
if let userData = userData, let dest = dest {
let request: Request = userData.unretainedValue()
let data = request.readUpLoadData(size * nmemb)
if let data = data {
data.withUnsafeBytes({ (p: UnsafePointer<UInt8>) -> Void in
memcpy(dest, p, data.count)
})
}
return data?.count ?? 0
}
return 0
}
let headerHandler: @convention(c) (UnsafeMutablePointer<Int8>?, Int, Int, UnsafeMutableRawPointer?) -> Int = { (contents, size, nmemb, userData) in
if let userData = userData, let contents = contents {
let request: Request = userData.unretainedValue()
request.writeHeader(Data(bytes: contents, count: size * nmemb))
}
return size * nmemb
}
let codes = [
//Informational
100: "continue",
101: "switching_protocols",
102: "processing",
103: "checkpoint",
122: "request_uri_too_long",
200: "okay",
201: "created",
202: "accepted",
203: "non_authoritative_information",
204: "no_content",
205: "reset_content",
206: "partial_content",
207: "multi_status",
208: "already_reported",
226: "im_used",
]
public typealias ProgressClosure = (Double) -> Void
public enum CurlError: Error {
case NetError(UInt32, String)
}
enum FormData {
case Text(String)
case File(String)
}
public class Response {
let request: Request
public let statusCode: Int
public var curlCode: UInt32 = 0
public let data: Data?
internal init(request: Request, statusCode: Int, data: Data?) {
self.request = request
self.statusCode = statusCode
self.data = data
}
public var headers: [String: String] {
guard let data = self.request.headerData else {
return [:]
}
guard let ret = String(data: data, encoding: .utf8) else {
return [:]
}
var strArray = ret.split(with: "\r\n")
strArray.removeFirst()
strArray.removeLast(2)
var headerDic: [String: String] = [:]
for str in strArray {
let a = str.split(with: ":")
headerDic[a[0]] = a[1].strip()
}
return headerDic
}
public var text: String {
guard let data = self.request.data else {
return ""
}
guard let ret = String(data: data, encoding: .utf8) else {
return ""
}
return ret
}
public func jsonObject<T: Decodable>() -> T? {
let decoder = JSONDecoder()
let parsedData = try! decoder.decode(T.self, from: self.data!)
return parsedData
}
public func jsonObject<T: Decodable>() -> [T]? {
let decoder = JSONDecoder()
let parsedData = try! decoder.decode([T].self, from: self.data!)
return parsedData
}
public var ok: Bool {
return true
}
public var redirect: Bool {
return true
}
public var permanentRedirect: Bool {
return true
}
}
public enum HTTPMethod {
case GET
case POST
case PUT
case DELETE
case HEAD
internal var methodStr: String {
switch self {
case .DELETE:
return "DELETE"
case .GET:
return "GET"
case .HEAD:
return "HEAD"
case .POST:
return "POST"
case .PUT:
return "PUT"
}
}
}
func param(_ p: [String: CustomStringConvertible]) -> String {
guard p.count > 0 else {
return ""
}
var pArray: [String] = []
for (key, value) in p {
pArray.append("\(key)=\(value)")
}
return "&".join(pArray)
}
public class Session {
private let cookieName: String
public init() {
self.cookieName = (OS.getcwd() ?? "") + "/." + ProcessInfo.processInfo.globallyUniqueString + ".cookie"
}
// public func get(url: String, params: [String: CustomStringConvertible] = [:], headers: [String: CustomStringConvertible] = [:]) -> Request {
// let r = Request.get(url: url, params: params, headers: headers)
// r.buildCookie(cookieFile: self.cookieName)
// return r
// }
deinit {
_ = OS.remove(path: self.cookieName)
}
}
public protocol PostBody {
func putData(request: Request)
}
public class FormBody: PostBody {
private var data: [String: FormData] = [:]
public func add(key: String, value: String) {
self.data[key] = .Text(value)
}
public func add(key: String, file: String) {
self.data[key] = .File(file)
}
public func putData(request: Request) {
let mime = curl_mime_init(request.handle)
for (k, v) in data {
let part = curl_mime_addpart(mime)
switch v {
case .Text(let str):
curl_mime_name(part, k)
curl_mime_data(part, str, CURL_ZERO_TERMINATED)
case .File(let file):
curl_mime_name(part, k)
curl_mime_filedata(part, file)
}
}
curl_easy_setopt(request.handle, CURLOPT_MIMEPOST, mime)
}
}
public class UrlEncodeBody: PostBody {
var data: [String: String] = [:]
public func add(key: String, value: String) {
self.data[key] = value
}
public func putData(request: Request) {
request.addHeader(key: "Content-Type", value: "application/x-www-form-urlencoded")
let form = curl_mime_init(request.handle)
for (k, v) in data {
let part = curl_mime_addpart(form)
curl_mime_data(part, v, CURL_ZERO_TERMINATED)
curl_mime_name(part, k)
}
curl_easy_setopt(request.handle, CURLOPT_MIMEPOST, form)
}
}
public enum TextType {
case Text
case Json
case Js
case XML
case XMLText
case HTML
internal var header: String {
switch self {
case .Text:
return "text/plain"
case .Json:
return "application/json"
case .Js:
return "application/javascript"
case .XML:
return "application/xml"
case .XMLText:
return "text/xml"
case .HTML:
return "text/html"
}
}
}
public class RawBody: PostBody {
var text: UnsafeMutablePointer<Int8>? = nil
var textType: TextType = .Text
public func add(value: String, type: TextType) {
self.text = strdup(value)
self.textType = type
}
public func add(value: Data, type: TextType) {
self.text = strdup(String(data: value, encoding: .utf8)!)
self.textType = type
}
public func putData(request: Request) {
request.addHeader(key: "Content-Type", value: self.textType.header)
curl_easy_setopt(request.handle, CURLOPT_POSTFIELDSIZE, -1)
curl_easy_setopt(request.handle, CURLOPT_POSTFIELDS, self.text)
}
deinit {
free(self.text)
}
}
public class BinaryBody: PostBody {
var fileName: String = ""
//TODO: fix me
public func putData(request: Request) {
}
}
let defaultHeaders: [String: String] = [
"User-Agent": "Goose/\(GooseVersion()) \(OS.uname().sysname)/\(OS.uname().release)",
"Accept-Encoding": "gzip, deflate",
"Accept": "*/*",
"Connection": "keep-alive"
]
public class Request {
public let method: HTTPMethod
public let url: String
fileprivate var handle: CURL
internal var data: Data? = nil
internal var uploadData: Data? = nil
internal var headerData: Data?
internal var textString: UnsafeMutablePointer<Int8>? = nil
internal var progressClosure: ProgressClosure?
internal var _headers: [String: String] = defaultHeaders
internal var query: [String: String] = [:]
internal var cookies: [String: String] = [:]
var header_list: UnsafeMutablePointer<curl_slist>? = nil
internal init(method: HTTPMethod, url: String) {
self.method = method
self.url = url
curl_global_init()
handle = curl_easy_init()
curl_easy_setopt(handle, CURLOPT_URL, url)
curl_easy_setopt(handle, CURLOPT_ACCEPT_ENCODING, "")
curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1)
curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1)
curl_easy_setopt_wr_callback(handle, CURLOPT_WRITEFUNCTION, writeHandler)
curl_easy_setopt(handle, CURLOPT_WRITEDATA, Unmanaged.passUnretained(self).toOpaque());
curl_easy_setopt_wr_callback(handle, CURLOPT_HEADERFUNCTION, headerHandler)
curl_easy_setopt(handle, CURLOPT_HEADERDATA, Unmanaged.passUnretained(self).toOpaque());
}
private func prepareHeaders() {
self._headers.forEach { (item) in
self.header_list = curl_slist_append(header_list, "\(item.key):\(item.value)");
}
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, self.header_list)
}
private func prepareMethod() {
if method == .POST {
curl_easy_setopt(handle, CURLOPT_POST, 1)
curl_easy_setopt_rd_callback(handle, CURLOPT_READFUNCTION, readHandler)
curl_easy_setopt(handle, CURLOPT_READDATA, Unmanaged.passUnretained(self).toOpaque())
} else {
curl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, method.methodStr)
}
}
private func prepareQuery() {
var queryString = ""
var strArray: [String] = []
for (k, v) in self.query {
var ks = ""
var vs = ""
if let kp = curl_easy_escape(self.handle, k, Int32(k.count)) {
ks = String(cString: kp)
}
if let vp = curl_easy_escape(self.handle, v, Int32(v.count)) {
vs = String(cString: vp)
}
strArray.append("\(ks)=\(vs)")
}
if strArray.count > 0 {
let query = strArray.joined(separator: "&")
let url = self.url + "?" + query
curl_easy_setopt(handle, CURLOPT_URL, url)
}
}
fileprivate func buildCookie(cookieFile: String) {
curl_easy_setopt(handle, CURLOPT_COOKIEJAR, cookieFile)
curl_easy_setopt(handle, CURLOPT_COOKIEFILE, cookieFile)
}
public static func get(url: String) -> Request {
return Request(method: .GET, url: url)
}
public static func post(url: String) -> Request {
return Request(method: .POST, url: url)
}
//put method
public static func put(url: String) -> Request {
return Request(method: .POST, url: url)
}
//put method
public static func delete(url: String) -> Request {
return Request(method: .POST, url: url)
}
public static func head(url: String) -> Request {
return Request(method: .HEAD, url: url)
}
public static func download(url: String) -> Request {
return Request(method: .GET, url: url)
}
//https://curl.haxx.se/libcurl/c/fileupload.html
public static func upload(url: String) -> Request {
return Request(method: .POST, url: url)
}
public func setTextString(_ json: Data) {
self.textString = strdup(String(data: json, encoding: .utf8)!)
curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE, -1)
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, self.textString!)
}
public func progress(closure: @escaping (Double) -> Void) -> Request {
self.progressClosure = closure
return self
}
internal func writeData(_ data: Data) {
if self.data == nil {
self.data = data
} else {
self.data?.append(data)
}
}
internal func writeHeader(_ data: Data) {
if self.headerData == nil {
self.headerData = data
} else {
self.headerData?.append(data)
}
}
internal func readUpLoadData(_ size: Int) -> Data? {
guard let data = self.uploadData else {
return nil
}
if data.count > size {
let subData = data[..<size]
self.uploadData = self.uploadData?.dropFirst(size)
return subData
} else {
let subData = data
self.uploadData = self.uploadData?.dropFirst(size)
return subData
}
}
public func recv(closure: @escaping (Data) -> Void) -> Request {
return self
}
public func error() -> Request {
return self
}
public func post(body: PostBody) {
body.putData(request: self)
}
public func addQuery(key: String, value: String) {
self.query[key] = value
}
public func addCookie(key: String, value: String) {
self.cookies[key] = value
}
public func removeCookie(key: String) {
self.cookies.removeValue(forKey: key)
}
public var cookie: [String: String] {
return [:]
}
public func addHeader(key: String, value: String) {
self._headers[key] = value
}
public func setAuth(user: String, password: String) {
curl_easy_setopt(self.handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY_VALUE())
curl_easy_setopt(self.handle, CURLOPT_USERPWD, "\(user):\(password)")
}
public func removeHeader(key: String) {
self._headers.removeValue(forKey: key)
}
public var headers: [String: String] {
return self._headers
}
public func execute() -> Response {
if Request.debug {
curl_easy_setopt(handle, CURLOPT_VERBOSE, 1)
}
self.prepareQuery()
self.prepareHeaders()
self.prepareMethod()
let res = curl_easy_perform(handle)
if res == CURLE_OK {
var statusCode: Int = 0
curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &statusCode)
return Response(request: self, statusCode: statusCode, data: Data())
} else {
let r = Response(request: self, statusCode: -1, data: Data())
r.curlCode = res.rawValue
return r
}
return Response(request: self, statusCode: 0, data: nil)
}
deinit {
print("curl clear \(self.url)")
free(textString)
curl_easy_cleanup(handle)
curl_slist_free_all(self.header_list)
}
public static var debug = false
}
|
bsd-3-clause
|
46a15fd6d405cb42ff9130fa15a79ede
| 24.72973 | 147 | 0.584034 | 3.873856 | false | false | false | false |
cubixlabs/SocialGIST
|
Pods/GISTFramework/GISTFramework/Classes/BaseClasses/BaseUITableView.swift
|
1
|
1645
|
//
// BaseTableView.swift
// GISTFramework
//
// Created by Shoaib Abdul on 14/06/2016.
// Copyright © 2016 Social Cubix. All rights reserved.
//
import UIKit
/// BaseUITableView is a subclass of UITableView and implements BaseView. It has some extra proporties and support for SyncEngine.
open class BaseUITableView: UITableView, BaseView {
//MARK: - Properties
/// Flag for whether to resize the values for iPad.
@IBInspectable open var sizeForIPad:Bool = GIST_CONFIG.sizeForIPad;
/// Background color key from Sync Engine.
@IBInspectable open var bgColorStyle:String? = nil {
didSet {
self.backgroundColor = SyncedColors.color(forKey: bgColorStyle);
}
}
@IBInspectable open var tintColorStyle:String? = nil {
didSet {
self.tintColor = SyncedColors.color(forKey: tintColorStyle);
}
}
//MARK: - Overridden Methods
/// Overridden method to setup/ initialize components.
override open func awakeFromNib() {
super.awakeFromNib()
} //F.E.
/// Overridden methed to update layout.
override open func layoutSubviews() {
super.layoutSubviews();
} //F.E.
//MARK: - Methods
/// Updates layout and contents from SyncEngine. this is a protocol method BaseView that is called when the view is refreshed.
func updateView(){
if let tintCStyle = tintColorStyle {
self.tintColorStyle = tintCStyle;
}
if let bgCStyle = self.bgColorStyle {
self.bgColorStyle = bgCStyle;
}
} //F.E.
} //CLS END
|
gpl-3.0
|
783f56a6b50a8e3fa18ea1e425fdacb7
| 27.842105 | 130 | 0.631995 | 4.670455 | false | false | false | false |
brunodlz/Couch
|
Couch/Couch/View/Show/Profile/ProfileView.swift
|
1
|
4136
|
import UIKit
import SnapKit
import AlamofireImage
final class ProfileView: UIView {
func setup(_ profile: Profile) {
usernameLabel.text = profile.name
avatarImage.af_setImage(withURL: URL(string: profile.avatar!)!)
let date = Date().convertString(To: profile.joined_at, mask: .day)
memberSinceLabel.text = "Member since: \(date)"
aboutLabel.text = profile.about
locationLabel.text = profile.location
ageLabel.text = "\(profile.age!) years old"
}
let containerView: UIView = {
let view = UIView(frame: .zero)
view.backgroundColor = .clear
view.layer.cornerRadius = 8
view.layer.borderColor = ColorPalette.white.cgColor
view.layer.borderWidth = 1.0
return view
}()
let usernameLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.textColor = ColorPalette.white
label.font = UIFont.systemFont(ofSize: 22, weight: UIFontWeightMedium)
return label
}()
let avatarImage: UIImageView = {
let image = UIImageView(frame: .zero)
return image
}()
let memberSinceLabel: Label = {
let label = Label()
return label
}()
let aboutLabel: Label = {
let label = Label()
return label
}()
let locationLabel: Label = {
let label = Label()
return label
}()
let ageLabel: Label = {
let label = Label()
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupViewConfiguration()
}
required init?(coder aDecoder: NSCoder) {
fatalError("storyboard ugh :P")
}
}
extension ProfileView: ViewConfiguration {
func setupConstraints() {
containerView.snp.makeConstraints { (make) in
make.top.equalTo(self).offset(8)
make.left.equalTo(self).offset(8)
make.right.equalTo(self).offset(-8)
make.bottom.equalTo(self).offset(-8)
}
usernameLabel.snp.makeConstraints { (make) in
make.top.equalTo(containerView.snp.top).offset(20)
make.left.equalTo(self)
make.right.equalTo(self)
make.height.equalTo(22)
}
avatarImage.snp.makeConstraints { (make) in
make.top.equalTo(usernameLabel.snp.bottom).offset(8)
make.centerX.equalTo(self)
make.width.equalTo(120)
make.height.equalTo(120)
}
memberSinceLabel.snp.makeConstraints { (make) in
make.top.equalTo(avatarImage.snp.bottom).offset(8)
make.left.equalTo(self).offset(32)
make.right.equalTo(self).offset(-32)
}
aboutLabel.snp.makeConstraints { (make) in
make.top.equalTo(memberSinceLabel.snp.bottom).offset(8)
make.left.equalTo(self).offset(32)
make.right.equalTo(self).offset(-32)
}
locationLabel.snp.makeConstraints { (make) in
make.top.equalTo(aboutLabel.snp.bottom).offset(8)
make.left.equalTo(self).offset(32)
make.right.equalTo(self).offset(-32)
}
ageLabel.snp.makeConstraints { (make) in
make.top.equalTo(locationLabel.snp.bottom).offset(8)
make.left.equalTo(self).offset(32)
make.right.equalTo(self).offset(-32)
}
}
func buildViewHierarchy() {
containerView.addSubview(usernameLabel)
containerView.addSubview(avatarImage)
containerView.addSubview(memberSinceLabel)
containerView.addSubview(aboutLabel)
containerView.addSubview(locationLabel)
containerView.addSubview(ageLabel)
self.addSubview(containerView)
}
func configureViews() {
avatarImage.clipsToBounds = true
avatarImage.layer.cornerRadius = 60
avatarImage.layer.borderWidth = 2
avatarImage.layer.borderColor = ColorPalette.white.cgColor
}
}
|
mit
|
95b06545104b8249c496b09624ee8a37
| 29.637037 | 78 | 0.593327 | 4.550055 | false | false | false | false |
neonichu/jarvis
|
Sources/GitHub.swift
|
1
|
903
|
import Chores
import Foundation
// FIXME: C&P from Chocolat
extension String {
func components(separator: Character = "\n") -> [String] {
return self.characters.split(separator).map(String.init)
}
var lines: [String] {
return components("\n")
}
}
func github_data_from_remote(remote: String) -> (String, String)? {
if remote.rangeOfString("[email protected]") != nil {
if let meat = remote.components(":").last?.components(".").first?.components("/") {
return (meat[0], meat[1])
}
} else {
if let url = NSURL(string: remote), components = url.pathComponents {
return (components[components.count-2], components[components.count-1])
}
}
return nil
}
func github_data_from_git() -> (String, String)? {
if let remote = (>["git", "remote", "-v"]).stdout.lines.first,
data = github_data_from_remote(remote) {
return data
}
return nil
}
|
mit
|
f9be820015507aac86ee1c2002dca4bf
| 23.405405 | 87 | 0.636766 | 3.513619 | false | false | false | false |
VinlorJiang/DouYuWL
|
DouYuWL/DouYuWL/Classes/Tools/Extension/UIBarButtonItem-Extention.swift
|
1
|
1476
|
//
// UIBarButtonItem-Extention.swift
// DouYuWL
//
// Created by dinpay on 2017/7/19.
// Copyright © 2017年 apple. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
// 1.第一种方法 类方法
/*
class func createItem(imageName : String, highlightedImageName : String = "", size : CGSize = CGSize.zero) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named : imageName), for: .normal)
btn.setImage(UIImage(named : highlightedImageName), for: .highlighted)
btn.frame = CGRect(origin: CGPoint.zero, size: size)
return UIBarButtonItem(customView: btn)
}
*/
// 便利构造函数: 1> convenience开头 2> 在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imageName : String, highlightedImageName : String = "", size : CGSize = CGSize.zero) {
// 1.创建 btn
let btn = UIButton()
// 2.设置 btn 的图片
btn.setImage(UIImage(named : imageName), for: .normal)
if highlightedImageName != "" {
btn.setImage(UIImage(named: highlightedImageName), for: .highlighted)
}
// 3.设置 btn 的尺寸
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
self.init(customView : btn)
}
}
|
mit
|
5f06f3b341a94287122664a21520388f
| 26.5 | 131 | 0.576 | 4.243827 | false | false | false | false |
sameertotey/LimoService
|
LimoService/PreviousLocationLookupViewController.swift
|
1
|
3935
|
//
// PreviousLocationLookupViewController.swift
// LimoService
//
// Created by Sameer Totey on 4/1/15.
// Copyright (c) 2015 Sameer Totey. All rights reserved.
//
import UIKit
class PreviousLocationLookupViewController: PFQueryTableViewController {
weak var currentUser: PFUser!
var selectedLocation: LimoUserLocation?
override init(style: UITableViewStyle, className: String!) {
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.parseClassName = "LimoUserLocation"
// self.textKey = "address"
self.pullToRefreshEnabled = true
self.objectsPerPage = 20
}
private func alert(message : String) {
let alert = UIAlertController(title: "Oops something went wrong.", message: message, preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
let settings = UIAlertAction(title: "Settings", style: UIAlertActionStyle.Default) { (action) -> Void in
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
return
}
alert.addAction(settings)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 60
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func queryForTable() -> PFQuery {
if let query = LimoUserLocation.query() {
query.whereKey("owner", equalTo: currentUser) // expect currentUser to be set here
query.orderByDescending("createdAt")
query.limit = 200;
return query
} else {
let query = PFQuery(className: "LimoUserLocation")
query.whereKey("owner", equalTo: currentUser) // expect currentUser to be set here
query.orderByDescending("createdAt")
query.limit = 200;
return query
}
}
override func objectAtIndexPath(indexPath: NSIndexPath!) -> PFObject? {
var obj : PFObject? = nil
if let allObjects = self.objects {
if indexPath.row < allObjects.count {
obj = allObjects[indexPath.row] as? PFObject
}
}
return obj
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject!) -> PFTableViewCell? {
let cell = tableView.dequeueReusableCellWithIdentifier("LocationCell", forIndexPath: indexPath) as! LocationLookupTableViewCell
cell.nameLabel.text = object.valueForKey("name") as? String
cell.addressLabel.text = object.valueForKey("address") as? String
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "return the Location"){
}
}
// MARK: - TableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let selectedObject = objectAtIndexPath(indexPath) {
if selectedObject is LimoUserLocation {
selectedLocation = (selectedObject as! LimoUserLocation)
performSegueWithIdentifier("Return Selection", sender: nil)
} else {
println("The type of the object \(selectedObject) is not LimoUserLocation it is ..")
}
}
}
}
|
mit
|
512b4175a61f38ce259df5aa20000f99
| 35.775701 | 138 | 0.640152 | 5.303235 | false | false | false | false |
ChristianKienle/Bold
|
Bold/Error.swift
|
1
|
494
|
import Foundation
public struct Error {
public enum Code : Int {
case prepareFailed
case bindFailed
case executeQueryFailed // Used when executeUpdate failed because executeQuery failed.
case stepFailed
}
public let code:Error.Code
public let message:String
public var SQLiteErrorCode:Int32? = nil
init(code:Error.Code, message:String, SQLiteErrorCode:Int32? = nil) {
self.code = code
self.message = message
self.SQLiteErrorCode = SQLiteErrorCode
}
}
|
mit
|
4a573c09b00950600386f735536bc1aa
| 26.444444 | 90 | 0.732794 | 4.295652 | false | false | false | false |
mtransitapps/mtransit-for-ios
|
MonTransit/Source/Agencies/Agency.swift
|
1
|
3036
|
//
// StmBusAgency.swift
// MonTransit
//
// Created by Thibault on 16-01-21.
// Copyright © 2016 Thibault. All rights reserved.
//
import UIKit
class Agency:NSObject {
var mDisplayIAds = true
// Agency ID
var mAgencyId:Int = 1
var mAgencyUniqueId: String = ""
// Agency Name
var mAgencyName:String = ""
// Agency Type
var mAgencyType:SQLProvider.DatabaseType = .eBus
// Zip Data
var mZipDataFile = ""
var mArchive:ZipLoader!
// Database Folder
var mMainDatabaseFolder = ""
var mFavoritesDatabaseFolder = ""
var mGtfsDatabaseFolder = ""
// Agency Database
var mMainDatabase = ""
var mFavoritesDatabase = ""
var mGtfsDatabase = ""
// DB file
var mGtfsRoute = ""
var mGtfsStop = ""
var mGtfsTrip = ""
var mGtfsTripStop = ""
var mGtfsServiceDate = ""
// Agency Default Color
var mAgencyDefaultColor = ""
// Agency file format
var mStopScheduleRaw = ""
var mStopScheduleFolder = ""
var mJsonAlertEn = ""
var mJsonAlertFr = ""
// Location
var mLatitude = 45.5088400
var mLongitude = -73.5878100
// Alert
var mAlertMessageFr = ""
var mAlertMessageEn = ""
func getAgencyId() -> Int{
return mAgencyId
}
func setZipData () {
mArchive = ZipLoader(iZipFilePath: getZipDataFile())
}
func getZipData () -> ZipLoader{
return mArchive
}
func setZipDataFile(iFile:String) {
mZipDataFile = iFile
}
func getZipDataFile () -> String {
return mZipDataFile
}
func closeZipData(){
mArchive = nil
}
func getMainDatabasePath() -> String{
return mMainDatabaseFolder + "/" + mMainDatabase
}
func getFavoritesDatabasePath() -> String {
return mFavoritesDatabaseFolder + "/" + mFavoritesDatabase
}
func getGtfsDatabasePath() -> String {
return mGtfsDatabaseFolder + "/" + mGtfsDatabase
}
func getAgencyDefaultColor () -> String {
return mAgencyDefaultColor
}
func getStopScheduleRawfileFormat () -> String {
return mStopScheduleRaw
}
func getMainFilePath() -> String {
return mStopScheduleFolder
}
func getLatitude() -> Double {
return mLatitude
}
func getLongitude() -> Double {
return mLongitude
}
func getJsonAlertPath() -> String {
let wLangId = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)!
return (wLangId as! String == "fr" ? mJsonAlertFr : mJsonAlertEn)
}
func getDefaultAlertMessage() -> String{
let wLangId = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)!
return (wLangId as! String == "fr" ? mAlertMessageFr : mAlertMessageEn)
}
}
|
apache-2.0
|
630b8ec8468f2ba3cbc94c2b41d7d60b
| 19.931034 | 82 | 0.573641 | 4.489645 | false | false | false | false |
Holmusk/HMRequestFramework-iOS
|
HMRequestFramework/database/coredata/protocol/HMCDRequestProcessorType.swift
|
1
|
8263
|
//
// HMCDRequestProcessorType.swift
// HMRequestFramework
//
// Created by Hai Pham on 7/22/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import CoreData
import RxSwift
import SwiftFP
/// Classes that implement this protocol must be able to perform CoreData
/// requests and process the result.
public protocol HMCDRequestProcessorType: HMRequestHandlerType, HMCDGeneralRequestProcessorType {
/// Perform a CoreData get request with required dependencies. This method
/// should be used for CoreData operations whose results are constrained
/// to some NSManagedObject subtype.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the operation fails.
func executeTyped<Val>(_ request: Req) throws -> Observable<Try<[Val]>>
where Val: NSFetchRequestResult
/// Perform a CoreData save request with required dependencies. This
/// method returns an Observable that emits the success/failure status of
/// each item that is saved.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
/// - Throws: Exception if the operation fails.
func executeTyped(_ request: Req) throws -> Observable<Try<[HMCDResult]>>
/// Perform a CoreData request with required dependencies.
///
/// This method should be used with operations that do not require specific
/// result type, e.g. CoreData save requests.
///
/// - Parameter request: A Req instance.
/// - Returns: An Observable instance.
func execute(_ request: Req) throws -> Observable<Try<Void>>
}
public extension HMCDRequestProcessorType {
/// Perform a CoreData typed request, which returns an Observable that emits
/// a Try containing an Array of some result, and process the result.
///
/// - Parameters:
/// - previous: The result of the upstream request.
/// - generator: A HMRequestGenerator instance.
/// - perform: A HMRequestPerformer instance.
/// - processor: A HMResultProcessor instance.
/// - qos: A QoSClass instance to perform work on.
/// - Returns: An Observable instance.
private func processArray<Prev,Val,Res>(
_ previous: Try<Prev>,
_ generator: @escaping HMRequestGenerator<Prev,Req>,
_ perform: @escaping HMRequestPerformer<Req,[Val]>,
_ processor: @escaping HMResultProcessor<Val,Res>,
_ qos: DispatchQoS.QoSClass)
-> Observable<Try<[Try<Res>]>>
{
return execute(previous, generator, perform, qos)
.map({try $0.getOrThrow()})
// We need to process the CoreData objects right within the vals Array,
// instead of using Observable.from and process each emission individually,
// because it could lead to properties being reset to nil (ARC-releated).
.flatMap({(vals: [Val]) -> Observable<[Try<Res>]> in
return Observable.just(vals)
.flatMapSequence({$0.map({(val) -> Observable<Try<Res>> in
do {
return try processor(val).subscribeOnConcurrent(qos: qos)
} catch let e {
return Observable.just(Try.failure(e))
}
})})
.flatMap({$0})
.catchErrorJustReturn(Try.failure)
.toArray()
})
.map(Try.success)
.catchErrorJustReturn(Try.failure)
}
/// Perform a CoreData get request and process the result.
///
/// - Parameters:
/// - previous: The result of the upstream request.
/// - generator: Generator function to create the current request.
/// - processor: Processor function to process the request result.
/// - qos: A QoSClass instance to perform work on.
/// - Returns: An Observable instance.
public func processTyped<Prev,Val,Res>(
_ previous: Try<Prev>,
_ generator: @escaping HMRequestGenerator<Prev,Req>,
_ processor: @escaping HMResultProcessor<Val,Res>,
_ qos: DispatchQoS.QoSClass)
-> Observable<Try<[Try<Res>]>> where Val: NSFetchRequestResult
{
return processArray(previous, generator, executeTyped, processor, qos)
}
/// Perform a CoreData result-based request and process the result. Each
/// HMCDResult represents the success/failure of the operation on one
/// particular item.
///
/// - Parameters:
/// - previous: The result of the upstream request.
/// - generator: Generator function to create the current request.
/// - processor: Processor function to process the request result.
/// - Returns: An Observable instance.
public func processTyped<Prev,Res>(
_ previous: Try<Prev>,
_ generator: @escaping HMRequestGenerator<Prev,Req>,
_ processor: @escaping HMResultProcessor<HMCDResult,Res>,
_ qos: DispatchQoS.QoSClass)
-> Observable<Try<[Try<Res>]>>
{
return processArray(previous, generator, executeTyped, processor, qos)
}
/// Perform a CoreData result-based request and process the result using
/// a default processor. Since HMResult and Try have similarities in terms
/// of semantics, we can simply use HMResult directly in the emission.
///
/// - Parameters:
/// - previous: The result of the upstream request.
/// - generator: Generator function to create the current request.
/// - qos: A QoSClass instance to perform work on.
/// - Returns: An Observable instance.
public func processResult<Prev>(
_ previous: Try<Prev>,
_ generator: @escaping HMRequestGenerator<Prev,Req>,
_ qos: DispatchQoS.QoSClass)
-> Observable<Try<[HMCDResult]>>
{
let processor = HMResultProcessors.eqProcessor(HMCDResult.self)
return processTyped(previous, generator, processor, qos)
.map({$0.map({$0.map(HMCDResult.unwrap)})})
}
/// Perform a CoreData get request and process the result into a pure object.
///
/// - Parameters:
/// - previous: The result of the upstream request.
/// - generator: Generator function to create the current request.
/// - poCls: The PureObject class type.
/// - qos: A QoSClass instance to perform work on.
/// - Returns: An Observable instance.
public func processPureObject<Prev,PO>(
_ previous: Try<Prev>,
_ generator: @escaping HMRequestGenerator<Prev,Req>,
_ poCls: PO.Type,
_ qos: DispatchQoS.QoSClass)
-> Observable<Try<[PO]>> where
PO: HMCDPureObjectType,
PO.CDClass: NSManagedObject,
PO.CDClass: HMCDPureObjectConvertibleType,
PO.CDClass.PureObject == PO
{
let processor = HMCDResultProcessors.pureObjectPs(poCls)
return processTyped(previous, generator, processor, qos)
// Since asPureObject() does not throw an error, we can safely
// assume the processing succeeds for all items.
.map({$0.map({$0.flatMap({$0.value})})})
}
/// This method should be used for all operations other than those which
/// require specific NSManagedObject subtypes.
///
/// - Parameters:
/// - previous: The result of the upstream request.
/// - generator: Generator function to create the current request.
/// - processor: Processor function to process the request result.
/// - qos: A QoSClass instance to perform work on.
/// - Returns: An Observable instance.
public func processVoid<Prev,Res>(
_ previous: Try<Prev>,
_ generator: @escaping HMRequestGenerator<Prev,Req>,
_ processor: @escaping HMResultProcessor<Void,Res>,
_ qos: DispatchQoS.QoSClass)
-> Observable<Try<Res>>
{
return execute(previous, generator, execute, qos)
.flatMap({try HMResultProcessors.processResultFn($0, processor)})
}
/// This method should be used for all operations other than those which
/// require specific NSManagedObject subtypes. Cast the result to Void using
/// a default processor.
///
/// - Parameters:
/// - previous: The result of the upstream request.
/// - generator: Generator function to create the current request.
/// - qos: A QoSClass instance to perform work on.
/// - Returns: An Observable instance.
public func processVoid<Prev>(
_ previous: Try<Prev>,
_ generator: @escaping HMRequestGenerator<Prev,Req>,
_ qos: DispatchQoS.QoSClass)
-> Observable<Try<Void>>
{
let processor = {(_: Any) in Observable.just(Try.success(()))}
return processVoid(previous, generator, processor, qos)
}
}
|
apache-2.0
|
025f8e4bf1ba6c428fe433e2e86f7f22
| 37.607477 | 97 | 0.681796 | 4.305367 | false | false | false | false |
sachin004/firefox-ios
|
ClientTests/ClientTests.swift
|
3
|
4352
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import XCTest
import Shared
import Storage
import WebKit
class ClientTests: XCTestCase {
func testArrayCursor() {
let data = ["One", "Two", "Three"];
let t = ArrayCursor<String>(data: data);
// Test subscript access
XCTAssertNil(t[-1], "Subscript -1 returns nil");
XCTAssertEqual(t[0]!, "One", "Subscript zero returns the correct data");
XCTAssertEqual(t[1]!, "Two", "Subscript one returns the correct data");
XCTAssertEqual(t[2]!, "Three", "Subscript two returns the correct data");
XCTAssertNil(t[3], "Subscript three returns nil");
// Test status data with default initializer
XCTAssertEqual(t.status, CursorStatus.Success, "Cursor as correct status");
XCTAssertEqual(t.statusMessage, "Success", "Cursor as correct status message");
XCTAssertEqual(t.count, 3, "Cursor as correct size");
// Test generator access
var i = 0;
for s in t {
XCTAssertEqual(s!, data[i], "Subscript zero returns the correct data");
i++;
}
// Test creating a failed cursor
let t2 = ArrayCursor<String>(data: data, status: CursorStatus.Failure, statusMessage: "Custom status message");
XCTAssertEqual(t2.status, CursorStatus.Failure, "Cursor as correct status");
XCTAssertEqual(t2.statusMessage, "Custom status message", "Cursor as correct status message");
XCTAssertEqual(t2.count, 0, "Cursor as correct size");
// Test subscript access return nil for a failed cursor
XCTAssertNil(t2[0], "Subscript zero returns nil if failure");
XCTAssertNil(t2[1], "Subscript one returns nil if failure");
XCTAssertNil(t2[2], "Subscript two returns nil if failure");
XCTAssertNil(t2[3], "Subscript three returns nil if failure");
// Test that generator doesn't work with failed cursors
var ran = false;
for s in t2 {
print("Got \(s)", terminator: "\n")
ran = true;
}
XCTAssertFalse(ran, "for...in didn't run for failed cursor");
}
func testSyncUA() {
let ua = UserAgent.syncUserAgent
let loc = ua.rangeOfString("^Firefox-iOS-Sync/[0-9\\.]+ \\([-_A-Za-z0-9= \\(\\)]+\\)$", options: NSStringCompareOptions.RegularExpressionSearch)
XCTAssertTrue(loc != nil, "Sync UA is as expected. Was \(ua)")
}
// Simple test to make sure the WKWebView UA matches the expected FxiOS pattern.
func testUserAgent() {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let compare: String -> Bool = { ua in
let range = ua.rangeOfString("^Mozilla/5\\.0 \\(.+\\) AppleWebKit/[0-9\\.]+ \\(KHTML, like Gecko\\) FxiOS/\(appVersion) Mobile/[A-Za-z0-9]+ Safari/[0-9\\.]+$", options: NSStringCompareOptions.RegularExpressionSearch)
return range != nil
}
XCTAssertTrue(compare(UserAgent.defaultUserAgent()), "User agent computes correctly.")
XCTAssertTrue(compare(UserAgent.cachedUserAgent(checkiOSVersion: true)!), "User agent is cached correctly.")
let expectation = expectationWithDescription("Found Firefox user agent")
let webView = WKWebView()
webView.evaluateJavaScript("navigator.userAgent") { result, error in
let userAgent = result as! String
if compare(userAgent) {
expectation.fulfill()
} else {
XCTFail("User agent did not match expected pattern! \(userAgent)")
}
}
waitForExpectationsWithTimeout(5, handler: nil)
}
func testDesktopUserAgent() {
let compare: String -> Bool = { ua in
let range = ua.rangeOfString("^Mozilla/5\\.0 \\(Macintosh; Intel Mac OS X [0-9_]+\\) AppleWebKit/[0-9\\.]+ \\(KHTML, like Gecko\\) Safari/[0-9\\.]+$", options: NSStringCompareOptions.RegularExpressionSearch)
return range != nil
}
XCTAssertTrue(compare(UserAgent.desktopUserAgent()), "Desktop user agent computes correctly.")
}
}
|
mpl-2.0
|
5d4eb124c28c83110fa4ae1ecaa2cb7e
| 43.408163 | 228 | 0.633961 | 4.720174 | false | true | false | false |
fanyinan/ImagePickerProject
|
ImagePicker/Album/PhotoAlbumView.swift
|
1
|
2989
|
//
// PhotoAlbumView.swift
// ImagePickerProject
//
// Created by 范祎楠 on 16/7/6.
// Copyright © 2016年 范祎楠. All rights reserved.
//
import UIKit
protocol PhotoAlbumViewDelegate: NSObjectProtocol {
func photoAlbumView(_ photoAlbumView: PhotoAlbumView, didSelectAtIndex index: Int)
}
class PhotoAlbumView: UIView {
fileprivate var tableView: UITableView!
fileprivate weak var delegate: PhotoAlbumViewDelegate?
let identifier = "PhotoAlbumCell"
init(frame: CGRect, delegate: PhotoAlbumViewDelegate) {
self.delegate = delegate
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/******************************************************************************
* private Implements
******************************************************************************/
//MARK: - private Implements
func setupUI(){
tableView = UITableView(frame: bounds, style: .plain)
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.backgroundColor = UIColor.white
tableView.tableFooterView = UIView()
tableView.dataSource = self
tableView.delegate = self
let nibCell = UINib(nibName: identifier, bundle: Bundle(for: PhotoAlbumView.self))
tableView.register(nibCell, forCellReuseIdentifier: identifier)
tableView.separatorColor = UIColor.separatorColor
tableView.rowHeight = 60.0
addSubview(tableView)
tableView.reloadData()
}
}
extension PhotoAlbumView: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return PhotosManager.shared.getAlbumCount()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! PhotoAlbumCell
guard let collection = PhotosManager.shared.getAlbumWith(indexPath.row) else { return cell }
cell.titleLabel.text = "\(collection.localizedTitle!) (\(PhotosManager.shared.getFetchResult(with: collection, resourceOption: PhotosManager.shared.resourceOption).count))"
PhotosManager.shared.fetchImage(with: indexPath.row, imageIndex: 0, sizeType: .thumbnail) { (image, _) -> Void in
if image == nil {
return
}
cell.thumbImageView.image = image
}
cell.separatorInset = UIEdgeInsets.zero
return cell
}
}
extension PhotoAlbumView: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: true)
}
PhotosManager.shared.currentAlbumIndex = indexPath.row
delegate?.photoAlbumView(self, didSelectAtIndex: indexPath.row)
}
}
|
bsd-2-clause
|
af41790f10161ce78f97aef5770b36d5
| 27.32381 | 176 | 0.668796 | 5.006734 | false | false | false | false |
jgonfer/JGFLabRoom
|
JGFLabRoom/Resources/Utils.swift
|
1
|
12796
|
//
// Utils.swift
// JGFLabRoom
//
// Created by Josep Gonzalez Fernandez on 14/1/16.
// Copyright © 2016 Josep Gonzalez Fernandez. All rights reserved.
//
import UIKit
import Foundation
let userDefaults = NSUserDefaults.standardUserDefaults()
class Utils {
// MARK: GENERAL
static var GlobalMainQueue: dispatch_queue_t {
return dispatch_get_main_queue()
}
static var GlobalUserInteractiveQueue: dispatch_queue_t {
return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)
}
static var GlobalUserInitiatedQueue: dispatch_queue_t {
return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
}
static var GlobalUtilityQueue: dispatch_queue_t {
return dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)
}
static var GlobalBackgroundQueue: dispatch_queue_t {
return dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
}
// MARK: NSNotificationCenter Management
class func registerNotificationWillEnterForeground(observer: AnyObject, selector: Selector) {
// Handle when the app becomes active, going from the background to the foreground
NSNotificationCenter.defaultCenter().addObserver(observer, selector: selector, name: UIApplicationWillEnterForegroundNotification, object: nil)
}
class func removeObserverForNotifications(observer: AnyObject) {
NSNotificationCenter.defaultCenter().removeObserver(observer)
}
// MARK: TableView Management
class func registerStandardXibForTableView(tableView: UITableView, name: String) {
// Registration of a standard UITableViewCell with identifier @name. It'll have standard parameters like cell.textLabel, cell.detailTextLabel and cell.imageView
tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: name)
}
class func registerCustomXibForTableView(tableView: UITableView, name: String) {
// Registration of a new Nib with identifier @name
tableView.registerNib(UINib(nibName: name, bundle: nil), forCellReuseIdentifier: name)
}
// MARK: Navigation Bar Management
class func cleanBackButtonTitle(nav: UINavigationController?) {
// Replacement of the existing button in the navigationBar
nav?.navigationBar.topItem!.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
}
// MARK: Dates Management
class func getStartEndDateForYear(year: Int) -> (NSDate, NSDate)? {
// We get the @year period by setting the start date of the @year, and the end date of the @year
let startDateString = "\(year)-01-01"
let endDateString = "\(year)-12-31"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
guard let startDate = dateFormatter.dateFromString(startDateString) else {
return nil
}
guard let endDate = dateFormatter.dateFromString(endDateString) else {
return nil
}
return (startDate, endDate)
}
class func getWeekdayThreeCharsFromDate(date: NSDate) -> String {
// Request for the three first characters of the weekday (Localized)
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "EEE"
return dayTimePeriodFormatter.stringFromDate(date).uppercaseString
}
class func getWeekdayNameFromDate(date: NSDate) -> String {
// Request for the full name of the weekday (Localized)
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "EEEE"
return dayTimePeriodFormatter.stringFromDate(date).capitalizedString
}
class func getMonthThreeCharsFromDate(date: NSDate) -> String {
// Request for the three first characters of the month (Localized)
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM"
return dayTimePeriodFormatter.stringFromDate(date).uppercaseString
}
class func getMonthNameFromDate(date: NSDate) -> String {
// Request for the full name of the month (Localized)
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "MMMM"
return dayTimePeriodFormatter.stringFromDate(date).capitalizedString
}
class func getMonthsArraysForEvents(events: [[String:String]]?) -> (months: [String]?, eventsSorted: [[[String:String]]]?) {
// Check that we have events to iterate
guard let events = events else {
return (nil, nil)
}
var months: [String]?
var eventsSorted: [[[String:String]]]?
for event in events {
// Check that the event has a date to use
guard let dateString = event["date"] else {
continue
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
// @col is a counter to control the months that we add to our @eventStore array
var col = 0
// Check that there is a valid date
if let date = dateFormatter.dateFromString(dateString) {
let month = getMonthNameFromDate(date)
// Check if the @months array is initialized
guard let _ = months else {
// If isn't initialized, we initialize the array with the first month and @eventStore with the @event that we have
months = [month]
eventsSorted = [[event]]
// Let's keep going on next iteration
continue
}
// Check if @months array contains the month of the current @event
guard months!.contains(month) else {
// If it isn't contained, we increment @col
col++
// We also add the current @month (Month's name) to @months
months?.append(month)
// And finally we add a new array initialized with the current @event to @eventSorted.
eventsSorted?.append([event])
// Our intention is to represent the new position @col of the array like a new month store in the array @eventStored. This kind of order will help us in the future when we'll display the array in our tableView providing this array as the data source.
// Let's keep going on next iteration
continue
}
eventsSorted![col].append(event)
}
}
return (months, eventsSorted)
}
// MARK: Common Crypto Management ()
// MARK: Read this
// 1) To get working Common Crypto you need implement a Bridging-Header.h in your project
// 2) Then, import in this new file the library with this line: "#import <CommonCrypto/CommonCrypto.h>"
// 3) For last but not less, go to the tab "Build Settings" in your project and search "Bridging Header". In the row result named "Objective-C Bridging Header", type the path of your Bridging Header file. In this project is "JGFLabRoom/Resources/JGFLabRoom-Bridging-Header.h". You can check it by navigating through folders in Finder.
// Et voilà! Xcode will recognize everything related to Common Crypto
class func generateRandomStringKey() -> String {
let bytesCount = 4 // number of bytes
var randomNum = ""
var randomBytes = [UInt8](count: bytesCount, repeatedValue: 0) // array to hold randoms bytes
// Gen random bytes
SecRandomCopyBytes(kSecRandomDefault, bytesCount, &randomBytes)
// Turn randomBytes into array of hexadecimal strings
// Join array of strings into single string
randomNum = randomBytes.map({String(format: "%04hhx", $0)}).joinWithSeparator("")
return randomNum
}
static func AESEncryption(message: String, key: String, algorithm: Int, blockSize: Int, contextSize: Int, keySize: Int, option: Int) -> (data: NSData, text: String)? {
let keyString = key
let keyData: NSData! = (keyString as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let keyBytes = UnsafeMutablePointer<Void>(keyData.bytes)
print("keyLength = \(keyData.length), keyData = \(keyData)")
let message = message
let data: NSData! = (message as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let dataLength = size_t(data.length)
let dataBytes = UnsafeMutablePointer<Void>(data.bytes)
print("dataLength = \(dataLength), data = \(data)")
let cryptData = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)
let cryptPointer = UnsafeMutablePointer<Void>(cryptData!.mutableBytes)
let cryptLength = size_t(cryptData!.length)
let keyLength = size_t(kCCKeySizeAES128)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(kCCOptionPKCS7Padding + kCCOptionECBMode)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
keyBytes, keyLength,
nil,
dataBytes, dataLength,
cryptPointer, cryptLength,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
// let x: UInt = numBytesEncrypted
cryptData!.length = Int(numBytesEncrypted)
print("cryptLength = \(numBytesEncrypted), cryptData = \(cryptData)")
// Not all data is a UTF-8 string so Base64 is used
let base64cryptString = cryptData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
print("base64cryptString = \(base64cryptString)")
return (cryptData!, base64cryptString)
} else {
print("Error: \(cryptStatus)")
return nil
}
}
static func AESDecryption(data:NSData, key: String, algorithm: Int, blockSize: Int, contextSize: Int, keySize: Int, option: Int) -> (data: NSData, text: String)? {
let keyString = key
let keyData: NSData! = (keyString as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let keyBytes = UnsafeMutablePointer<Void>(keyData.bytes)
print("keyLength = \(keyData.length), keyData = \(keyData)")
//let message = "Don´t try to read this text. Top Secret Stuff"
// let data: NSData! = (message as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let dataLength = size_t(data.length)
let dataBytes = UnsafeMutablePointer<Void>(data.bytes)
print("dataLength = \(dataLength), data = \(data)")
let cryptData = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)
let cryptPointer = UnsafeMutablePointer<Void>(cryptData!.mutableBytes)
let cryptLength = size_t(cryptData!.length)
let keyLength = size_t(kCCKeySizeAES128)
let operation: CCOperation = UInt32(kCCDecrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(kCCOptionPKCS7Padding + kCCOptionECBMode)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
keyBytes, keyLength,
nil,
dataBytes, dataLength,
cryptPointer, cryptLength,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
// let x: UInt = numBytesEncrypted
cryptData!.length = Int(numBytesEncrypted)
print("DecryptcryptLength = \(numBytesEncrypted), Decrypt = \(cryptData)")
// Not all data is a UTF-8 string so Base64 is used
let base64cryptString = cryptData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
print("base64DecryptString = \(base64cryptString)")
print( "utf8 actual string = \(NSString(data: cryptData!, encoding: NSUTF8StringEncoding))");
return (cryptData!, base64cryptString)
} else {
print("Error: \(cryptStatus)")
return nil
}
}
}
|
mit
|
c49f043cf01fc8dd517b58e48c9953bf
| 44.856631 | 338 | 0.63269 | 5.078603 | false | false | false | false |
devpunk/cartesian
|
cartesian/View/Store/VStoreHeader.swift
|
1
|
3943
|
import UIKit
class VStoreHeader:UICollectionReusableView
{
private let attrTitle:[String:Any]
private let attrDescr:[String:Any]
private let labelMargins:CGFloat
private weak var label:UILabel!
private weak var imageView:UIImageView!
private weak var layoutLabelHeight:NSLayoutConstraint!
private let kLabelTop:CGFloat = 16
private let kLabelLeft:CGFloat = 10
private let kLabelRight:CGFloat = -10
private let kImageSize:CGFloat = 100
override init(frame:CGRect)
{
attrTitle = [
NSFontAttributeName:UIFont.bolder(size:20),
NSForegroundColorAttributeName:UIColor.cartesianBlue]
attrDescr = [
NSFontAttributeName:UIFont.regular(size:16),
NSForegroundColorAttributeName:UIColor.black]
labelMargins = -kLabelRight + kLabelLeft + kImageSize
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.white
isUserInteractionEnabled = false
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.backgroundColor = UIColor.clear
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
self.label = label
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
imageView.translatesAutoresizingMaskIntoConstraints = false
self.imageView = imageView
addSubview(label)
addSubview(imageView)
NSLayoutConstraint.topToTop(
view:label,
toView:self,
constant:kLabelTop)
layoutLabelHeight = NSLayoutConstraint.height(
view:label)
NSLayoutConstraint.leftToRight(
view:label,
toView:imageView,
constant:kLabelLeft)
NSLayoutConstraint.rightToRight(
view:label,
toView:self,
constant:kLabelRight)
NSLayoutConstraint.topToTop(
view:imageView,
toView:self)
NSLayoutConstraint.size(
view:imageView,
constant:kImageSize)
NSLayoutConstraint.leftToLeft(
view:imageView,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
guard
let attributedText:NSAttributedString = label.attributedText
else
{
return
}
let width:CGFloat = bounds.maxX
let height:CGFloat = bounds.maxY
let usableWidth:CGFloat = width - labelMargins
let usableSize:CGSize = CGSize(width:usableWidth, height:height)
let boundingRect:CGRect = attributedText.boundingRect(
with:usableSize,
options:NSStringDrawingOptions([
NSStringDrawingOptions.usesLineFragmentOrigin,
NSStringDrawingOptions.usesFontLeading]),
context:nil)
layoutLabelHeight.constant = ceil(boundingRect.size.height)
super.layoutSubviews()
}
//MARK: public
func config(model:MStoreItem)
{
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
let stringTitle:NSAttributedString = NSAttributedString(
string:model.title,
attributes:attrTitle)
let stringDescr:NSAttributedString = NSAttributedString(
string:model.descr,
attributes:attrDescr)
mutableString.append(stringTitle)
mutableString.append(stringDescr)
label.attributedText = mutableString
imageView.image = model.image
setNeedsLayout()
}
}
|
mit
|
56dee175e447bde1a30e8a77444c9c30
| 30.293651 | 81 | 0.622876 | 6.047546 | false | false | false | false |
dulingkang/Capture
|
Capture/Capture/SeniorBeauty/Mosaic/APMosaicView.swift
|
1
|
5296
|
//
// APMosaicView.swift
// Capture
//
// Created by ShawnDu on 15/12/8.
// Copyright © 2015年 ShawnDu. All rights reserved.
//
import UIKit
class APMosaicView: UIView {
var previousTouchLocation: CGPoint = CGPointZero
var currentTouchLocation: CGPoint = CGPointZero
var hideImage: CGImageRef!
var scratchImage: CGImageRef!
var contextMask: CGContextRef!
var sizeBrush: CGFloat = 60.0 {
didSet{
CGContextSetLineWidth(contextMask, sizeBrush)
}
}
var hideView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
self.opaque = false
}
//MARK: CoreGraphics methods
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let imageToDraw = UIImage.init(CGImage: self.scratchImage)
imageToDraw.drawInRect(self.bounds)
}
func setBrushSize(size: CGFloat){
CGContextSetLineWidth(contextMask, size)
}
func getEndImg(image: UIImage) ->UIImage{
return UIGraphicsGetImageFromCurrentImageContext()
}
func setHiddenView(hideView: UIView){
let colorspace = CGColorSpaceCreateDeviceGray()
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(hideView.bounds.size, false, 0)
hideView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
hideView.layer.contentsScale = scale
hideImage = UIGraphicsGetImageFromCurrentImageContext().CGImage
UIGraphicsEndImageContext()
let imageWidth = CGImageGetWidth(hideImage)
let imageHeight = CGImageGetHeight(hideImage)
let pixels = CFDataCreateMutable(nil, imageWidth * imageHeight);
contextMask = CGBitmapContextCreate(CFDataGetMutableBytePtr(pixels), imageWidth, imageHeight , 8, imageWidth, colorspace, CGImageAlphaInfo.None.rawValue)
let dataProvider = CGDataProviderCreateWithCFData(pixels)
CGContextSetFillColorWithColor(contextMask, UIColor.blackColor().CGColor)
CGContextFillRect(contextMask, self.frame)
CGContextSetStrokeColorWithColor(contextMask, UIColor.whiteColor().CGColor)
CGContextSetLineWidth(contextMask, 2000)
CGContextSetLineCap(contextMask, CGLineCap.Round)
let mask = CGImageMaskCreate(imageWidth, imageHeight, 8, 8, imageWidth, dataProvider, nil, false);
scratchImage = CGImageCreateWithMask(hideImage, mask)
self.hideImageView()
}
func setPathColor(fillColor: UIColor, strokeColor: UIColor){
CGContextSetLineWidth(contextMask, self.sizeBrush)
CGContextSetFillColorWithColor(contextMask, fillColor.CGColor)
CGContextSetStrokeColorWithColor(contextMask, strokeColor.CGColor)
}
func hideImageView(){
CGContextMoveToPoint(contextMask, 0,0)
CGContextAddLineToPoint(contextMask, self.bounds.width, self.bounds.height)
CGContextStrokePath(contextMask);
self.setNeedsDisplay()
}
func scratchTheViewFrom(startPoint: CGPoint, endPoint: CGPoint){
let scale = UIScreen.mainScreen().scale;
CGContextMoveToPoint(contextMask, startPoint.x * scale, (self.frame.size.height - startPoint.y) * scale)
CGContextAddLineToPoint(contextMask, endPoint.x * scale, (self.frame.size.height - endPoint.y) * scale)
CGContextStrokePath(contextMask);
self.setNeedsDisplay()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
let touch : UITouch = (event?.touchesForView(self)?.first)!
self.currentTouchLocation = touch.locationInView(self)
print("\(self.currentTouchLocation)")
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesMoved(touches, withEvent: event)
let touch = event!.touchesForView(self)?.first
if (!CGPointEqualToPoint(previousTouchLocation, CGPointZero))
{
currentTouchLocation = touch!.locationInView(self)
}
previousTouchLocation = touch!.previousLocationInView(self)
self.scratchTheViewFrom(previousTouchLocation, endPoint: currentTouchLocation)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
let touch = event!.touchesForView(self)?.first
if (!CGPointEqualToPoint(previousTouchLocation, CGPointZero))
{
previousTouchLocation = touch!.previousLocationInView(self)
self.scratchTheViewFrom(previousTouchLocation, endPoint: currentTouchLocation)
}
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
}
//MARK: touch event
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
fcdd7f05356680acf68621869b87022c
| 32.929487 | 161 | 0.660306 | 5.395515 | false | false | false | false |
jonnguy/HSTracker
|
HSTracker/UIs/Battlegrounds/BattlegroundsDetailsView.swift
|
1
|
5991
|
//
// BattlegroundsOverlayView.swift
// HSTracker
//
// Created by Martin BONNIN on 30/11/2019.
// Copyright © 2019 HearthSim LLC. All rights reserved.
//
import Foundation
import kotlin_hslog
class BattlegroundsDetailsView: NSView {
var board: BattlegroundsBoard?
var cache: [(String, NSImage)] = []
init() {
super.init(frame: NSRect.zero)
logger.debug("BattlegroundsDetailsView created")
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let backgroundColor: NSColor = NSColor.clear
//let backgroundColor = NSColor.init(red: 0x48/255.0, green: 0x7E/255.0, blue: 0xAA/255.0, alpha: 0.3)
backgroundColor.set()
dirtyRect.fill()
if let board = self.board {
drawBoard(board: board)
}
}
func drawBoard(board: BattlegroundsBoard) {
drawTurn(turns: (board.currentTurn - board.turn)/2)
var i = 0
let rect = NSRect(x: 0, y: 0, width: bounds.width/7, height: bounds.height - CGFloat(30)).insetBy(dx: 4, dy: 4)
for minion in board.minions {
drawMinion(minion: minion, rect: rect.offsetBy(dx: CGFloat(i) * bounds.width/7, dy: 0))
i += 1
}
}
func drawResource(name: String, rect: NSRect) {
if let image = NSImage(contentsOfFile: Bundle.main.resourcePath! + "/Resources/Battlegrounds/\(name)") {
image.draw(in: rect)
}
}
func drawText(text: String, rect: NSRect) {
if let font = NSFont(name: "ChunkFive", size: 14) {
var attributes: [NSAttributedStringKey: Any] = [
.font: font,
.foregroundColor: NSColor.white,
.strokeWidth: -2,
.strokeColor: NSColor.black
]
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
attributes[.paragraphStyle] = paragraph
text.draw(with: rect, options: NSString.DrawingOptions.truncatesLastVisibleLine,
attributes: attributes)
}
}
func drawMinion(minion: BattlegroundsMinion, rect: NSRect) {
let backgroundColor = NSColor.init(red: 0x48/255.0, green: 0x7E/255.0, blue: 0xAA/255.0, alpha: 1)
backgroundColor.set()
rect.fill()
let rect = rect.insetBy(dx: 2, dy: 2)
let h = rect.height/2
let imageRect = NSRect(x: rect.minX, y: rect.minY + rect.height - h, width: rect.width, height: h)
let iconH = h - 6
let x = rect.minX + (imageRect.width/4 - iconH)/2
let y = rect.minY + 3
let iconRect = NSRect(x: x, y: CGFloat(y), width: iconH, height: iconH)
let offset = (iconH - 14)/2
drawResource(name: "attackminion.png", rect: iconRect)
drawText(text: "\(minion.attack)", rect: iconRect.offsetBy(dx: 0, dy: offset))
if minion.divineShield {
drawResource(name: "divineshield.png", rect: iconRect.offsetBy(dx: imageRect.width/4, dy: 0))
}
if minion.poisonous {
drawResource(name: "poison.png", rect: iconRect.offsetBy(dx: 2*imageRect.width/4, dy: 0))
}
drawResource(name: "costhealth.png", rect: iconRect.offsetBy(dx: 3*imageRect.width/4, dy: 0))
drawText(text: "\(minion.health)", rect: iconRect.offsetBy(dx: 3*imageRect.width/4, dy: 0).offsetBy(dx: 0, dy: offset))
if let image = cache.first(where: { $0.0 == minion.CardId })?.1 {
image.draw(in: imageRect)
drawResource(name: "fade.png", rect: imageRect)
if let font = NSFont(name: "ChunkFive", size: 14) {
let attributes: [NSAttributedStringKey: Any] = [
.font: font,
.foregroundColor: NSColor.white,
.strokeWidth: -2,
.strokeColor: NSColor.black
]
let cardJson = AppDelegate.instance().coreManager.cardJson!
let name = cardJson.getCard(id: minion.CardId).name
let textRect = imageRect.insetBy(dx: 8, dy: 10)
name.draw(with: textRect, options: NSString.DrawingOptions.truncatesLastVisibleLine,
attributes: attributes)
}
return
} else {
NSColor.black.set()
imageRect.fill()
}
let cardId = minion.CardId
ImageUtils.tile(for: cardId, completion: { [weak self] in
guard let image = $0 else {
logger.warning("No image for \(minion.CardId)")
return
}
self?.cache.append((cardId, image))
if let count = self?.cache.count, count > 7 {
self?.cache.remove(at: 0)
}
DispatchQueue.main.async { [weak self] in
self?.needsDisplay = true
}
})
}
func drawTurn(turns: Int32) {
if let font = NSFont(name: "ChunkFive", size: 20) {
let attributes: [NSAttributedStringKey: Any] = [
.font: font,
.foregroundColor: NSColor.white,
.strokeWidth: -2,
.strokeColor: NSColor.black
]
let h = CGFloat(20)
"\(turns) turn(s) ago".draw(with: NSRect(x: 0, y: (bounds.height - h), width: bounds.width, height: h),
options: NSString.DrawingOptions.truncatesLastVisibleLine,
attributes: attributes)
}
}
func setBoard(board: BattlegroundsBoard) {
self.board = board
self.needsDisplay = true
}
}
|
mit
|
a2fd9f0533b8901a1348b4ecd929ee64
| 34.868263 | 127 | 0.546244 | 4.116838 | false | false | false | false |
gottesmm/swift
|
test/IDE/import_as_member.swift
|
5
|
3008
|
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.A -always-argument-labels > %t.printed.A.txt
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.B -always-argument-labels > %t.printed.B.txt
// RUN: %FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt
// RUN: %FileCheck %s -check-prefix=PRINTB -strict-whitespace < %t.printed.B.txt
// PRINT: struct Struct1 {
// PRINT-NEXT: var x: Double
// PRINT-NEXT: var y: Double
// PRINT-NEXT: var z: Double
// PRINT-NEXT: init()
// PRINT-NEXT: init(x x: Double, y y: Double, z z: Double)
// PRINT-NEXT: }
// Make sure the other extension isn't here.
// PRINT-NOT: static var static1: Double
// PRINT: extension Struct1 {
// PRINT-NEXT: static var globalVar: Double
// PRINT-NEXT: init(value value: Double)
// PRINT-NEXT: init(specialLabel specialLabel: ())
// PRINT-NEXT: func inverted() -> Struct1
// PRINT-NEXT: mutating func invert()
// PRINT-NEXT: func translate(radians radians: Double) -> Struct1
// PRINT-NEXT: func scale(_ radians: Double) -> Struct1
// PRINT-NEXT: var radius: Double { get nonmutating set }
// PRINT-NEXT: var altitude: Double{{$}}
// PRINT-NEXT: var magnitude: Double { get }
// PRINT-NEXT: static func staticMethod() -> Int32
// PRINT-NEXT: static var property: Int32
// PRINT-NEXT: static var getOnlyProperty: Int32 { get }
// PRINT-NEXT: func selfComesLast(x x: Double)
// PRINT-NEXT: func selfComesThird(a a: Int32, b b: Float, x x: Double)
// PRINT-NEXT: }
// PRINT-NOT: static var static1: Double
// Make sure the other extension isn't here.
// PRINTB-NOT: static var globalVar: Double
// PRINTB: extension Struct1 {
// PRINTB: static var static1: Double
// PRINTB-NEXT: static var static2: Float
// PRINTB-NEXT: init(float value: Float)
// PRINTB-NEXT: static var zero: Struct1 { get }
// PRINTB-NEXT: }
// PRINTB: var currentStruct1: Struct1
// PRINTB-NOT: static var globalVar: Double
// RUN: %target-typecheck-verify-swift -I %S/Inputs/custom-modules
import ImportAsMember.A
import ImportAsMember.B
let iamStructFail = IAMStruct1CreateSimple()
// expected-error@-1{{missing argument for parameter #1 in call}}
var iamStruct = Struct1(x: 1.0, y: 1.0, z: 1.0)
let gVarFail = IAMStruct1GlobalVar
// expected-error@-1{{IAMStruct1GlobalVar' has been renamed to 'Struct1.globalVar'}}
let gVar = Struct1.globalVar
print("\(gVar)")
let iamStructInitFail = IAMStruct1CreateSimple(42)
// expected-error@-1{{'IAMStruct1CreateSimple' has been replaced by 'Struct1.init(value:)'}}
let iamStructInitFail2 = Struct1(value: 42)
let gVar2 = Struct1.static2
// Instance properties
iamStruct.radius += 1.5
_ = iamStruct.magnitude
// Static properties
iamStruct = Struct1.zero
// Global properties
currentStruct1.x += 1.5
|
apache-2.0
|
0843d3dd6cfdb9e7dc637ba2b220054b
| 36.6 | 206 | 0.702793 | 3.179704 | false | false | false | false |
gottesmm/swift
|
test/SILGen/writeback.swift
|
4
|
5849
|
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s
struct Foo {
mutating // used to test writeback.
func foo() {}
subscript(x: Int) -> Foo {
get {
return Foo()
}
set {}
}
}
var x: Foo {
get {
return Foo()
}
set {}
}
var y: Foo {
get {
return Foo()
}
set {}
}
var z: Foo {
get {
return Foo()
}
set {}
}
var readonly: Foo {
get {
return Foo()
}
}
func bar(x x: inout Foo) {}
// Writeback to value type 'self' argument
x.foo()
// CHECK: [[FOO:%.*]] = function_ref @_T09writeback3FooV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout Foo) -> ()
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @_T09writeback1xAA3FooVfg : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [trivial] [[X_TEMP]]
// CHECK: apply [[FOO]]([[X_TEMP]]) : $@convention(method) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @_T09writeback1xAA3FooVfs : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]] : $*Foo
// Writeback to inout argument
bar(x: &x)
// CHECK: [[BAR:%.*]] = function_ref @_T09writeback3baryAA3FooVz1x_tF : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @_T09writeback1xAA3FooVfg : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [trivial] [[X_TEMP]] : $*Foo
// CHECK: apply [[BAR]]([[X_TEMP]]) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @_T09writeback1xAA3FooVfs : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]] : $*Foo
func zang(x x: Foo) {}
// No writeback for pass-by-value argument
zang(x: x)
// CHECK: function_ref @_T09writeback4zangyAA3FooV1x_tF : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @_T09writeback1xAA3FooVfs
zang(x: readonly)
// CHECK: function_ref @_T09writeback4zangyAA3FooV1x_tF : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @_T09writeback8readonlyAA3FooVfs
func zung() -> Int { return 0 }
// Ensure that subscripts are only evaluated once.
bar(x: &x[zung()])
// CHECK: [[BAR:%.*]] = function_ref @_T09writeback3baryAA3FooVz1x_tF : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[ZUNG:%.*]] = function_ref @_T09writeback4zungSiyF : $@convention(thin) () -> Int
// CHECK: [[INDEX:%.*]] = apply [[ZUNG]]() : $@convention(thin) () -> Int
// CHECK: [[GET_X:%.*]] = function_ref @_T09writeback1xAA3FooVfg : $@convention(thin) () -> Foo
// CHECK: [[GET_SUBSCRIPT:%.*]] = function_ref @_T09writeback3FooV9subscript{{[_0-9a-zA-Z]*}}fg : $@convention(method) (Int, Foo) -> Foo
// CHECK: apply [[GET_SUBSCRIPT]]([[INDEX]], {{%.*}}) : $@convention(method) (Int, Foo) -> Foo
// CHECK: apply [[BAR]]({{%.*}}) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[SET_SUBSCRIPT:%.*]] = function_ref @_T09writeback3FooV9subscript{{[_0-9a-zA-Z]*}}fs : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: apply [[SET_SUBSCRIPT]]({{%.*}}, [[INDEX]], {{%.*}}) : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: function_ref @_T09writeback1xAA3FooVfs : $@convention(thin) (Foo) -> ()
protocol Fungible {}
extension Foo : Fungible {}
var addressOnly: Fungible {
get {
return Foo()
}
set {}
}
func funge(x x: inout Fungible) {}
funge(x: &addressOnly)
// CHECK: [[FUNGE:%.*]] = function_ref @_T09writeback5fungeyAA8Fungible_pz1x_tF : $@convention(thin) (@inout Fungible) -> ()
// CHECK: [[TEMP:%.*]] = alloc_stack $Fungible
// CHECK: [[GET:%.*]] = function_ref @_T09writeback11addressOnlyAA8Fungible_pfg : $@convention(thin) () -> @out Fungible
// CHECK: apply [[GET]]([[TEMP]]) : $@convention(thin) () -> @out Fungible
// CHECK: apply [[FUNGE]]([[TEMP]]) : $@convention(thin) (@inout Fungible) -> ()
// CHECK: [[SET:%.*]] = function_ref @_T09writeback11addressOnlyAA8Fungible_pfs : $@convention(thin) (@in Fungible) -> ()
// CHECK: apply [[SET]]([[TEMP]]) : $@convention(thin) (@in Fungible) -> ()
// CHECK: dealloc_stack [[TEMP]] : $*Fungible
// Test that writeback occurs with generic properties.
// <rdar://problem/16525257>
protocol Runcible {
associatedtype Frob: Frobable
var frob: Frob { get set }
}
protocol Frobable {
associatedtype Anse
var anse: Anse { get set }
}
// CHECK-LABEL: sil hidden @_T09writeback12test_generic{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Runce, #Runcible.frob!materializeForSet.1
// CHECK: witness_method $Runce.Frob, #Frobable.anse!setter.1
func test_generic<Runce: Runcible>(runce runce: inout Runce, anse: Runce.Frob.Anse) {
runce.frob.anse = anse
}
// We should *not* write back when referencing decls or members as rvalues.
// <rdar://problem/16530235>
// CHECK-LABEL: sil hidden @_T09writeback15loadAddressOnlyAA8Fungible_pyF : $@convention(thin) () -> @out Fungible {
func loadAddressOnly() -> Fungible {
// CHECK: function_ref writeback.addressOnly.getter
// CHECK-NOT: function_ref writeback.addressOnly.setter
return addressOnly
}
// CHECK-LABEL: sil hidden @_T09writeback10loadMember{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Runce, #Runcible.frob!getter.1
// CHECK: witness_method $Runce.Frob, #Frobable.anse!getter.1
// CHECK-NOT: witness_method $Runce.Frob, #Frobable.anse!setter.1
// CHECK-NOT: witness_method $Runce, #Runcible.frob!setter.1
func loadMember<Runce: Runcible>(runce runce: Runce) -> Runce.Frob.Anse {
return runce.frob.anse
}
|
apache-2.0
|
ebd5ec4f355577c72507cd36b444b21c
| 36.49359 | 147 | 0.617712 | 3.17363 | false | false | false | false |
willpowell8/JIRAMobileKit
|
JIRAMobileKit/Classes/ViewControllers/JiraImageViewController.swift
|
1
|
2040
|
//
// JiraImageViewController.swift
// Pods
//
// Created by Will Powell on 30/08/2017.
//
//
import UIKit
protocol JiraImageViewControllerDelegate {
func updateImage(image:UIImage, attachmentID:Int)
}
class JiraImageViewController: UIViewController {
var canvas:AnnoateImageView?
var image:UIImage? {
didSet{
canvas?.image = image
}
}
var attachmentID:Int?
var delegate:JiraImageViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.gray
self.navigationItem.title = "Annotate Image"
canvas = AnnoateImageView()
canvas?.clearCanvas(animated:false)
canvas?.drawColor = .red
canvas?.isUserInteractionEnabled = true
self.view.addSubview(canvas!)
if #available(iOS 9.0, *) {
canvas?.translatesAutoresizingMaskIntoConstraints = false
canvas?.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant:10).isActive = true
canvas?.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant:-10).isActive = true
canvas?.heightAnchor.constraint(equalTo: self.view.heightAnchor, constant:-20).isActive = true
canvas?.topAnchor.constraint(equalTo: self.view.topAnchor, constant:10).isActive = true
}
canvas?.contentMode = .scaleAspectFit
canvas?.image = image
let applyButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(apply))
self.navigationItem.rightBarButtonItems = [applyButton]
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func apply(){
self.delegate?.updateImage(image: self.canvas!.image!,attachmentID: attachmentID ?? 0)
self.navigationController?.popViewController(animated: true)
}
}
|
mit
|
b935682460050f11dbd45d2009120845
| 32.442623 | 109 | 0.672059 | 4.903846 | false | false | false | false |
Resoulte/DYZB
|
DYZB/DYZB/Classes/Home/Controller/DYRecommendController.swift
|
1
|
3807
|
//
// DYRecommendController.swift
// DYZB
//
// Created by ma c on 16/10/26.
// Copyright © 2016年 shifei. All rights reserved.
//
import UIKit
// MARK: -定义常量
private let kCycleViewH = kScreenW * 3 / 8
private let kGameViewH : CGFloat = 90.0
class DYRecommendController: DYBaseViewController {
// MARK: -懒加载
lazy var recommendVM = DYRecommendViewModel()
lazy var cycleView : DYRecommendCycleView = {
let cycleView = DYRecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH)
return cycleView
}()
lazy var gameView : DYRecommendGameView = {
let gameView = DYRecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
// MARK: -系统回调的方法
override func viewDidLoad() {
super.viewDidLoad()
loadCycleData()
}
}
// MARK: - 设置UI界面
extension DYRecommendController {
override func setupUI() {
super.setupUI()
collection.delegate = self
// 1.将UICollectionView加入控制器view当中
view.addSubview(collection)
// 2.将cycleView加到collectionview
collection.addSubview(cycleView)
// 将gameView加到collectionview
collection.addSubview(gameView)
// 3.设置collectionview的内边距
collection.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0)
}
}
// MARK: - 请求数据
extension DYRecommendController {
// 请求推荐数据
override func loadData() {
// 1.给父类中的viewmodel赋值
baseVM = recommendVM
// 2.发送请求
recommendVM.requestData {
self.collection.reloadData()
// 将数据传给gameView
var groups = self.recommendVM.anchorGroups
// 1.移除前两组数据
groups.removeFirst()
groups.removeFirst()
// 添加更多
let moreGroup = DYAnchorGroupItem()
moreGroup.tag_name = "更多"
groups.append(moreGroup)
self.gameView.groups = groups
}
self.loadFinishedData()
}
// 请求轮播数据
fileprivate func loadCycleData() {
recommendVM.requestCycleData {
self.cycleView.cycleItems = self.recommendVM.cycleItems
}
}
}
extension DYRecommendController : UICollectionViewDelegateFlowLayout{
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let group = recommendVM.anchorGroups[indexPath.section]
let anchor = group.anchors[indexPath.item]
if indexPath.section == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyID, for: indexPath) as! DYPrettyCollectionViewCell
cell.anchor = anchor
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalID, for: indexPath) as! DYNormalCollectionViewCell
cell.anchor = anchor
return cell
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kNormalItemW, height: kPrettyItemH)
} else {
return CGSize(width: kNormalItemW, height: kNormalItemH)
}
}
}
|
mit
|
bdc1efddb0a411eb66dba2c37cb52e26
| 26.560606 | 160 | 0.62177 | 5.145686 | false | false | false | false |
imfree-jdcastro/Evrythng-iOS-SDK
|
Evrythng-iOS/URLHelper.swift
|
1
|
3013
|
//
// URLHelper.swift
// EvrythngiOS
//
// Created by JD Castro on 27/05/2017.
// Copyright © 2017 ImFree. All rights reserved.
//
import UIKit
public class URLHelper {
/**
Add, update, or remove a query string item from the URL
:param: url the URL
:param: key the key of the query string item
:param: value the value to replace the query string item, nil will remove item
:returns: the URL with the mutated query string
*/
public class func addOrUpdateQueryStringParameter(url: String, key: String, value: Any?) -> String {
if var components = URLComponents(string: url) {
if var queryItems = components.queryItems {
for (index, item) in queryItems.enumerated() {
// Match query string key and update
if item.name == key {
if let v = value {
queryItems[index] = URLQueryItem(name: key, value: v as? String)
} else {
queryItems.remove(at: index)
}
components.queryItems = queryItems.count > 0
? queryItems : nil
return components.string!
}
}
// Key doesn't exist if reaches here
if let v = value {
// Add key to URL query string
queryItems.append(URLQueryItem(name: key, value: v as? String))
components.queryItems = queryItems as [URLQueryItem]
return components.string!
}
} else {
if let v = value {
// Add key to URL query string
components.queryItems = [URLQueryItem(name: key, value: v as? String)]
return components.string!
}
}
}
return url
}
/**
Add, update, or remove a query string parameters from the URL
:param: url the URL
:param: values the dictionary of query string parameters to replace
:returns: the URL with the mutated query string
*/
public class func addOrUpdateQueryStringParameter(url: String, values: [String: Any]) -> String {
var newUrl = url
for item in values {
newUrl = addOrUpdateQueryStringParameter(url: newUrl, key: item.0, value: item.1)
}
return newUrl
}
/**
Removes a query string item from the URL
:param: url the URL
:param: key the key of the query string item
:returns: the URL with the mutated query string
*/
public class func removeQueryStringParameter(url: String, key: String) -> String {
return addOrUpdateQueryStringParameter(url: url, key: key, value: nil)
}
}
|
apache-2.0
|
850ca0d40c55ae2dbb0ca83dfa90a048
| 32.098901 | 104 | 0.519588 | 5.184165 | false | false | false | false |
Ahmed-Ali/RealmObjectEditor
|
Realm Object Editor/ImplementationFileContentGenerator.swift
|
1
|
2076
|
//
// ImplementationFileContentGenerator.swift
// Realm Object Editor
//
// Created by Ahmed Ali on 1/24/15.
// Copyright (c) 2015 Ahmed Ali. All rights reserved.
//
class ImplementationFileContentGenerator: FileContentGenerator {
override func getFileContent() -> String
{
appendCopyrights(entity.name, fileExtension: lang.implementation.fileExtension)
content += lang.implementation.headerImport
content += lang.implementation.modelDefinition
content += lang.implementation.modelStart
content.replace(EntityName, by: entity.name)
appendIndexedAttributes(lang.implementation.indexedAttributesDefination, forEachIndexedAttribute: lang.implementation.forEachIndexedAttribute)
appendPrimaryKey(lang.implementation.primaryKeyDefination)
appendDefaultValues()
appendIgnoredProperties(lang.implementation.ignoredProperties, forEachIgnoredProperty: lang.implementation.forEachIgnoredProperty)
content += lang.implementation.modelEnd
return content
}
//MARK: - Default Values
func appendDefaultValues()
{
var defValues = ""
let types = lang.dataTypes.toDictionary()
for attr in entity.attributes{
if !attr.hasDefault{
continue
}
let defValue = defaultValueForAttribute(attr, types: types)
if attr.defaultValue.characters.count == 0{
continue
}
var defValueDefination = lang.implementation.forEachPropertyWithDefaultValue
defValueDefination.replace(AttrName, by: attr.name)
defValueDefination.replace(AttrDefaultValue, by: defValue)
defValues += defValueDefination
}
if defValues.characters.count > 0{
var defValuesDef = lang.implementation.defaultValuesDefination
defValuesDef.replace(DefaultValues, by: defValues)
content += defValuesDef
}
}
}
|
mit
|
4dffa6b4548bd0e4cc39aded704ec437
| 33.032787 | 150 | 0.655106 | 5.255696 | false | false | false | false |
Zacharyg88/Alien-Adventure-3
|
Alien Adventure/SettingsViewController.swift
|
3
|
1771
|
//
// SettingsViewController.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/4/15.
// Copyright © 2015 Udacity. All rights reserved.
//
import UIKit
// MARK: - SettingsViewController: UIViewController
class SettingsViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var levelSegmentedControl: UISegmentedControl!
@IBOutlet weak var startGameButton: UIButton!
@IBOutlet weak var showBadgesLabel: UILabel!
@IBOutlet weak var showBadgesSwitch: UISwitch!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
let attributesDictionary: [String:AnyObject] = [
NSFontAttributeName: UIFont(name: Settings.Common.Font, size: 18)!
]
titleLabel.font = UIFont(name: Settings.Common.Font, size: 32)
showBadgesLabel.font = UIFont(name: Settings.Common.Font, size: 20)
showBadgesSwitch.onTintColor = UIColor.magenta
levelSegmentedControl.setTitleTextAttributes(attributesDictionary, for: UIControlState())
Settings.Common.Level = levelSegmentedControl.selectedSegmentIndex
startGameButton.titleLabel?.font = UIFont(name: Settings.Common.Font, size: 20)
addTargets()
}
// MARK: Add Targets
func addTargets() {
print("adding targets!")
}
// MARK: Implementing Actions
func switchLevel(segmentControl: UISegmentedControl) {
print("level control has changed!")
}
func showBadges(switchControl: UISwitch) {
print("show badges switch has changed!")
}
func startGame() {
print("start button has been pressed!")
}
}
|
mit
|
d92b430d1de357b5f839a0a518b3beca
| 28.016393 | 97 | 0.658757 | 5.028409 | false | false | false | false |
harryworld/CocoaSwiftPlayer
|
CocoaSwiftPlayer/ViewControllers/StatusItemViewController/StatusItemViewController.swift
|
1
|
1047
|
//
// StatusItemViewController.swift
// CocoaSwiftPlayer
//
// Created by Harry Ng on 17/2/2016.
// Copyright © 2016 STAY REAL. All rights reserved.
//
import Cocoa
class StatusItemViewController: PlayerViewController {
// ========================
// MARK: - Static functions
// ========================
class func loadFromNib() -> StatusItemViewController {
let vc = NSStoryboard(name: "Main", bundle: nil).instantiateControllerWithIdentifier("StatusItemViewController") as! StatusItemViewController
return vc
}
// =========================
// MARK: - Lifecycle methods
// =========================
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
let manager = PlayerManager.sharedManager
volumeSlider.floatValue = manager.volume
if manager.isPlaying {
songTitleLabel.stringValue = manager.currentSong!.title
timeLabel.stringValue = manager.songProgressText
}
}
}
|
mit
|
d633bd9a29d0bf1c23efed51acd6312b
| 26.526316 | 149 | 0.585086 | 5.364103 | false | false | false | false |
ivanbruel/SwipeIt
|
Pods/KeychainSwift/KeychainSwift/KeychainSwift.swift
|
1
|
9215
|
import Security
import Foundation
/**
A collection of helper functions for saving text and data in the keychain.
*/
public class KeychainSwift {
var lastQueryParameters: [String: NSObject]? // Used by the unit tests
/// Contains result code from the last operation. Value is noErr (0) for a successful result.
public var lastResultCode: OSStatus = noErr
var keyPrefix = "" // Can be useful in test.
/**
Specify an access group that will be used to access keychain items. Access groups can be used to share keychain items between applications. When access group value is nil all application access groups are being accessed. Access group name is used by all functions: set, get, delete and clear.
*/
public var accessGroup: String?
/**
Specifies whether the items can be synchronized with other devices through iCloud. Setting this property to true will
add the item to other devices with the `set` method and obtain synchronizable items with the `get` command. Deleting synchronizable items will remove them from all devices. In order for keychain synchronization to work the user must enable "Keychain" in iCloud settings.
*/
public var synchronizable: Bool = false
/// Instantiate a KeychainSwift object
public init() { }
/**
- parameter keyPrefix: a prefix that is added before the key in get/set methods. Note that `clear` method still clears everything from the Keychain.
*/
public init(keyPrefix: String) {
self.keyPrefix = keyPrefix
}
/**
Stores the text value in the keychain item under the given key.
- parameter key: Key under which the text value is stored in the keychain.
- parameter value: Text string to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the text was successfully written to the keychain.
*/
public func set(value: String, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
if let value = value.dataUsingEncoding(NSUTF8StringEncoding) {
return set(value, forKey: key, withAccess: access)
}
return false
}
/**
Stores the data in the keychain item under the given key.
- parameter key: Key under which the data is stored in the keychain.
- parameter value: Data to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the text was successfully written to the keychain.
*/
public func set(value: NSData, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
delete(key) // Delete any existing key before saving it
let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value
let prefixedKey = keyWithPrefix(key)
var query = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey,
KeychainSwiftConstants.valueData : value,
KeychainSwiftConstants.accessible : accessible
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: true)
lastQueryParameters = query
lastResultCode = SecItemAdd(query as CFDictionaryRef, nil)
return lastResultCode == noErr
}
/**
Stores the boolean value in the keychain item under the given key.
- parameter key: Key under which the value is stored in the keychain.
- parameter value: Boolean to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the value in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the value was successfully written to the keychain.
*/
public func set(value: Bool, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
var localValue = value
let data = NSData(bytes: &localValue, length: sizeof(Bool))
return set(data, forKey: key, withAccess: access)
}
/**
Retrieves the text value from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The text value from the keychain. Returns nil if unable to read the item.
*/
public func get(key: String) -> String? {
if let data = getData(key) {
if let currentString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
return currentString
}
lastResultCode = -67853 // errSecInvalidEncoding
}
return nil
}
/**
Retrieves the data from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The text value from the keychain. Returns nil if unable to read the item.
*/
public func getData(key: String) -> NSData? {
let prefixedKey = keyWithPrefix(key)
var query: [String: NSObject] = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey,
KeychainSwiftConstants.returnData : kCFBooleanTrue,
KeychainSwiftConstants.matchLimit : kSecMatchLimitOne
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
var result: AnyObject?
lastResultCode = withUnsafeMutablePointer(&result) {
SecItemCopyMatching(query, UnsafeMutablePointer($0))
}
if lastResultCode == noErr { return result as? NSData }
return nil
}
/**
Retrieves the boolean value from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The boolean value from the keychain. Returns nil if unable to read the item.
*/
public func getBool(key: String) -> Bool? {
guard let data = getData(key) else { return nil }
var boolValue = false
data.getBytes(&boolValue, length: sizeof(Bool))
return boolValue
}
/**
Deletes the single keychain item specified by the key.
- parameter key: The key that is used to delete the keychain item.
- returns: True if the item was successfully deleted.
*/
public func delete(key: String) -> Bool {
let prefixedKey = keyWithPrefix(key)
var query: [String: NSObject] = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
lastResultCode = SecItemDelete(query as CFDictionaryRef)
return lastResultCode == noErr
}
/**
Deletes all Keychain items used by the app. Note that this method deletes all items regardless of the prefix settings used for initializing the class.
- returns: True if the keychain items were successfully deleted.
*/
public func clear() -> Bool {
var query: [String: NSObject] = [ kSecClass as String : kSecClassGenericPassword ]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
lastResultCode = SecItemDelete(query as CFDictionaryRef)
return lastResultCode == noErr
}
/// Returns the key with currently set prefix.
func keyWithPrefix(key: String) -> String {
return "\(keyPrefix)\(key)"
}
func addAccessGroupWhenPresent(items: [String: NSObject]) -> [String: NSObject] {
guard let accessGroup = accessGroup else { return items }
var result: [String: NSObject] = items
result[KeychainSwiftConstants.accessGroup] = accessGroup
return result
}
/**
Adds kSecAttrSynchronizable: kSecAttrSynchronizableAny` item to the dictionary when the `synchronizable` property is true.
- parameter items: The dictionary where the kSecAttrSynchronizable items will be added when requested.
- parameter addingItems: Use `true` when the dictionary will be used with `SecItemAdd` method (adding a keychain item). For getting and deleting items, use `false`.
- returns: the dictionary with kSecAttrSynchronizable item added if it was requested. Otherwise, it returns the original dictionary.
*/
func addSynchronizableIfRequired(items: [String: NSObject], addingItems: Bool) -> [String: NSObject] {
if !synchronizable { return items }
var result: [String: NSObject] = items
result[KeychainSwiftConstants.attrSynchronizable] = addingItems == true ? true : kSecAttrSynchronizableAny
return result
}
}
|
mit
|
1ab9fae3b0500c3a15f15bb588e249fa
| 34.175573 | 294 | 0.715681 | 5.125139 | false | false | false | false |
rudkx/swift
|
validation-test/compiler_crashers_2_fixed/0097-rdar32077627.swift
|
1
|
348
|
// RUN: not %target-swift-frontend -typecheck -primary-file %s -requirement-machine-inferred-signatures=verify -debug-generic-signatures 2>&1 | %FileCheck %s
// CHECK-LABEL: .hexEncodeBytes@
// CHECK-NEXT: <T where T : Collection, T.[Sequence]Element == UInt8>
func hexEncodeBytes<T: Collection>(_ bytes: T) where T.Generator.Element == UInt8 { }
|
apache-2.0
|
3c6a42ac2eb3bee189a451e24aa1ac76
| 68.6 | 157 | 0.732759 | 3.48 | false | false | false | false |
BenEmdon/swift-algorithm-club
|
Radix Sort/radixSort.swift
|
1
|
981
|
/*
Sorting Algorithm that sorts an input array of integers digit by digit.
*/
func radixSort(inout arr: [Int] ) {
let radix = 10 //Here we define our radix to be 10
var done = false
var index: Int
var digit = 1 //Which digit are we on?
while !done { //While our sorting is not completed
done = true //Assume it is done for now
var buckets: [[Int]] = [] //Our sorting subroutine is bucket sort, so let us predefine our buckets
for _ in 1...radix {
buckets.append([])
}
for number in arr {
index = number / digit //Which bucket will we access?
buckets[index % radix].append(number)
if done && index > 0 { //If we arent done, continue to finish, otherwise we are done
done = false
}
}
var i = 0
for j in 0..<radix {
let bucket = buckets[j]
for number in bucket {
arr[i] = number
i += 1
}
}
digit *= radix //Move to the next digit
}
}
|
mit
|
52ce1af9dec60284daefd6c0684f3855
| 19.87234 | 103 | 0.58104 | 3.802326 | false | false | false | false |
Lisergishnu/TetraVex
|
TetraVexKit/TVPuzzleGenerator.swift
|
1
|
2350
|
//
// PuzzleGenerator.swift
// TetraVex
//
// Created by Marco Benzi Tobar on 17-06-16.
// Copyright © 2016 Marco Benzi Tobar
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation (version 3)
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import Foundation
import GameplayKit
extension Int
{
public static func random(_ range: ClosedRange<Int>, randomSource: GKRandomSource ) -> Int
{
var offset = 0
if range.lowerBound < 0 // allow negative ranges
{
offset = abs(range.lowerBound)
}
let mini = Int(range.lowerBound + offset)
let maxi = Int(range.upperBound + offset)
return Int(mini + randomSource.nextInt(upperBound: maxi - mini)) - offset
}
}
open class TVPuzzleGenerator {
// MARK: - Properties
open var solvedBoard : [[TVPieceModel]]
var source : GKARC4RandomSource
// MARK: - Initialization
public init(width: Int, height: Int, rangeOfNumbers: ClosedRange<Int>, seed: Data? = nil){
if seed == nil {
self.source = GKARC4RandomSource()
} else {
self.source = GKARC4RandomSource(seed: seed!)
}
solvedBoard = Array(repeating: Array(repeating:TVPieceModel(top: 0, left: 0, bottom: 0, right: 0), count: width), count: width)
for i in 0..<width {
for j in 0..<height {
var p = solvedBoard[i][j]
if j > 0 {
p.bottomValue = (solvedBoard[i][j-1]).topValue
} else {
p.bottomValue = Int.random(rangeOfNumbers, randomSource: source)
}
if i > 0 {
p.leftValue = (solvedBoard[i-1][j]).rightValue
} else {
p.leftValue = Int.random(rangeOfNumbers, randomSource: source)
}
p.rightValue = Int.random(rangeOfNumbers, randomSource: source)
p.topValue = Int.random(rangeOfNumbers, randomSource: source)
solvedBoard[i][j] = p
}
}
}
}
|
gpl-3.0
|
3499ed8ffd2fd607cd918001afb3d25b
| 30.743243 | 131 | 0.65049 | 3.800971 | false | false | false | false |
papertigers/Dwifft
|
Dwifft/Dwifft.swift
|
2
|
5235
|
//
// LCS.swift
// Dwifft
//
// Created by Jack Flintermann on 3/14/15.
// Copyright (c) 2015 jflinter. All rights reserved.
//
public struct Diff<T> {
public let results: [DiffStep<T>]
public var insertions: [DiffStep<T>] {
return results.filter({ $0.isInsertion }).sorted { $0.idx < $1.idx }
}
public var deletions: [DiffStep<T>] {
return results.filter({ !$0.isInsertion }).sorted { $0.idx > $1.idx }
}
public func reversed() -> Diff<T> {
let reversedResults = self.results.reversed().map { (result: DiffStep<T>) -> DiffStep<T> in
switch result {
case .insert(let i, let j):
return .delete(i, j)
case .delete(let i, let j):
return .insert(i, j)
}
}
return Diff<T>(results: reversedResults)
}
}
public func +<T> (left: Diff<T>, right: DiffStep<T>) -> Diff<T> {
return Diff<T>(results: left.results + [right])
}
/// These get returned from calls to Array.diff(). They represent insertions or deletions that need to happen to transform array a into array b.
public enum DiffStep<T> : CustomDebugStringConvertible {
case insert(Int, T)
case delete(Int, T)
var isInsertion: Bool {
switch(self) {
case .insert:
return true
case .delete:
return false
}
}
public var debugDescription: String {
switch(self) {
case .insert(let i, let j):
return "+\(j)@\(i)"
case .delete(let i, let j):
return "-\(j)@\(i)"
}
}
public var idx: Int {
switch(self) {
case .insert(let i, _):
return i
case .delete(let i, _):
return i
}
}
public var value: T {
switch(self) {
case .insert(let j):
return j.1
case .delete(let j):
return j.1
}
}
}
public extension Array where Element: Equatable {
/// Returns the sequence of ArrayDiffResults required to transform one array into another.
public func diff(_ other: [Element]) -> Diff<Element> {
let table = MemoizedSequenceComparison.buildTable(self, other, self.count, other.count)
return Array.diffFromIndices(table, self, other, self.count, other.count)
}
/// Walks back through the generated table to generate the diff.
fileprivate static func diffFromIndices(_ table: [[Int]], _ x: [Element], _ y: [Element], _ i: Int, _ j: Int) -> Diff<Element> {
if i == 0 && j == 0 {
return Diff<Element>(results: [])
} else if i == 0 {
return diffFromIndices(table, x, y, i, j-1) + DiffStep.insert(j-1, y[j-1])
} else if j == 0 {
return diffFromIndices(table, x, y, i - 1, j) + DiffStep.delete(i-1, x[i-1])
} else if table[i][j] == table[i][j-1] {
return diffFromIndices(table, x, y, i, j-1) + DiffStep.insert(j-1, y[j-1])
} else if table[i][j] == table[i-1][j] {
return diffFromIndices(table, x, y, i - 1, j) + DiffStep.delete(i-1, x[i-1])
} else {
return diffFromIndices(table, x, y, i-1, j-1)
}
}
/// Applies a generated diff to an array. The following should always be true:
/// Given x: [T], y: [T], x.apply(x.diff(y)) == y
public func apply(_ diff: Diff<Element>) -> Array<Element> {
var copy = self
for result in diff.deletions {
copy.remove(at: result.idx)
}
for result in diff.insertions {
copy.insert(result.value, at: result.idx)
}
return copy
}
}
public extension Array where Element: Equatable {
/// Returns the longest common subsequence between two arrays.
public func LCS(_ other: [Element]) -> [Element] {
let table = MemoizedSequenceComparison.buildTable(self, other, self.count, other.count)
return Array.lcsFromIndices(table, self, other, self.count, other.count)
}
/// Walks back through the generated table to generate the LCS.
fileprivate static func lcsFromIndices(_ table: [[Int]], _ x: [Element], _ y: [Element], _ i: Int, _ j: Int) -> [Element] {
if i == 0 || j == 0 {
return []
} else if x[i-1] == y[j-1] {
return lcsFromIndices(table, x, y, i - 1, j - 1) + [x[i - 1]]
} else if table[i-1][j] > table[i][j-1] {
return lcsFromIndices(table, x, y, i - 1, j)
} else {
return lcsFromIndices(table, x, y, i, j - 1)
}
}
}
internal struct MemoizedSequenceComparison<T: Equatable> {
static func buildTable(_ x: [T], _ y: [T], _ n: Int, _ m: Int) -> [[Int]] {
var table = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1)
for i in 0...n {
for j in 0...m {
if (i == 0 || j == 0) {
table[i][j] = 0
}
else if x[i-1] == y[j-1] {
table[i][j] = table[i-1][j-1] + 1
} else {
table[i][j] = max(table[i-1][j], table[i][j-1])
}
}
}
return table
}
}
|
mit
|
9273e7fa6f31d87fcc5f270868bdf68f
| 33.440789 | 144 | 0.528558 | 3.52288 | false | false | false | false |
curiousurick/BluetoothBackupSensor-iOS
|
CSS427Bluefruit_Connect/BLE Test/MqttSettingsViewController.swift
|
4
|
21831
|
//
// MqttSettingsViewController.swift
// Adafruit Bluefruit LE Connect
//
// Created by Antonio García on 28/07/15.
// Copyright (c) 2015 Adafruit Industries. All rights reserved.
//
import UIKit
class MqttSettingsViewController: KeyboardAwareViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource, MqttManagerDelegate {
// Constants
private static let defaultHeaderCellHeight : CGFloat = 50;
// UI
@IBOutlet weak var baseTableView: UITableView!
@IBOutlet var pickerView: UIPickerView!
@IBOutlet var pickerToolbar: UIToolbar!
// Data
private enum SettingsSections : Int {
case Status = 0
case Server = 1
case Publish = 2
case Subscribe = 3
case Advanced = 4
}
private enum PickerViewType {
case Qos
case Action
}
private var selectedIndexPath = NSIndexPath(forRow: 0, inSection: 0)
private var pickerViewType = PickerViewType.Qos
private var previousSubscriptionTopic : String?
//
override func viewDidLoad() {
super.viewDidLoad()
self.title = "MQTT Settings"
// Register custom cell nibs
baseTableView.registerNib(UINib(nibName: "MqttSettingsHeaderCell", bundle: nil), forCellReuseIdentifier: "HeaderCell")
baseTableView.registerNib(UINib(nibName: "MqttSettingsStatusCell", bundle: nil), forCellReuseIdentifier: "StatusCell")
baseTableView.registerNib(UINib(nibName: "MqttSettingsEditValueCell", bundle: nil), forCellReuseIdentifier: "EditValueCell")
baseTableView.registerNib(UINib(nibName: "MqttSettingsEditValuePickerCell", bundle: nil), forCellReuseIdentifier: "EditValuePickerCell")
baseTableView.registerNib(UINib(nibName: "MqttSettingsEditPickerCell", bundle: nil), forCellReuseIdentifier: "EditPickerCell")
// Note: baseTableView is grouped to make the section titles no to overlap the section rows
baseTableView.backgroundColor = UIColor.clearColor()
previousSubscriptionTopic = MqttSettings.sharedInstance.subscribeTopic
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
MqttManager.sharedInstance.delegate = self
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if (IS_IPAD) {
self.view.endEditing(true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func headerTitleForSection(section: Int) -> String? {
switch(section) {
case SettingsSections.Status.rawValue: return nil
case SettingsSections.Server.rawValue: return "Server"
case SettingsSections.Publish.rawValue: return "Publish"
case SettingsSections.Subscribe.rawValue: return "Subscribe"
case SettingsSections.Advanced.rawValue: return "Advanced"
default: return nil
}
}
func subscriptionTopicChanged(newTopic: String?, qos: MqttManager.MqttQos) {
printLog(self, funcName: (__FUNCTION__), logString: "subscription changed from: \(previousSubscriptionTopic) to: \(newTopic)");
let mqttManager = MqttManager.sharedInstance
if (previousSubscriptionTopic != nil) {
mqttManager.unsubscribe(previousSubscriptionTopic!)
}
if (newTopic != nil) {
mqttManager.subscribe(newTopic!, qos: qos)
}
previousSubscriptionTopic = newTopic
}
func indexPathFromTag(tag: Int) -> NSIndexPath {
// To help identify each textfield a tag is added with this format: 12 (1 is the section, 2 is the row)
return NSIndexPath(forRow: tag % 10, inSection: tag / 10)
}
func tagFromIndexPath(indexPath : NSIndexPath) -> Int {
// To help identify each textfield a tag is added with this format: 12 (1 is the section, 2 is the row)
return indexPath.section * 10 + indexPath.row
}
// MARK: - UITableViewDelegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return SettingsSections.Advanced.rawValue + 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch(section) {
case SettingsSections.Status.rawValue: return 1
case SettingsSections.Server.rawValue: return 2
case SettingsSections.Publish.rawValue: return 2
case SettingsSections.Subscribe.rawValue: return 2
case SettingsSections.Advanced.rawValue: return 2
default: return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let section = indexPath.section
let row = indexPath.row;
let cell : UITableViewCell
if(section == SettingsSections.Status.rawValue) {
let statusCell = tableView.dequeueReusableCellWithIdentifier("StatusCell", forIndexPath: indexPath) as! MqttSettingsStatusCell
let status = MqttManager.sharedInstance.status
let showWait = status == .Connecting || status == .Disconnecting
if (showWait) {
statusCell.waitView.startAnimating()
}else {
statusCell.waitView.stopAnimating()
}
statusCell.actionButton.hidden = showWait
let statusText : String;
switch(status) {
case .Connected: statusText = "Connected"
case .Connecting: statusText = "Connecting..."
case .Disconnecting: statusText = "Disconnecting..."
case .Error: statusText = "Error"
default: statusText = "Disconnected"
}
statusCell.statusLabel.text = statusText
UIView.performWithoutAnimation({ () -> Void in // Change title disabling animations (if enabled the user can see the old title for a moment)
statusCell.actionButton.setTitle(status == .Connected ?"Disconnect":"Connect", forState: UIControlState.Normal)
statusCell.layoutIfNeeded()
})
statusCell.onClickAction = {
[unowned self] in
// End editing
self.view.endEditing(true)
// Connect / Disconnect
let mqttManager = MqttManager.sharedInstance
let status = mqttManager.status
if (status == .Disconnected || status == .None || status == .Error) {
mqttManager.connectFromSavedSettings()
} else {
mqttManager.disconnect()
MqttSettings.sharedInstance.isConnected = false
}
self.baseTableView?.reloadData()
}
cell = statusCell
}
else {
let mqttSettings = MqttSettings.sharedInstance
let editValueCell : MqttSettingsEditValueCell
switch(section) {
case SettingsSections.Server.rawValue:
editValueCell = tableView.dequeueReusableCellWithIdentifier("EditValueCell", forIndexPath: indexPath) as! MqttSettingsEditValueCell
editValueCell.reset()
let labels = ["Address:", "Port:"]
editValueCell.nameLabel.text = labels[row]
let valueTextField = editValueCell.valueTextField! // valueTextField should exist on this cell
if (row == 0) {
valueTextField.text = mqttSettings.serverAddress
}
else if (row == 1) {
valueTextField.placeholder = "\(MqttSettings.defaultServerPort)"
if (mqttSettings.serverPort != MqttSettings.defaultServerPort) {
valueTextField.text = "\(mqttSettings.serverPort)"
}
valueTextField.keyboardType = UIKeyboardType.NumberPad;
}
case SettingsSections.Publish.rawValue:
editValueCell = tableView.dequeueReusableCellWithIdentifier("EditValuePickerCell", forIndexPath: indexPath) as! MqttSettingsEditValueCell
editValueCell.reset()
let labels = ["UART RX:", "UART TX:"]
editValueCell.nameLabel.text = labels[row]
let valueTextField = editValueCell.valueTextField!
valueTextField.text = mqttSettings.getPublishTopic(row)
let typeTextField = editValueCell.typeTextField!
typeTextField.text = titleForQos(mqttSettings.getPublishQos(row))
setupTextFieldForPickerInput(typeTextField, indexPath: indexPath)
case SettingsSections.Subscribe.rawValue:
editValueCell = tableView.dequeueReusableCellWithIdentifier(row==0 ? "EditValuePickerCell":"EditPickerCell", forIndexPath: indexPath) as! MqttSettingsEditValueCell
editValueCell.reset()
let labels = ["Topic:", "Action:"]
editValueCell.nameLabel.text = labels[row]
let typeTextField = editValueCell.typeTextField!
if (row == 0) {
let valueTextField = editValueCell.valueTextField!
valueTextField.text = mqttSettings.subscribeTopic
typeTextField.text = titleForQos(mqttSettings.subscribeQos)
setupTextFieldForPickerInput(typeTextField, indexPath: indexPath)
}
else if (row == 1) {
typeTextField.text = titleForSubscribeBehaviour(mqttSettings.subscribeBehaviour)
setupTextFieldForPickerInput(typeTextField, indexPath: indexPath)
}
case SettingsSections.Advanced.rawValue:
editValueCell = tableView.dequeueReusableCellWithIdentifier("EditValueCell", forIndexPath: indexPath) as! MqttSettingsEditValueCell
editValueCell.reset()
let labels = ["Username:", "Password:"]
editValueCell.nameLabel.text = labels[row]
let valueTextField = editValueCell.valueTextField!
if (row == 0) {
valueTextField.text = mqttSettings.username
}
else if (row == 1) {
valueTextField.text = mqttSettings.password
}
default:
editValueCell = tableView.dequeueReusableCellWithIdentifier("EditValueCell", forIndexPath: indexPath) as! MqttSettingsEditValueCell
editValueCell.reset()
break;
}
if let valueTextField = editValueCell.valueTextField {
valueTextField.returnKeyType = UIReturnKeyType.Next
valueTextField.delegate = self;
valueTextField.tag = tagFromIndexPath(indexPath)
}
cell = editValueCell
}
return cell
}
func setupTextFieldForPickerInput(textField : UITextField, indexPath : NSIndexPath) {
textField.inputView = pickerView
textField.inputAccessoryView = pickerToolbar
textField.delegate = self
textField.tag = tagFromIndexPath(indexPath);
textField.textColor = self.view.tintColor
textField.tintColor = UIColor.clearColor() // remove caret
}
func titleForSubscribeBehaviour(behaviour: MqttSettings.SubscribeBehaviour) -> String {
switch(behaviour) {
case .LocalOnly: return "Local Only"
case .Transmit: return "Transmit"
}
}
func titleForQos(qos: MqttManager.MqttQos) -> String {
switch(qos) {
case .AtLeastOnce : return "At Least Once"
case .AtMostOnce : return "At Most Once"
case .ExactlyOnce : return "Exactly Once"
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.backgroundColor = UIColor.clearColor()
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! MqttSettingsHeaderCell
headerCell.backgroundColor = UIColor.clearColor()
headerCell.nameLabel.text = headerTitleForSection(section)
let hasSwitch = section == SettingsSections.Publish.rawValue || section == SettingsSections.Subscribe.rawValue;
headerCell.isOnSwitch.hidden = !hasSwitch;
if (hasSwitch) {
let mqttSettings = MqttSettings.sharedInstance;
if (section == SettingsSections.Publish.rawValue) {
headerCell.isOnSwitch.on = mqttSettings.isPublishEnabled
headerCell.isOnChanged = { isOn in
mqttSettings.isPublishEnabled = isOn;
}
}
else if (section == SettingsSections.Subscribe.rawValue) {
headerCell.isOnSwitch.on = mqttSettings.isSubscribeEnabled
headerCell.isOnChanged = { [unowned self] isOn in
mqttSettings.isSubscribeEnabled = isOn;
self.subscriptionTopicChanged(nil, qos: mqttSettings.subscribeQos)
}
}
}
return headerCell;
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if (headerTitleForSection(section) == nil) {
UITableViewAutomaticDimension
return 0.5; // no title, so 0 height (hack: set to 0.5 because 0 height is not correctly displayed)
}
else {
return MqttSettingsViewController.defaultHeaderCellHeight;
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Focus on textfield if present
if let editValueCell = tableView.cellForRowAtIndexPath(indexPath) as? MqttSettingsEditValueCell {
editValueCell.valueTextField?.becomeFirstResponder()
}
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Go to next textField
if (textField.returnKeyType == UIReturnKeyType.Next) {
let tag = textField.tag;
var nextView = baseTableView.viewWithTag(tag+1)
if (nextView == nil || nextView!.inputView != nil) {
nextView = baseTableView.viewWithTag(((tag/10)+1)*10)
}
if let next = nextView {
next.becomeFirstResponder()
// Scroll to show it
baseTableView.scrollToRowAtIndexPath(indexPathFromTag(next.tag), atScrollPosition: .Middle, animated: true)
}
else {
textField.resignFirstResponder()
}
}
return true;
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
// Update selected indexpath
selectedIndexPath = indexPathFromTag(textField.tag)
// Setup inputView if needed
if (textField.inputView != nil) {
// Setup valueTextField
let isAction = selectedIndexPath.section == SettingsSections.Subscribe.rawValue && selectedIndexPath.row == 1
pickerViewType = isAction ? PickerViewType.Action:PickerViewType.Qos
pickerView .reloadAllComponents()
pickerView.tag = textField.tag // pass the current textfield tag to the pickerView
//pickerView.selectRow(<#row: Int#>, inComponent: 0, animated: false)
}
return true;
}
func textFieldDidEndEditing(textField: UITextField) {
if (textField.inputView == nil) { // textfields with input view are not managed here
let indexPath = indexPathFromTag(textField.tag)
let section = indexPath.section
let row = indexPath.row
let mqttSettings = MqttSettings.sharedInstance;
// Update settings with new values
switch(section) {
case SettingsSections.Server.rawValue:
if (row == 0) { // Server Address
mqttSettings.serverAddress = textField.text
}
else if (row == 1) { // Server Port
if let port = Int(textField.text!) {
mqttSettings.serverPort = port
}
else {
textField.text = nil;
mqttSettings.serverPort = MqttSettings.defaultServerPort
}
}
case SettingsSections.Publish.rawValue:
mqttSettings.setPublishTopic(row, topic: textField.text)
case SettingsSections.Subscribe.rawValue:
let topic = textField.text
mqttSettings.subscribeTopic = topic
subscriptionTopicChanged(topic, qos: mqttSettings.subscribeQos)
case SettingsSections.Advanced.rawValue:
if (row == 0) { // Username
mqttSettings.username = textField.text;
}
else if (row == 1) { // Password
mqttSettings.password = textField.text;
}
default:
break;
}
}
}
// MARK: - KeyboardAwareViewController
override func keyboardPositionChanged(keyboardFrame : CGRect, keyboardShown : Bool) {
super.keyboardPositionChanged(keyboardFrame, keyboardShown:keyboardShown )
if (IS_IPHONE) {
let height = keyboardFrame.height
baseTableView.contentInset = UIEdgeInsetsMake(0, 0, height, 0);
}
//printLog(self, (__FUNCTION__), "keyboard size: \(height) appearing: \(keyboardShown)");
if (keyboardShown) {
baseTableView.scrollToRowAtIndexPath(selectedIndexPath, atScrollPosition: .Middle, animated: true)
}
}
// MARK: - Input Toolbar
@IBAction func onClickInputToolbarDone(sender: AnyObject) {
let selectedPickerRow = pickerView.selectedRowInComponent(0);
let indexPath = indexPathFromTag(pickerView.tag)
let section = indexPath.section
let row = indexPath.row
let mqttSettings = MqttSettings.sharedInstance;
// Update settings with new values
switch(section) {
case SettingsSections.Publish.rawValue:
mqttSettings.setPublishQos(row, qos: MqttManager.MqttQos(rawValue: selectedPickerRow)!)
case SettingsSections.Subscribe.rawValue:
if (row == 0) { // Topic Qos
let qos = MqttManager.MqttQos(rawValue: selectedPickerRow)!
mqttSettings.subscribeQos = qos
subscriptionTopicChanged(mqttSettings.subscribeTopic, qos: qos)
}
else if (row == 1) { // Action
mqttSettings.subscribeBehaviour = MqttSettings.SubscribeBehaviour(rawValue: selectedPickerRow)!
}
default:
break;
}
// End editing
self.view.endEditing(true)
baseTableView.reloadData() // refresh values
}
// MARK: - UIPickerViewDataSource
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerViewType == .Action ? 2:3
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
// let labels : [String];
switch(pickerViewType) {
case .Qos:
return titleForQos(MqttManager.MqttQos(rawValue: row)!)
case .Action:
return titleForSubscribeBehaviour(MqttSettings.SubscribeBehaviour(rawValue: row)!)
}
}
// MARK: UIPickerViewDelegate
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
// MARK: - MqttManagerDelegate
func onMqttConnected() {
// Update status
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
self.baseTableView.reloadData()
})
}
func onMqttDisconnected() {
// Update status
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
self.baseTableView.reloadData()
})
}
func onMqttMessageReceived(message : String, topic: String) {
}
func onMqttError(message : String) {
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
let alert = UIAlertController(title:"Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
// Update status
self.baseTableView.reloadData()
})
}
}
|
mit
|
0a4b885ad79c5cda6be142b5cc58d76a
| 39.202578 | 195 | 0.60426 | 5.627739 | false | false | false | false |
julienbodet/wikipedia-ios
|
WMF Framework/ReadingList+JSON.swift
|
5
|
1915
|
import Foundation
extension ReadingList {
@objc public static let conflictingReadingListNameUpdatedNotification = NSNotification.Name(rawValue: "WMFConflictingReadingListNameUpdatedNotification")
@objc public static let conflictingReadingListNameUpdatedOldNameKey = NSNotification.Name(rawValue: "oldName")
@objc public static let conflictingReadingListNameUpdatedNewNameKey = NSNotification.Name(rawValue: "newName")
func update(with remoteList: APIReadingList) {
self.readingListID = NSNumber(value: remoteList.id)
if remoteList.name == CommonStrings.readingListsDefaultListTitle {
let userCreatedAnnotation = WMFLocalizedString("reading-list-name-user-created-annotation", value: "_[user created]", comment: "Annotation added to a conflicting reading list name")
let newName = String.localizedStringWithFormat("%1$@%2$@", remoteList.name, userCreatedAnnotation)
if newName != self.name {
let userInfo = [ReadingList.conflictingReadingListNameUpdatedOldNameKey: remoteList.name, ReadingList.conflictingReadingListNameUpdatedNewNameKey: newName]
NotificationCenter.default.post(name: ReadingList.conflictingReadingListNameUpdatedNotification, object: nil, userInfo: userInfo)
}
self.name = newName
} else {
self.name = remoteList.name
}
self.readingListDescription = remoteList.description
if let createdDate = DateFormatter.wmf_iso8601().date(from: remoteList.created) {
self.createdDate = createdDate as NSDate
}
if let updatedDate = DateFormatter.wmf_iso8601().date(from: remoteList.updated) {
self.updatedDate = updatedDate as NSDate
}
if remoteList.isDefault && !isDefault {
isDefault = true
}
errorCode = nil
isUpdatedLocally = false
}
}
|
mit
|
a22c9bc25b0a5cfb24d97765d340b2e6
| 55.323529 | 193 | 0.707572 | 5.23224 | false | false | false | false |
winkelsdorf/SearchControllerTraitBug
|
SearchControllerTraitBugDemo/MasterViewController.swift
|
1
|
3949
|
//
// MasterViewController.swift
// SearchControllerTraitBugDemo
//
// Created by Frederik Winkelsdorf on 03/02/2017.
// Copyright © 2017 Frederik Winkelsdorf. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
var searchController: UISearchController!
var detailViewController: DetailViewController? = nil
var objects: [Any] = []
var searchResults: [Any] = []
override func viewDidLoad() {
super.viewDidLoad()
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
// Added:
configureSearchController()
definesPresentationContext = true // fixes SearchBar overlapping Detail
}
func configureSearchController() {
searchController = UISearchController(searchResultsController: nil) // nil = use this controller for results
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
tableView.tableHeaderView = searchController.searchBar
// Bugfix: The search bar does not set its size automatically which causes it to have zero
// height when there is no scope bar. If you remove the scopeButtonTitles above and the
// search bar is no longer visible make sure you force the search bar to size itself (make
// sure you do this after you add it to the view hierarchy).
searchController.searchBar.sizeToFit()
}
override func viewWillAppear(_ animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
func insertNewObject(_ sender: Any) {
objects.insert(NSDate(), at: 0)
let indexPath = IndexPath(row: 0, section: 0)
self.tableView.insertRows(at: [indexPath], with: .automatic)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
// MARK: - Search
func updateSearchResults(for searchController: UISearchController) {
guard let searchString = searchController.searchBar.text?.lowercased() else { return }
if !searchString.isEmpty {
searchResults = []
} else {
searchResults = []
}
tableView.reloadData()
}
}
|
mit
|
9c630a4a22bff188a9a05ac25c1ae279
| 35.897196 | 144 | 0.686677 | 5.69697 | false | false | false | false |
iguchunhui/protobuf-swift
|
src/ProtocolBuffers/runtime-pb-swift/UnknownFieldSet.swift
|
3
|
12345
|
// Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public func == (lhs: UnknownFieldSet, rhs: UnknownFieldSet) -> Bool
{
return lhs.fields == rhs.fields
}
public class UnknownFieldSet:Hashable,Equatable
{
public var fields:Dictionary<Int32,Field>
convenience public init()
{
self.init(fields: Dictionary())
}
public init(fields:Dictionary<Int32,Field>)
{
self.fields = fields
}
public var hashValue:Int
{
get {
var hashCode:Int = 0
for value in fields.values
{
hashCode = (hashCode &* 31) &+ value.hashValue
}
return hashCode
}
}
public func hasField(number:Int32) -> Bool
{
guard fields[number] != nil else
{
return false
}
return true
}
public func getField(number:Int32) -> Field
{
if let field = fields[number]
{
return field
}
return Field()
}
public func writeToCodedOutputStream(output:CodedOutputStream) throws
{
var sortedKeys = Array(fields.keys)
sortedKeys.sortInPlace { $0 < $1 }
for number in sortedKeys
{
let value:Field = fields[number]!
try value.writeTo(number, output: output)
}
}
public func writeToOutputStream(output:NSOutputStream) throws
{
let codedOutput:CodedOutputStream = CodedOutputStream(output: output)
try writeToCodedOutputStream(codedOutput)
try codedOutput.flush()
}
public func writeDescriptionTo(inout output:String, indent:String)
{
var sortedKeys = Array(fields.keys)
sortedKeys.sortInPlace { $0 < $1 }
for number in sortedKeys
{
let value:Field = fields[number]!
value.writeDescriptionFor(number, outputString: &output, indent: indent)
}
}
public class func builder() -> UnknownFieldSet.Builder {
return UnknownFieldSet.Builder()
}
public class func parseFromCodedInputStream(input:CodedInputStream) throws -> UnknownFieldSet {
return try UnknownFieldSet.Builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromData(data:NSData) throws -> UnknownFieldSet {
return try UnknownFieldSet.Builder().mergeFromData(data).build()
}
public class func parseFromInputStream(input:NSInputStream) throws -> UnknownFieldSet
{
return try UnknownFieldSet.Builder().mergeFromInputStream(input).build()
}
public class func builderWithUnknownFields(copyFrom:UnknownFieldSet) throws -> UnknownFieldSet.Builder
{
return try UnknownFieldSet.Builder().mergeUnknownFields(copyFrom)
}
public func serializedSize()->Int32
{
var result:Int32 = 0
for number in fields.keys
{
let field:Field = fields[number]!
result += field.getSerializedSize(number)
}
return result
}
public func writeAsMessageSetTo(output:CodedOutputStream) throws
{
for number in fields.keys
{
let field:Field = fields[number]!
try field.writeAsMessageSetExtensionTo(number, output:output)
}
}
public func serializedSizeAsMessageSet() -> Int32
{
var result:Int32 = 0
for number in fields.keys
{
let field:Field = fields[number]!
result += field.getSerializedSizeAsMessageSetExtension(number)
}
return result
}
public func data() throws -> NSData
{
let size = serializedSize()
let data = NSMutableData(length: Int(size))!
let stream:CodedOutputStream = CodedOutputStream(data: data)
try writeToCodedOutputStream(stream)
return stream.buffer.buffer
}
public class Builder
{
private var fields:Dictionary<Int32,Field>
private var lastFieldNumber:Int32
private var lastField:Field?
public init()
{
fields = Dictionary()
lastFieldNumber = 0
}
public func addField(field:Field, number:Int32) throws -> UnknownFieldSet.Builder {
guard number != 0 else
{
throw ProtocolBuffersError.IllegalArgument("Illegal Field Number")
}
if (lastField != nil && lastFieldNumber == number) {
lastField = nil
lastFieldNumber = 0
}
fields[number]=field
return self
}
public func getFieldBuilder(number:Int32) throws -> Field?
{
if (lastField != nil) {
if (number == lastFieldNumber) {
return lastField
}
try addField(lastField!, number:lastFieldNumber)
}
if (number == 0)
{
return nil
}
else
{
let existing = fields[number]
lastFieldNumber = number
lastField = Field()
if (existing != nil) {
lastField?.mergeFromField(existing!)
}
return lastField
}
}
public func build() throws -> UnknownFieldSet
{
try getFieldBuilder(0)
var result:UnknownFieldSet
if (fields.count == 0) {
result = UnknownFieldSet(fields: Dictionary())
}
else
{
result = UnknownFieldSet(fields: fields)
}
fields.removeAll(keepCapacity: false)
return result
}
public func buildPartial() throws -> UnknownFieldSet?
{
throw ProtocolBuffersError.Obvious("UnsupportedMethod")
}
public func clone() throws -> UnknownFieldSet?
{
throw ProtocolBuffersError.Obvious("UnsupportedMethod")
}
public func isInitialized() -> Bool
{
return true
}
public func unknownFields() throws -> UnknownFieldSet {
return try build()
}
public func setUnknownFields(unknownFields:UnknownFieldSet) throws -> UnknownFieldSet.Builder?
{
throw ProtocolBuffersError.Obvious("UnsupportedMethod")
}
public func hasField(number:Int32) throws -> Bool
{
guard number != 0 else
{
throw ProtocolBuffersError.IllegalArgument("Illegal Field Number")
}
return number == lastFieldNumber || (fields[number] != nil)
}
public func mergeField(field:Field, number:Int32) throws -> UnknownFieldSet.Builder
{
guard number != 0 else
{
throw ProtocolBuffersError.IllegalArgument("Illegal Field Number")
}
if (try hasField(number)) {
try getFieldBuilder(number)?.mergeFromField(field)
}
else
{
try addField(field, number:number)
}
return self
}
public func mergeUnknownFields(other:UnknownFieldSet) throws -> UnknownFieldSet.Builder
{
for number in other.fields.keys
{
let field:Field = other.fields[number]!
try mergeField(field ,number:number)
}
return self
}
public func mergeFromData(data:NSData) throws -> UnknownFieldSet.Builder
{
let input:CodedInputStream = CodedInputStream(data: data)
try mergeFromCodedInputStream(input)
try input.checkLastTagWas(0)
return self
}
public func mergeFromInputStream(input:NSInputStream) throws -> UnknownFieldSet.Builder
{
throw ProtocolBuffersError.Obvious("UnsupportedMethod")
}
public func mergeFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> UnknownFieldSet.Builder
{
throw ProtocolBuffersError.Obvious("UnsupportedMethod")
}
public func mergeVarintField(number:Int32, value:Int64) throws -> UnknownFieldSet.Builder
{
guard number != 0 else
{
throw ProtocolBuffersError.IllegalArgument("Illegal Field Number: Zero is not a valid field number.")
}
try getFieldBuilder(number)?.variantArray.append(value)
return self
}
public func mergeFieldFrom(tag:Int32, input:CodedInputStream) throws -> Bool
{
let number = WireFormat.getTagFieldNumber(tag)
let tags = WireFormat.getTagWireType(tag)
let format:WireFormat? = WireFormat(rawValue: tags)
guard let _ = format else {
throw ProtocolBuffersError.InvalidProtocolBuffer("Invalid Wire Type")
}
switch format! {
case .Varint:
try getFieldBuilder(number)?.variantArray.append(try input.readInt64())
return true
case .Fixed32:
let value = try input.readFixed32()
try getFieldBuilder(number)?.fixed32Array.append(value)
return true
case .Fixed64:
let value = try input.readFixed64()
try getFieldBuilder(number)?.fixed64Array.append(value)
return true
case .LengthDelimited:
try getFieldBuilder(number)?.lengthDelimited.append(try input.readData())
return true
case .StartGroup:
let subBuilder:UnknownFieldSet.Builder = UnknownFieldSet.Builder()
try input.readUnknownGroup(number, builder:subBuilder)
try getFieldBuilder(number)?.groupArray.append(subBuilder.build())
return true
case .EndGroup:
return false
default:
throw ProtocolBuffersError.InvalidProtocolBuffer("Invalid Wire Type")
}
}
public func mergeFromCodedInputStream(input:CodedInputStream) throws -> UnknownFieldSet.Builder {
while (true) {
let tag:Int32 = try input.readTag()
let mergeField = try mergeFieldFrom(tag, input:input)
if tag == 0 || !(mergeField)
{
break
}
}
return self
}
public func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> UnknownFieldSet.Builder
{
throw ProtocolBuffersError.Obvious("UnsupportedMethod")
}
public func mergeFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> UnknownFieldSet.Builder
{
let input = CodedInputStream(data: data)
try mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry)
try input.checkLastTagWas(0)
return self
}
public func clear() ->UnknownFieldSet.Builder
{
fields = Dictionary()
lastFieldNumber = 0
lastField = nil
return self
}
}
}
|
apache-2.0
|
883bcfa0a2c25bdca0990fdeca27ef04
| 31.401575 | 140 | 0.566059 | 5.565825 | false | false | false | false |
tkremenek/swift
|
test/decl/ext/protocol.swift
|
5
|
25220
|
// RUN: %target-typecheck-verify-swift
// ----------------------------------------------------------------------------
// Using protocol requirements from inside protocol extensions
// ----------------------------------------------------------------------------
protocol P1 {
@discardableResult
func reqP1a() -> Bool
}
extension P1 {
func extP1a() -> Bool { return !reqP1a() }
var extP1b: Bool {
return self.reqP1a()
}
var extP1c: Bool {
return extP1b && self.extP1a()
}
}
protocol P2 {
associatedtype AssocP2 : P1
func reqP2a() -> AssocP2
}
extension P2 {
func extP2a() -> AssocP2? { return reqP2a() }
func extP2b() {
self.reqP2a().reqP1a()
}
func extP2c() -> Self.AssocP2 { return extP2a()! }
}
protocol P3 {
associatedtype AssocP3 : P2
func reqP3a() -> AssocP3
}
extension P3 {
func extP3a() -> AssocP3.AssocP2 {
return reqP3a().reqP2a()
}
}
protocol P4 {
associatedtype AssocP4
func reqP4a() -> AssocP4
}
// ----------------------------------------------------------------------------
// Using generics from inside protocol extensions
// ----------------------------------------------------------------------------
func acceptsP1<T : P1>(_ t: T) { }
extension P1 {
func extP1d() { acceptsP1(self) }
}
func acceptsP2<T : P2>(_ t: T) { }
extension P2 {
func extP2acceptsP1() { acceptsP1(reqP2a()) }
func extP2acceptsP2() { acceptsP2(self) }
}
// Use of 'Self' as a return type within a protocol extension.
protocol SelfP1 {
associatedtype AssocType
}
protocol SelfP2 {
}
func acceptSelfP1<T, U : SelfP1>(_ t: T, _ u: U) -> T where U.AssocType == T {
return t
}
extension SelfP1 {
func tryAcceptSelfP1<Z : SelfP1>(_ z: Z)-> Self where Z.AssocType == Self {
return acceptSelfP1(self, z)
}
}
// ----------------------------------------------------------------------------
// Initializers in protocol extensions
// ----------------------------------------------------------------------------
protocol InitP1 {
init(string: String)
}
extension InitP1 {
init(int: Int) { self.init(string: "integer") }
}
struct InitS1 : InitP1 {
init(string: String) { }
}
class InitC1 : InitP1 {
required init(string: String) { }
}
func testInitP1() {
var is1 = InitS1(int: 5)
is1 = InitS1(string: "blah") // check type
_ = is1
var ic1 = InitC1(int: 5)
ic1 = InitC1(string: "blah") // check type
_ = ic1
}
// ----------------------------------------------------------------------------
// Subscript in protocol extensions
// ----------------------------------------------------------------------------
protocol SubscriptP1 {
func readAt(_ i: Int) -> String
func writeAt(_ i: Int, string: String)
}
extension SubscriptP1 {
subscript(i: Int) -> String {
get { return readAt(i) }
set(newValue) { writeAt(i, string: newValue) }
}
}
struct SubscriptS1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
struct SubscriptC1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
func testSubscriptP1(_ ss1: SubscriptS1, sc1: SubscriptC1,
i: Int, s: String) {
var ss1 = ss1
var sc1 = sc1
_ = ss1[i]
ss1[i] = s
_ = sc1[i]
sc1[i] = s
}
// ----------------------------------------------------------------------------
// Using protocol extensions on types that conform to the protocols.
// ----------------------------------------------------------------------------
struct S1 : P1 {
@discardableResult
func reqP1a() -> Bool { return true }
func once() -> Bool {
return extP1a() && extP1b
}
}
func useS1(_ s1: S1) -> Bool {
s1.reqP1a()
return s1.extP1a() && s1.extP1b
}
extension S1 {
func twice() -> Bool {
return extP1a() && extP1b
}
}
// ----------------------------------------------------------------------------
// Protocol extensions with redundant requirements
// ----------------------------------------------------------------------------
protocol FooProtocol {}
extension FooProtocol where Self: FooProtocol {} // expected-warning {{requirement of 'Self' to 'FooProtocol' is redundant in an extension of 'FooProtocol'}}
protocol AnotherFooProtocol {}
protocol BazProtocol {}
extension AnotherFooProtocol where Self: BazProtocol, Self: AnotherFooProtocol {} // expected-warning {{requirement of 'Self' to 'AnotherFooProtocol' is redundant in an extension of 'AnotherFooProtocol'}}
protocol AnotherBazProtocol {
associatedtype BazValue
}
extension AnotherBazProtocol where BazValue: AnotherBazProtocol {} // ok, does not warn because BazValue is not Self
// ----------------------------------------------------------------------------
// Protocol extensions with additional requirements
// ----------------------------------------------------------------------------
extension P4 where Self.AssocP4 : P1 {
// expected-note@-1 {{candidate requires that 'Int' conform to 'P1' (requirement specified as 'Self.AssocP4' : 'P1')}}
// expected-note@-2 {{candidate requires that 'S4aHelper' conform to 'P1' (requirement specified as 'Self.AssocP4' : 'P1')}}
func extP4a() {
acceptsP1(reqP4a())
}
}
struct S4aHelper { }
struct S4bHelper : P1 {
func reqP1a() -> Bool { return true }
}
struct S4a : P4 {
func reqP4a() -> S4aHelper { return S4aHelper() }
}
struct S4b : P4 {
func reqP4a() -> S4bHelper { return S4bHelper() }
}
struct S4c : P4 {
func reqP4a() -> Int { return 0 }
}
struct S4d : P4 {
func reqP4a() -> Bool { return false }
}
extension P4 where Self.AssocP4 == Int { // expected-note {{where 'Self.AssocP4' = 'Bool'}}
func extP4Int() { }
}
extension P4 where Self.AssocP4 == Bool {
// expected-note@-1 {{candidate requires that the types 'Int' and 'Bool' be equivalent (requirement specified as 'Self.AssocP4' == 'Bool')}}
// expected-note@-2 {{candidate requires that the types 'S4aHelper' and 'Bool' be equivalent (requirement specified as 'Self.AssocP4' == 'Bool')}}
func extP4a() -> Bool { return reqP4a() }
}
func testP4(_ s4a: S4a, s4b: S4b, s4c: S4c, s4d: S4d) {
s4a.extP4a() // expected-error{{no exact matches in call to instance method 'extP4a'}}
s4b.extP4a() // ok
s4c.extP4a() // expected-error{{no exact matches in call to instance method 'extP4a'}}
s4c.extP4Int() // okay
var b1 = s4d.extP4a() // okay, "Bool" version
b1 = true // checks type above
s4d.extP4Int() // expected-error{{referencing instance method 'extP4Int()' on 'P4' requires the types 'Bool' and 'Int' be equivalent}}
_ = b1
}
// ----------------------------------------------------------------------------
// Protocol extensions with a superclass constraint on Self
// ----------------------------------------------------------------------------
protocol ConformedProtocol {
typealias ConcreteConformanceAlias = Self
}
class BaseWithAlias<T> : ConformedProtocol {
typealias ConcreteAlias = T
struct NestedNominal {}
func baseMethod(_: T) {}
}
class DerivedWithAlias : BaseWithAlias<Int> {}
protocol ExtendedProtocol {
typealias AbstractConformanceAlias = Self
}
extension ExtendedProtocol where Self : DerivedWithAlias {
func f0(x: T) {} // expected-error {{cannot find type 'T' in scope}}
func f1(x: ConcreteAlias) {
let _: Int = x
baseMethod(x)
}
func f2(x: ConcreteConformanceAlias) {
let _: DerivedWithAlias = x
}
func f3(x: AbstractConformanceAlias) {
let _: DerivedWithAlias = x
}
func f4(x: NestedNominal) {}
}
// rdar://problem/21991470 & https://bugs.swift.org/browse/SR-5022
class NonPolymorphicInit {
init() { } // expected-note {{selected non-required initializer 'init()'}}
}
protocol EmptyProtocol { }
// The diagnostic is not very accurate, but at least we reject this.
extension EmptyProtocol where Self : NonPolymorphicInit {
init(string: String) {
self.init()
// expected-error@-1 {{constructing an object of class type 'Self' with a metatype value must use a 'required' initializer}}
}
}
// ----------------------------------------------------------------------------
// Using protocol extensions to satisfy requirements
// ----------------------------------------------------------------------------
protocol P5 {
func reqP5a()
}
// extension of P5 provides a witness for P6
extension P5 {
func reqP6a() { reqP5a() }
}
protocol P6 {
func reqP6a()
}
// S6a uses P5.reqP6a
struct S6a : P5 {
func reqP5a() { }
}
extension S6a : P6 { }
// S6b uses P5.reqP6a
struct S6b : P5, P6 {
func reqP5a() { }
}
// S6c uses P5.reqP6a
struct S6c : P6 {
}
extension S6c : P5 {
func reqP5a() { }
}
// S6d does not use P5.reqP6a
struct S6d : P6 {
func reqP6a() { }
}
extension S6d : P5 {
func reqP5a() { }
}
protocol P7 {
associatedtype P7Assoc
func getP7Assoc() -> P7Assoc
}
struct P7FromP8<T> { }
protocol P8 {
associatedtype P8Assoc
func getP8Assoc() -> P8Assoc
}
// extension of P8 provides conformance to P7Assoc
extension P8 {
func getP7Assoc() -> P7FromP8<P8Assoc> { return P7FromP8() }
}
// Okay, P7 requirements satisfied by P8
struct P8a : P8, P7 {
func getP8Assoc() -> Bool { return true }
}
func testP8a(_ p8a: P8a) {
var p7 = p8a.getP7Assoc()
p7 = P7FromP8<Bool>() // okay, check type of above
_ = p7
}
// Okay, P7 requirements explicitly specified
struct P8b : P8, P7 {
func getP7Assoc() -> Int { return 5 }
func getP8Assoc() -> Bool { return true }
}
func testP8b(_ p8b: P8b) {
var p7 = p8b.getP7Assoc()
p7 = 17 // check type of above
_ = p7
}
protocol PConforms1 {
}
extension PConforms1 {
func pc2() { } // expected-note{{candidate exactly matches}}
}
protocol PConforms2 : PConforms1, MakePC2Ambiguous {
func pc2() // expected-note{{multiple matching functions named 'pc2()' with type '() -> ()'}}
}
protocol MakePC2Ambiguous {
}
extension MakePC2Ambiguous {
func pc2() { } // expected-note{{candidate exactly matches}}
}
struct SConforms2a : PConforms2 { } // expected-error{{type 'SConforms2a' does not conform to protocol 'PConforms2'}}
struct SConforms2b : PConforms2 {
func pc2() { }
}
// Satisfying requirements via protocol extensions for fun and profit
protocol _MySeq { }
protocol MySeq : _MySeq {
associatedtype Generator : IteratorProtocol
func myGenerate() -> Generator
}
protocol _MyCollection : _MySeq {
associatedtype Index : Strideable
var myStartIndex : Index { get }
var myEndIndex : Index { get }
associatedtype _Element
subscript (i: Index) -> _Element { get }
}
protocol MyCollection : _MyCollection {
}
struct MyIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
struct OtherIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
extension _MyCollection {
func myGenerate() -> MyIndexedIterator<Self> {
return MyIndexedIterator(container: self, index: self.myEndIndex)
}
}
struct SomeCollection1 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
}
struct SomeCollection2 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
func myGenerate() -> OtherIndexedIterator<SomeCollection2> {
return OtherIndexedIterator(container: self, index: self.myEndIndex)
}
}
func testSomeCollections(_ sc1: SomeCollection1, sc2: SomeCollection2) {
var mig = sc1.myGenerate()
mig = MyIndexedIterator(container: sc1, index: sc1.myStartIndex)
_ = mig
var ig = sc2.myGenerate()
ig = MyIndexedIterator(container: sc2, index: sc2.myStartIndex) // expected-error {{cannot assign value of type 'MyIndexedIterator<SomeCollection2>' to type 'OtherIndexedIterator<SomeCollection2>'}}
_ = ig
}
public protocol PConforms3 {}
extension PConforms3 {
public var z: Int {
return 0
}
}
public protocol PConforms4 : PConforms3 {
var z: Int { get }
}
struct PConforms4Impl : PConforms4 {}
let pc4z = PConforms4Impl().z
// rdar://problem/20608438
protocol PConforms5 {
func f() -> Int
}
protocol PConforms6 : PConforms5 {}
extension PConforms6 {
func f() -> Int { return 42 }
}
func test<T: PConforms6>(_ x: T) -> Int { return x.f() }
struct PConforms6Impl : PConforms6 { }
// Extensions of a protocol that directly satisfy requirements (i.e.,
// default implementations hack N+1).
protocol PConforms7 {
func method()
var property: Int { get }
subscript (i: Int) -> Int { get }
}
extension PConforms7 {
func method() { }
var property: Int { return 5 }
subscript (i: Int) -> Int { return i }
}
struct SConforms7a : PConforms7 { }
protocol PConforms8 {
associatedtype Assoc
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms8 {
func method() -> Int { return 5 }
var property: Int { return 5 }
subscript (i: Int) -> Int { return i }
}
struct SConforms8a : PConforms8 { }
struct SConforms8b : PConforms8 {
func method() -> String { return "" }
var property: String { return "" }
subscript (i: String) -> String { return i }
}
func testSConforms8b() {
let s: SConforms8b.Assoc = "hello"
_ = s
}
struct SConforms8c : PConforms8 {
func method() -> String { return "" } // no warning in type definition
}
func testSConforms8c() {
let s: SConforms8c.Assoc = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'SConforms8c.Assoc' (aka 'Int')}}
_ = s
let i: SConforms8c.Assoc = 5
_ = i
}
protocol DefaultInitializable {
init()
}
extension String : DefaultInitializable { }
extension Int : DefaultInitializable { }
protocol PConforms9 {
associatedtype Assoc : DefaultInitializable // expected-note{{protocol requires nested type 'Assoc'}}
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms9 {
func method() -> Self.Assoc { return Assoc() }
var property: Self.Assoc { return Assoc() }
subscript (i: Self.Assoc) -> Self.Assoc { return Assoc() }
}
struct SConforms9a : PConforms9 { // expected-error{{type 'SConforms9a' does not conform to protocol 'PConforms9'}}
}
struct SConforms9b : PConforms9 {
typealias Assoc = Int
}
func testSConforms9b(_ s9b: SConforms9b) {
var p = s9b.property
p = 5
_ = p
}
struct SConforms9c : PConforms9 {
typealias Assoc = String
}
func testSConforms9c(_ s9c: SConforms9c) {
var p = s9c.property
p = "hello"
_ = p
}
struct SConforms9d : PConforms9 {
func method() -> Int { return 5 }
}
func testSConforms9d(_ s9d: SConforms9d) {
var p = s9d.property
p = 6
_ = p
}
protocol PConforms10 {}
extension PConforms10 {
func f() {}
}
protocol PConforms11 {
func f()
}
struct SConforms11 : PConforms10, PConforms11 {}
// ----------------------------------------------------------------------------
// Typealiases in protocol extensions.
// ----------------------------------------------------------------------------
// Basic support
protocol PTypeAlias1 {
associatedtype AssocType1
}
extension PTypeAlias1 {
typealias ArrayOfAssocType1 = [AssocType1]
}
struct STypeAlias1a: PTypeAlias1 {
typealias AssocType1 = Int
}
struct STypeAlias1b<T>: PTypeAlias1 {
typealias AssocType1 = T
}
func testPTypeAlias1() {
var a: STypeAlias1a.ArrayOfAssocType1 = []
a.append(1)
var b: STypeAlias1b<String>.ArrayOfAssocType1 = []
b.append("hello")
}
// Defaulted implementations to satisfy a requirement.
struct TypeAliasHelper<T> { }
protocol PTypeAliasSuper2 {
}
extension PTypeAliasSuper2 {
func foo() -> TypeAliasHelper<Self> { return TypeAliasHelper() }
}
protocol PTypeAliasSub2 : PTypeAliasSuper2 {
associatedtype Helper
func foo() -> Helper
}
struct STypeAliasSub2a : PTypeAliasSub2 { }
struct STypeAliasSub2b<T, U> : PTypeAliasSub2 { }
// ----------------------------------------------------------------------------
// Partial ordering of protocol extension members
// ----------------------------------------------------------------------------
// Partial ordering between members of protocol extensions and members
// of concrete types.
struct S1b : P1 {
func reqP1a() -> Bool { return true }
func extP1a() -> Int { return 0 }
}
func useS1b(_ s1b: S1b) {
var x = s1b.extP1a() // uses S1b.extP1a due to partial ordering
x = 5 // checks that "x" deduced to "Int" above
_ = x
var _: Bool = s1b.extP1a() // still uses P1.ext1Pa due to type annotation
}
// Partial ordering between members of protocol extensions for
// different protocols.
protocol PInherit1 { }
protocol PInherit2 : PInherit1 { }
protocol PInherit3 : PInherit2 { }
protocol PInherit4 : PInherit2 { }
extension PInherit1 {
func order1() -> Int { return 0 }
}
extension PInherit2 {
func order1() -> Bool { return true }
}
extension PInherit3 {
func order1() -> Double { return 1.0 }
}
extension PInherit4 {
func order1() -> String { return "hello" }
}
struct SInherit1 : PInherit1 { }
struct SInherit2 : PInherit2 { }
struct SInherit3 : PInherit3 { }
struct SInherit4 : PInherit4 { }
func testPInherit(_ si2 : SInherit2, si3: SInherit3, si4: SInherit4) {
var b1 = si2.order1() // PInherit2.order1
b1 = true // check that the above returned Bool
_ = b1
var d1 = si3.order1() // PInherit3.order1
d1 = 3.14159 // check that the above returned Double
_ = d1
var s1 = si4.order1() // PInherit4.order1
s1 = "hello" // check that the above returned String
_ = s1
// Other versions are still visible, since they may have different
// types.
b1 = si3.order1() // PInherit2.order1
var _: Int = si3.order1() // PInherit1.order1
}
protocol PConstrained1 {
associatedtype AssocTypePC1
}
extension PConstrained1 {
func pc1() -> Int { return 0 }
}
extension PConstrained1 where AssocTypePC1 : PInherit2 {
func pc1() -> Bool { return true }
}
extension PConstrained1 where Self.AssocTypePC1 : PInherit3 {
func pc1() -> String { return "hello" }
}
struct SConstrained1 : PConstrained1 {
typealias AssocTypePC1 = SInherit1
}
struct SConstrained2 : PConstrained1 {
typealias AssocTypePC1 = SInherit2
}
struct SConstrained3 : PConstrained1 {
typealias AssocTypePC1 = SInherit3
}
func testPConstrained1(_ sc1: SConstrained1, sc2: SConstrained2,
sc3: SConstrained3) {
var i = sc1.pc1() // PConstrained1.pc1
i = 17 // checks type of above
_ = i
var b = sc2.pc1() // PConstrained1 (with PInherit2).pc1
b = true // checks type of above
_ = b
var s = sc3.pc1() // PConstrained1 (with PInherit3).pc1
s = "hello" // checks type of above
_ = s
}
protocol PConstrained2 {
associatedtype AssocTypePC2
}
protocol PConstrained3 : PConstrained2 {
}
extension PConstrained2 where Self.AssocTypePC2 : PInherit1 {
func pc2() -> Bool { return true }
}
extension PConstrained3 {
func pc2() -> String { return "hello" }
}
struct SConstrained3a : PConstrained3 {
typealias AssocTypePC2 = Int
}
struct SConstrained3b : PConstrained3 {
typealias AssocTypePC2 = SInherit3
}
func testSConstrained3(_ sc3a: SConstrained3a, sc3b: SConstrained3b) {
var s = sc3a.pc2() // PConstrained3.pc2
s = "hello"
_ = s
_ = sc3b.pc2()
s = sc3b.pc2()
var _: Bool = sc3b.pc2()
}
extension PConstrained3 where AssocTypePC2 : PInherit1 { }
// Extending via a superclass constraint.
class Superclass {
func foo() { }
static func bar() { }
typealias Foo = Int
}
protocol PConstrained4 { }
extension PConstrained4 where Self : Superclass {
func testFoo() -> Foo {
foo()
self.foo()
return Foo(5)
}
static func testBar() {
bar()
self.bar()
}
}
protocol PConstrained5 { }
protocol PConstrained6 {
associatedtype Assoc
func foo()
}
protocol PConstrained7 { }
extension PConstrained6 {
var prop1: Int { return 0 }
var prop2: Int { return 0 } // expected-note{{'prop2' previously declared here}}
subscript (key: Int) -> Int { return key }
subscript (key: Double) -> Double { return key } // expected-note{{'subscript(_:)' previously declared here}}
}
extension PConstrained6 {
var prop2: Int { return 0 } // expected-error{{invalid redeclaration of 'prop2'}}
subscript (key: Double) -> Double { return key } // expected-error{{invalid redeclaration of 'subscript(_:)'}}
}
extension PConstrained6 where Assoc : PConstrained5 {
var prop1: Int { return 0 } // okay
var prop3: Int { return 0 } // expected-note{{'prop3' previously declared here}}
subscript (key: Int) -> Int { return key } // ok
subscript (key: String) -> String { return key } // expected-note{{'subscript(_:)' previously declared here}}
func foo() { } // expected-note{{'foo()' previously declared here}}
}
extension PConstrained6 where Assoc : PConstrained5 {
var prop3: Int { return 0 } // expected-error{{invalid redeclaration of 'prop3'}}
subscript (key: String) -> String { return key } // expected-error{{invalid redeclaration of 'subscript(_:)'}}
func foo() { } // expected-error{{invalid redeclaration of 'foo()'}}
}
extension PConstrained6 where Assoc : PConstrained7 {
var prop1: Int { return 0 } // okay
subscript (key: Int) -> Int { return key } // okay
func foo() { } // okay
}
extension PConstrained6 where Assoc == Int {
var prop4: Int { return 0 }
subscript (key: Character) -> Character { return key }
func foo() { } // okay
}
extension PConstrained6 where Assoc == Double {
var prop4: Int { return 0 } // okay
subscript (key: Character) -> Character { return key } // okay
func foo() { } // okay
}
// Interaction between RawRepresentable and protocol extensions.
public protocol ReallyRaw : RawRepresentable {
}
public extension ReallyRaw where RawValue: SignedInteger {
// expected-warning@+1 {{'public' modifier is redundant for initializer declared in a public extension}}
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
}
enum Foo : Int, ReallyRaw {
case a = 0
}
// ----------------------------------------------------------------------------
// Semantic restrictions
// ----------------------------------------------------------------------------
// Extension cannot have an inheritance clause.
protocol BadProto1 { }
protocol BadProto2 { }
extension BadProto1 : BadProto2 { } // expected-error{{extension of protocol 'BadProto1' cannot have an inheritance clause}}
extension BadProto2 {
struct S { } // expected-error{{type 'S' cannot be nested in protocol extension of 'BadProto2'}}
class C { } // expected-error{{type 'C' cannot be nested in protocol extension of 'BadProto2'}}
enum E { } // expected-error{{type 'E' cannot be nested in protocol extension of 'BadProto2'}}
}
extension BadProto1 {
func foo() { }
var prop: Int { return 0 }
subscript (i: Int) -> String {
return "hello"
}
}
// rdar://problem/20756244
protocol BadProto3 { }
typealias BadProto4 = BadProto3
extension BadProto4 { } // okay
typealias RawRepresentableAlias = RawRepresentable
extension RawRepresentableAlias { } // okay
extension AnyObject { } // expected-error{{non-nominal type 'AnyObject' cannot be extended}}
// Members of protocol extensions cannot be overridden.
// rdar://problem/21075287
class BadClass1 : BadProto1 {
func foo() { }
override var prop: Int { return 5 } // expected-error{{property does not override any property from its superclass}}
}
protocol BadProto5 {
associatedtype T1 // expected-note{{protocol requires nested type 'T1'}}
associatedtype T2 // expected-note{{protocol requires nested type 'T2'}}
associatedtype T3 // expected-note{{protocol requires nested type 'T3'}}
}
class BadClass5 : BadProto5 {} // expected-error{{type 'BadClass5' does not conform to protocol 'BadProto5'}}
typealias A = BadProto1
typealias B = BadProto1
extension A & B {} // expected-warning {{extending a protocol composition is not supported; extending 'BadProto1' instead}}
// Suppress near-miss warning for unlabeled initializers.
protocol P9 {
init(_: Int)
init(_: Double)
}
extension P9 {
init(_ i: Int) {
self.init(Double(i))
}
}
struct X9 : P9 {
init(_: Float) { }
}
extension X9 {
init(_: Double) { }
}
// Suppress near-miss warning for unlabeled subscripts.
protocol P10 {
subscript (_: Int) -> Int { get }
subscript (_: Double) -> Double { get }
}
extension P10 {
subscript(i: Int) -> Int {
return Int(self[Double(i)])
}
}
struct X10 : P10 {
subscript(f: Float) -> Float { return f }
}
extension X10 {
subscript(d: Double) -> Double { return d }
}
protocol Empty1 {}
protocol Empty2 {}
struct Concrete1 {}
extension Concrete1 : Empty1 & Empty2 {}
typealias TA = Empty1 & Empty2
struct Concrete2 {}
extension Concrete2 : TA {}
func f<T : Empty1 & Empty2>(_: T) {}
func useF() {
f(Concrete1())
f(Concrete2())
}
|
apache-2.0
|
a7a28281d68629fb6aa87159131d4898
| 22.996194 | 204 | 0.627716 | 3.712645 | false | false | false | false |
moray95/MCChat
|
Pod/Classes/DetailsViewController.swift
|
1
|
2092
|
//
// DetailsViewViewController.swift
// MultipeerConnectivityChat
//
// Created by Moray on 26/06/15.
// Copyright © 2015 Moray. All rights reserved.
//
import UIKit
class DetailsViewController: UIViewController
{
// MARK: Outlets
@IBOutlet weak var displayNameLabel: UILabel!
@IBOutlet weak var firstNameLabel: UILabel!
@IBOutlet weak var lastNameLabel: UILabel!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var bioLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var compassImageView: UIImageView!
// MARK: Instance Variables
var userInfo : UserInfo?
// MARK: View load/unload
override func viewDidLoad()
{
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss:")
let gestureRecognizer = UITapGestureRecognizer(target: self, action: "dismiss:")
gestureRecognizer.numberOfTapsRequired = 1
gestureRecognizer.numberOfTouchesRequired = 1
view.addGestureRecognizer(gestureRecognizer)
compassImageView.transform = CGAffineTransformMakeRotation(CGFloat(userInfo!.orientation * M_PI / 180.0))
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
imageView.layer.cornerRadius = 34
imageView.layer.masksToBounds = true
imageView.layer.borderWidth = 0
imageView.image = userInfo!.avatar ?? avatarForDisplayName(userInfo!.displayName).avatarImage()
compassImageView.layer.cornerRadius = 34
compassImageView.layer.masksToBounds = true
compassImageView.layer.borderWidth = 0
displayNameLabel.text = userInfo!.displayName
firstNameLabel.text = userInfo!.firstName
lastNameLabel.text = userInfo!.lastName
ageLabel.text = "\(userInfo!.age!)"
bioLabel.numberOfLines = 0
bioLabel.text = userInfo!.bio
}
// MARK: Actions
func dismiss(sender : AnyObject)
{
dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
12d5463d54f302ff4ca7eb93680ef8ac
| 29.75 | 120 | 0.697752 | 5.125 | false | false | false | false |
eKasztany/4ania
|
ios/Queue/Queue/Models/Service.swift
|
1
|
726
|
//
// Created by Aleksander Grzyb on 24/09/16.
// Copyright © 2016 Aleksander Grzyb. All rights reserved.
//
import Foundation
struct Service {
let uid: String
let serviceGroups: [ServiceGroup]
}
extension Service {
init?(dictionary: JSONDictionary) {
guard let serviceData = dictionary["service_data"],
let serviceDataDictionary = serviceData as? JSONDictionary,
let serviceGroups = serviceDataDictionary["grupy"],
let serviceGroupsArray = serviceGroups as? [JSONDictionary],
let uid = dictionary["department_id"] as? String else { return nil }
self.serviceGroups = serviceGroupsArray.flatMap(ServiceGroup.init)
self.uid = uid
}
}
|
apache-2.0
|
33914b63d88a8e6a7900ba53c19c1973
| 30.521739 | 80 | 0.675862 | 4.36747 | false | false | false | false |
Spacerat/HexKeyboard
|
HexKeyboard/AppDelegate.swift
|
1
|
6589
|
//
// AppDelegate.swift
// HexKeyboard
//
// Created by Joseph Atkins-Turkish on 02/09/2014.
// Copyright (c) 2014 Joseph Atkins-Turkish. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let url = NSBundle.mainBundle().URLForResource("defaults", withExtension: "plist")!
//let defaults = NSMutableDictionary.dictionaryWithContentsOfURL(url)
let defaults = NSMutableDictionary(contentsOfURL: url);
NSUserDefaults.standardUserDefaults().registerDefaults(defaults!)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "joe.HexKeyboard" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("HexKeyboard", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("HexKeyboard.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
//error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
error = nil;
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
|
gpl-2.0
|
00b4d1eef897be66d59460bafae7d0a5
| 54.838983 | 290 | 0.706329 | 5.883036 | false | false | false | false |
davedelong/DDMathParser
|
MathParser/Sources/MathParser/FractionNumberExtractor.swift
|
1
|
1271
|
//
// FractionNumberExtractor.swift
// DDMathParser
//
// Created by Dave DeLong on 8/30/15.
//
//
import Foundation
internal struct FractionNumberExtractor: TokenExtractor {
internal static let fractions: Dictionary<Character, Double> = [
"½": 0.5,
"⅓": 0.3333333,
"⅔": 0.6666666,
"¼": 0.25,
"¾": 0.75,
"⅕": 0.2,
"⅖": 0.4,
"⅗": 0.6,
"⅘": 0.8,
"⅙": 0.1666666,
"⅚": 0.8333333,
"⅛": 0.125,
"⅜": 0.375,
"⅝": 0.625,
"⅞": 0.875
]
func matchesPreconditions(_ buffer: TokenCharacterBuffer, configuration: Configuration) -> Bool {
guard let peek = buffer.peekNext() else { return false }
guard let _ = FractionNumberExtractor.fractions[peek] else { return false }
return true
}
func extract(_ buffer: TokenCharacterBuffer, configuration: Configuration) -> Tokenizer.Result {
let start = buffer.currentIndex
// consume the character
buffer.consume()
let range: Range<Int> = start ..< buffer.currentIndex
let raw = buffer[range]
return .value(FractionNumberToken(string: raw, range: range))
}
}
|
mit
|
72752cc266e2706626a9a45e69c957a3
| 24.916667 | 101 | 0.557878 | 3.658824 | false | true | false | false |
Roommate-App/roomy
|
roomy/Pods/IBAnimatable/Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationBallScale.swift
|
2
|
1694
|
//
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallScale: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 1
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circle = ActivityIndicatorShape.circle.makeLayer(size: size, color: color)
circle.frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallScale {
var animation: CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimation]
animation.timingFunctionType = .easeInOut
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
var scaleAnimation: CABasicAnimation {
let scaleAnimation = CABasicAnimation(keyPath:"transform.scale")
scaleAnimation.duration = duration
scaleAnimation.fromValue = 0
scaleAnimation.toValue = 1
return scaleAnimation
}
var opacityAnimation: CABasicAnimation {
let opacityAnimation = CABasicAnimation(keyPath:"opacity")
opacityAnimation.duration = duration
opacityAnimation.fromValue = 1
opacityAnimation.toValue = 0
return opacityAnimation
}
}
|
mit
|
519b9dfb2078b76c6c499f6b05271e69
| 28.719298 | 83 | 0.710153 | 5.117825 | false | false | false | false |
tomekc/R.swift
|
R.swift/main.swift
|
2
|
1769
|
//
// main.swift
// R.swift
//
// Created by Mathijs Kadijk on 11-12-14.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
do {
let callInformation = try CallInformation(processInfo: NSProcessInfo.processInfo())
let xcodeproj = try Xcodeproj(url: callInformation.xcodeprojURL)
let resourceURLs = try xcodeproj.resourceURLsForTarget(callInformation.targetName, pathResolver: pathResolverWithSourceTreeFolderToURLConverter(callInformation.URLForSourceTreeFolder))
let resources = Resources(resourceURLs: resourceURLs, fileManager: NSFileManager.defaultManager())
let (internalStruct, externalStruct) = generateResourceStructsWithResources(resources)
let fileContents = [
Header,
Imports,
externalStruct.description,
internalStruct.description,
ReuseIdentifier.description,
NibResourceProtocol.description,
ReusableProtocol.description,
ReuseIdentifierUITableViewExtension.description,
ReuseIdentifierUICollectionViewExtension.description,
NibUIViewControllerExtension.description,
].joinWithSeparator("\n\n")
// Write file if we have changes
if readResourceFile(callInformation.outputURL) != fileContents {
writeResourceFile(fileContents, toFileURL: callInformation.outputURL)
}
} catch let InputParsingError.UserAskedForHelp(helpString: helpString) {
print(helpString)
exit(1)
} catch let InputParsingError.IllegalOption(helpString: helpString) {
fail("Illegal option given.")
print(helpString)
exit(2)
} catch let InputParsingError.MissingOption(helpString: helpString) {
fail("Not all mandatory option given.")
print(helpString)
exit(2)
} catch let ResourceParsingError.ParsingFailed(description) {
fail(description)
exit(3)
}
|
mit
|
d0dff0fe326dbc1501e480a334a2f6a2
| 31.759259 | 186 | 0.781232 | 4.4225 | false | false | false | false |
mlgoogle/viossvc
|
viossvc/Scenes/User/DrawCashDetailViewController.swift
|
1
|
3679
|
//
// DrawCashDetailViewController.swift
// viossvc
//
// Created by 木柳 on 2016/11/27.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
import SVProgressHUD
class DrawCashDetailViewController: BaseTableViewController {
@IBOutlet weak var bankCardLabel: UILabel!
@IBOutlet weak var drawCashCount: UILabel!
@IBOutlet weak var drawCashTime: UILabel!
@IBOutlet weak var stepIcon1: UIButton!
@IBOutlet weak var stepIcon2: UIButton!
@IBOutlet weak var stepIcon3: UIButton!
var stats: Int?{
didSet{
stepIcon1.selected = stats == 0
stepIcon2.selected = stats == 1
stepIcon3.selected = stats == 2
}
}
var model: DrawCashRecordModel?
//MARK: --LIFECYCLE
override func viewDidLoad() {
super.viewDidLoad()
initData()
initUI()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if model == nil {
return
}
updateUI(model!)
navigationItem.hidesBackButton = false
navigationItem.rightBarButtonItem = nil
}
//MARK: --DATA
func initData() {
if model != nil {
return
}
let object: DrawCashModel = DrawCashModel()
object.uid = CurrentUserHelper.shared.userInfo.uid
object.account = CurrentUserHelper.shared.userInfo.currentBankCardNumber
object.num = 1
object.size = 1
AppAPIHelper.userAPI().drawCashDetail(object, complete: { [weak self](result) in
if result == nil{
SVProgressHUD.showErrorMessage(ErrorMessage: "获取提现详情内容失败,请前往提现记录中查看", ForDuration: 1, completion: {
self?.navigationController?.pushViewControllerWithIdentifier(DrawCashRecordViewController.className(), animated: true)
})
return
}
let resultModel = result as! DrawCashModel
if resultModel.withdraw_record.count >= 0{
let model:DrawCashRecordModel = resultModel.withdraw_record[0]
self?.updateUI(model)
}
}, error: errorBlockFunc())
}
//MARK: --UI
func initUI() {
navigationItem.backBarButtonItem = nil
navigationItem.hidesBackButton = true
if navigationItem.rightBarButtonItem == nil {
let sureBtn = UIButton.init(frame: CGRectMake(0, 0, 40, 30))
sureBtn.setTitle("确定", forState: .Normal)
sureBtn.titleLabel?.font = UIFont.systemFontOfSize(S18)
sureBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
sureBtn.backgroundColor = UIColor.clearColor()
sureBtn.addTarget(self, action: #selector(rightItemTapped), forControlEvents: .TouchUpInside)
let sureItem = UIBarButtonItem.init(customView: sureBtn)
navigationItem.rightBarButtonItem = sureItem
}
}
func updateUI(model: DrawCashRecordModel) {
let bankNum = ((model.account)! as NSString).substringWithRange(NSRange.init(location: model.account!.length()-4, length: 4))
let bankName = model.bank_name
bankCardLabel.text = "\(bankName!)(\(bankNum))"
drawCashCount.text = "¥\(model.cash/100)"
drawCashTime.text = model.request_time
stats = model.status
}
func rightItemTapped(sender: UIButton) {
navigationController?.popToRootViewControllerAnimated(true)
}
}
|
apache-2.0
|
795d716c621d7389c494fc439b2ad075
| 32.869159 | 138 | 0.607616 | 4.86443 | false | false | false | false |
kevintavog/PeachMetadata
|
source/PeachMetadata/DirectoryOutline.swift
|
1
|
4346
|
//
// PeachMetadata
//
import AppKit
import RangicCore
extension PeachWindowController
{
@IBAction func openFolder(_ sender: AnyObject)
{
let dialog = NSOpenPanel()
dialog.canChooseFiles = false
dialog.canChooseDirectories = true
if 1 != dialog.runModal().rawValue || dialog.urls.count < 1 {
return
}
NSDocumentController.shared.noteNewRecentDocumentURL(dialog.urls[0])
let folderName = dialog.urls[0].path
populateDirectoryView(folderName)
}
func populateDirectoryView(_ folderName: String)
{
Preferences.lastOpenedFolder = folderName
rootDirectory = DirectoryTree(parent: nil, folder: folderName)
directoryView.deselectAll(nil)
directoryView.reloadData()
}
func selectDirectoryViewRow(_ folderName: String)
{
var bestRow = -1
for row in 0..<directoryView.numberOfRows {
let dt = directoryView.item(atRow: row) as! DirectoryTree
if dt.folder == folderName {
bestRow = row
break
}
if folderName.lowercased().hasPrefix(dt.folder.lowercased()) {
bestRow = row
}
}
if bestRow >= 0 {
directoryView.selectRowIndexes(IndexSet(integer: bestRow), byExtendingSelection: false)
directoryView.scrollRowToVisible(bestRow)
}
}
func outlineViewSelectionDidChange(_ notification: Notification)
{
let selectedItem = toTree(directoryView.item(atRow: directoryView.selectedRow) as AnyObject?)
populateImageView(selectedItem.folder)
Preferences.lastSelectedFolder = selectedItem.folder
}
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int
{
if rootDirectory == nil { return 0 }
return toTree(item).subFolders.count
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool
{
return toTree(item).subFolders.count > 0
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject
{
return toTree(item).subFolders[index]
}
func outlineView(_ outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject?
{
return toTree(item).relativePath as AnyObject?
}
func toTree(_ item: AnyObject?) -> DirectoryTree
{
if let dirTree = item as! DirectoryTree? {
return dirTree
}
return rootDirectory!
}
}
class DirectoryTree : NSObject
{
let folder: String
let relativePath: String
fileprivate var _subFolders: [DirectoryTree]?
init(parent: DirectoryTree!, folder: String)
{
self.folder = folder
if parent == nil {
relativePath = ""
} else {
relativePath = folder.relativePathFromBase(parent.folder)
}
}
var subFolders: [DirectoryTree]
{
if _subFolders == nil {
populateChildren()
}
return _subFolders!
}
fileprivate func populateChildren()
{
var folderEntries = [DirectoryTree]()
if FileManager.default.fileExists(atPath: folder) {
if let files = getFiles(folder) {
for f in files {
var isFolder: ObjCBool = false
if FileManager.default.fileExists(atPath: f.path, isDirectory:&isFolder) && isFolder.boolValue {
folderEntries.append(DirectoryTree(parent: self, folder: f.path))
}
}
}
}
_subFolders = folderEntries
}
fileprivate func getFiles(_ folderName: String) -> [URL]?
{
do {
let list = try FileManager.default.contentsOfDirectory(
at: URL(fileURLWithPath: folderName),
includingPropertiesForKeys: nil,
options:FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
return list.sorted { $0.absoluteString < $1.absoluteString }
}
catch let error {
Logger.error("Failed getting files in \(folderName): \(error)")
return nil
}
}
}
|
mit
|
b5b4af4e762ba091e9ebc710edfc35c4
| 27.973333 | 144 | 0.606765 | 5.065268 | false | false | false | false |
radvansky-tomas/NutriFacts
|
nutri-facts/nutri-facts/ViewControllers/ProfileViewController.swift
|
1
|
8691
|
//
// ProfileViewController.swift
// nutri-facts
//
// Created by Tomas Radvansky on 16/05/2015.
// Copyright (c) 2015 Tomas Radvansky. All rights reserved.
//
import UIKit
import ASValueTrackingSlider
class ProfileViewController: UIViewController,ASValueTrackingSliderDelegate,ASValueTrackingSliderDataSource {
//MARK: IBOutlets
@IBOutlet weak var genderLabel: UILabel!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var heightLabel: UILabel!
@IBOutlet weak var weightLabel: UILabel!
@IBOutlet weak var desiredWeightLabel: UILabel!
@IBOutlet weak var maleBtn: NutriButton!
@IBOutlet weak var femaleBtn: NutriButton!
@IBOutlet weak var ageSlider: ASValueTrackingSlider!
@IBOutlet weak var heightSlider: ASValueTrackingSlider!
@IBOutlet weak var weightSlider: ASValueTrackingSlider!
@IBOutlet weak var desiredWeightSlider: ASValueTrackingSlider!
//MARK: Vars
var currentUser:User!
//MARK: View Management
override func viewDidLoad() {
super.viewDidLoad()
//Prepare Navigation controller
self.navigationItem.hidesBackButton = true
//Are we editing or creating new user?
if let firstUser:User = Core.sharedInstance.realm.objects(User).first
{
currentUser = firstUser
}
else
{
//Load default values
currentUser = User()
currentUser.height = 180
currentUser.age = 27
currentUser.gender = false
currentUser.weight = 65.0
currentUser.desiredWeight = 65.0
}
//Setup custom sliders + Load default values
ageSlider.minimumValue = 10
ageSlider.maximumValue = 110
ageSlider.setMaxFractionDigitsDisplayed(0)
ageSlider.textColor = UIColor.redColor()
ageSlider.popUpViewColor = ControlBcgSolidColor
ageSlider.delegate = self
ageSlider.dataSource = self
ageSlider.value = Float(self.currentUser.age)
weightSlider.minimumValue = 0
weightSlider.maximumValue = 260
weightSlider.setMaxFractionDigitsDisplayed(0)
weightSlider.textColor = UIColor.whiteColor()
weightSlider.delegate = self
weightSlider.dataSource = self
weightSlider.value = Float(self.currentUser.weight)
heightSlider.minimumValue = 50
heightSlider.maximumValue = 230
heightSlider.setMaxFractionDigitsDisplayed(0)
heightSlider.textColor = UIColor.redColor()
heightSlider.popUpViewColor = ControlBcgSolidColor
heightSlider.delegate = self
heightSlider.dataSource = self
heightSlider.value = Float(self.currentUser.height)
desiredWeightSlider.minimumValue = 0
desiredWeightSlider.maximumValue = 260
desiredWeightSlider.setMaxFractionDigitsDisplayed(0)
desiredWeightSlider.textColor = UIColor.whiteColor()
desiredWeightSlider.delegate = self
desiredWeightSlider.dataSource = self
desiredWeightSlider.value = Float(self.currentUser.weight)
//Start writting session to avoid realm error during process
Core.sharedInstance.realm.beginWrite()
//Load initial UI
UpdateUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func UpdateUI()
{
if self.currentUser.gender == true
{
genderLabel.text = "Female"
}
else
{
genderLabel.text = "Male"
}
if self.currentUser.gender == true
{
maleBtn.backgroundColor = ControlBcgColor
femaleBtn.backgroundColor = ControlBcgHighlightedColor
}
else
{
maleBtn.backgroundColor = ControlBcgHighlightedColor
femaleBtn.backgroundColor = ControlBcgColor
}
weightSlider.setPopUpViewAnimatedColors(WeightSliderColors, withPositions: self.GetColorPositions()) //slider color based on BMI for better UX
desiredWeightSlider.setPopUpViewAnimatedColors(WeightSliderColors, withPositions: self.GetColorPositions()) //slider color based on BMI for better UX
ageLabel.text = String(format: "%d yrs", self.currentUser.age)
heightLabel.text = String(format: "%d cm", self.currentUser.height)
weightLabel.text = String(format: "%.2f kg", self.currentUser.weight)
desiredWeightLabel.text = String(format: "%.2f kg", self.currentUser.desiredWeight)
}
//MARK: IBActions
@IBAction func LetsStartBtnClicked(sender: AnyObject) {
// Save changes + move to base controller (->then to Dashboard VC)
Core.sharedInstance.realm.add(self.currentUser, update: true)
Core.sharedInstance.realm.commitWrite()
self.navigationController?.popToRootViewControllerAnimated(true)
}
@IBAction func MaleBtnClicked(button:NutriButton!)
{
if self.currentUser.gender == true
{
self.currentUser.gender = false
}
UpdateUI()
}
@IBAction func FemaleBtnClicked(button:NutriButton!)
{
if self.currentUser.gender == false
{
self.currentUser.gender = true
}
UpdateUI()
}
//MARK: Slider updates
@IBAction func AgeChanged(slider: ASValueTrackingSlider!)
{
self.currentUser.age = Int(slider.value)
UpdateUI()
}
@IBAction func HeightChanged(slider: ASValueTrackingSlider!)
{
self.currentUser.height = Int(slider.value)
UpdateUI()
}
@IBAction func WeightChanged(slider: ASValueTrackingSlider!)
{
self.currentUser.weight = Double(slider.value)
weightLabel.text = String(format: "%.2f kg", self.currentUser.weight)
}
@IBAction func DesiredWeightChanged(slider: ASValueTrackingSlider!)
{
self.currentUser.desiredWeight = Double(slider.value)
desiredWeightLabel.text = String(format: "%.2f kg", self.currentUser.desiredWeight)
}
//MARK: ASValueTrackingSliderDelegate
func sliderWillDisplayPopUpView(slider: ASValueTrackingSlider!) {
slider.superview?.bringSubviewToFront(slider)
}
func slider(slider: ASValueTrackingSlider!, stringForValue value: Float) -> String! {
//Custom label formatter
if slider == ageSlider
{
return String(format: "%.f yrs", value)
}
else if slider == heightSlider
{
return String(format: "%.f cm", value)
}
else
{
return String(format: "%.2f kg", value)
}
}
//MARK: Helpers
func GetColorPositions()->Array<NSNumber>
{
// *Severe Thinness < 16
// Moderate Thinness 16 - 17
// Mild Thinness 17 - 18.5
// Normal 18.5 - 25
// Overweight 25 - 30
// Obese Class I 30 - 35
// *Obese Class II 35 - 40
var result:Array<NSNumber> = Array<NSNumber>()
var kgValue:Float = 0
result.append(NSNumber(float: kgValue))
kgValue = Globals.WeightForBMI(self.currentUser.gender, height: Float(self.currentUser.height), BMI: 16.0, age: self.currentUser.age)
result.append(NSNumber(float: kgValue))
kgValue = Globals.WeightForBMI(self.currentUser.gender, height: Float(self.currentUser.height), BMI: 18.5, age: self.currentUser.age)
result.append(NSNumber(float: kgValue))
kgValue = Globals.WeightForBMI(self.currentUser.gender, height: Float(self.currentUser.height), BMI: 18.5, age: self.currentUser.age)
result.append(NSNumber(float: kgValue))
kgValue = Globals.WeightForBMI(self.currentUser.gender, height: Float(self.currentUser.height), BMI: 25.0, age: self.currentUser.age)
result.append(NSNumber(float: kgValue))
kgValue = Globals.WeightForBMI(self.currentUser.gender, height: Float(self.currentUser.height), BMI: 35.0, age: self.currentUser.age)
result.append(NSNumber(float: kgValue))
kgValue = Globals.WeightForBMI(self.currentUser.gender, height: Float(self.currentUser.height), BMI: 35.5, age: self.currentUser.age)
result.append(NSNumber(float: kgValue))
kgValue = Globals.WeightForBMI(self.currentUser.gender, height: Float(self.currentUser.height), BMI: 40, age: self.currentUser.age)
result.append(NSNumber(float: 260)) //till the end
return result
}
}
|
gpl-2.0
|
c1bd44e7f1138e5272c2de06e1e7666a
| 37.118421 | 157 | 0.648602 | 4.521852 | false | false | false | false |
eBardX/XestiMonitors
|
Tests/CoreLocation/SignificantLocationMonitorTests.swift
|
1
|
2930
|
//
// SignificantLocationMonitorTests.swift
// XestiMonitorsTests
//
// Created by J. G. Pusey on 2018-03-22.
//
// © 2018 J. G. Pusey (see LICENSE.md)
//
import CoreLocation
import XCTest
@testable import XestiMonitors
internal class SignificantLocationMonitorTests: XCTestCase {
let locationManager = MockLocationManager()
override func setUp() {
super.setUp()
LocationManagerInjector.inject = { self.locationManager }
}
func testIsAvailable_false() {
let monitor = SignificantLocationMonitor(queue: .main) { _ in
XCTAssertEqual(OperationQueue.current, .main)
}
locationManager.updateSignificantLocation(available: false)
XCTAssertFalse(monitor.isAvailable)
}
func testIsAvailable_true() {
let monitor = SignificantLocationMonitor(queue: .main) { _ in
XCTAssertEqual(OperationQueue.current, .main)
}
locationManager.updateSignificantLocation(available: true)
XCTAssertTrue(monitor.isAvailable)
}
func testMonitor_error() {
let expectation = self.expectation(description: "Handler called")
let expectedError = makeError()
var expectedEvent: SignificantLocationMonitor.Event?
let monitor = SignificantLocationMonitor(queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
locationManager.updateSignificantLocation(error: expectedError)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didUpdate(info) = event,
case let .error(error) = info {
XCTAssertEqual(error as NSError, expectedError)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_location() {
let expectation = self.expectation(description: "Handler called")
let expectedLocation = CLLocation()
var expectedEvent: SignificantLocationMonitor.Event?
let monitor = SignificantLocationMonitor(queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
locationManager.updateSignificantLocation(expectedLocation)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didUpdate(info) = event,
case let .location(location) = info {
XCTAssertEqual(location, expectedLocation)
} else {
XCTFail("Unexpected event")
}
}
private func makeError() -> NSError {
return NSError(domain: "CLErrorDomain",
code: CLError.Code.network.rawValue)
}
}
|
mit
|
f94cb918b231f05ef98d338207932ce3
| 29.195876 | 73 | 0.643223 | 5.221034 | false | true | false | false |
psturm-swift/SwiftySignals
|
Sources/AnyObserver.swift
|
1
|
1712
|
// Copyright (c) 2017 Patrick Sturm <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public final class AnyObserver<T>: ObserverType {
public typealias MessageIn = T
private let _process: (T)->Void
private let _unsubscribed: ()->Void
public init<Base: ObserverType>(base: Base) where Base.MessageIn == MessageIn {
self._process = {
base.process(message: $0)
}
self._unsubscribed = {
base.unsubscribed()
}
}
public func process(message: MessageIn) {
_process(message)
}
public func unsubscribed() {
_unsubscribed()
}
}
|
mit
|
9675e0927d48a1aacfdc8ce33650155a
| 37.909091 | 83 | 0.705607 | 4.493438 | false | false | false | false |
King-Wizard/UITextField-Shake-Swift
|
UITextFieldShakeSwift/UITextField+Shake.swift
|
1
|
5862
|
//
// UITextField+Shake.swift
// UITextFieldShakeSwift
//
// UITextFieldShakeSwift version 1.0.3
//
// Initially created by Andrea Mazzini (using Objective-C) on 08/02/14.
// Translated from Objective-C to Swift by King-Wizard on 09/05/15.
// Copyright (c) 2015 King-Wizard. All rights reserved.
//
import UIKit
import Foundation
/**
@enum ShakeDirection
Enum that specifies the direction of the shake
*/
public enum ShakeDirection : Int {
case horizontal = 0
case vertical = 1
}
/*
Swift Framework creation: http://bit.ly/1T8SkUR
Build your own Cocoa Touch Frameworks, in pure Swift: http://bit.ly/1gNLyZ8
Deleting contents from Xcode Derived data folder: http://bit.ly/1ItWqSo
*/
public extension UITextField {
/**
Shake the UITextField.
Shake the text field with default values.
*/
func shake() {
self.shake(10, withDelta: 5, completion: nil)
}
/**
Shake the UITextField.
Shake the text field a given number of times.
:param: times The number of shakes.
:param: delta The width of the shake.
*/
func shake(_ times: Int,
withDelta delta: CGFloat) {
self.shake(times, withDelta: delta, completion: nil)
}
/**
Shake the UITextField.
Shake the text field a given number of times.
:param: times The number of shakes.
:param: delta The width of the shake.
:param: handler A block object to be executed when the shake sequence ends.
*/
func shake(_ times: Int,
withDelta delta: CGFloat,
completion handler: (() -> Void)?) {
self._shake(times, direction: 1, currentTimes: 0, withDelta: delta, speed: 0.03, shakeDirection: ShakeDirection.horizontal, completion: handler)
}
/**
Shake the UITextField at a custom speed.
Shake the text field a given number of times with a given speed.
:param: times The number of shakes.
:param: delta The width of the shake.
:param: interval The duration of one shake.
*/
func shake(_ times: Int,
withDelta delta: CGFloat,
speed interval: TimeInterval) {
self.shake(times, withDelta: delta, speed: interval, completion: nil)
}
/**
Shake the UITextField at a custom speed.
Shake the text field a given number of times with a given speed.
:param: times The number of shakes.
:param: delta The width of the shake.
:param: interval The duration of one shake.
:param: handler A block object to be executed when the shake sequence ends.
*/
func shake(_ times: Int,
withDelta delta: CGFloat,
speed interval: TimeInterval,
completion handler: (() -> Void)?) {
self._shake(times, direction: 1, currentTimes: 0, withDelta: delta, speed: interval, shakeDirection: ShakeDirection.horizontal, completion: handler)
}
/**
Shake the UITextField at a custom speed.
Shake the text field a given number of times with a given speed.
:param: times The number of shakes.
:param: delta The width of the shake.
:param: interval The duration of one shake.
:param: direction of the shake.
*/
func shake(_ times: Int,
withDelta delta: CGFloat,
speed interval: TimeInterval,
shakeDirection: ShakeDirection) {
self.shake(times, withDelta: delta, speed: interval, shakeDirection: shakeDirection, completion: nil)
}
/**
Shake the UITextField at a custom speed.
Shake the text field a given number of times with a given speed.
:param: times The number of shakes.
:param: delta The width of the shake.
:param: interval The duration of one shake.
:param: direction of the shake.
:param: handler A block object to be executed when the shake sequence ends.
*/
func shake(_ times: Int,
withDelta delta: CGFloat,
speed interval: TimeInterval,
shakeDirection: ShakeDirection,
completion handler: (() -> Void)?) {
self._shake(times, direction: 1, currentTimes: 0, withDelta: delta, speed: interval, shakeDirection: shakeDirection, completion: handler)
}
private func _shake(_ times: Int,
direction: Int,
currentTimes current: Int,
withDelta delta: CGFloat,
speed interval: TimeInterval,
shakeDirection: ShakeDirection,
completion handler: (() -> Void)?) {
UIView.animate(withDuration: interval, animations: {
() -> Void in
self.transform = (shakeDirection == ShakeDirection.horizontal) ?
CGAffineTransform(translationX: delta * CGFloat(direction), y: 0) :
CGAffineTransform(translationX: 0, y: delta * CGFloat(direction))
}, completion: {
(finished: Bool) in
if current >= times {
UIView.animate(withDuration: interval, animations: {
() -> Void in
self.transform = CGAffineTransform.identity
}, completion: {
(finished: Bool) in
if let handler = handler {
handler()
}
})
return
}
self._shake(times - 1,
direction: direction * -1,
currentTimes: current + 1,
withDelta: delta,
speed: interval,
shakeDirection: shakeDirection,
completion: handler)
})
}
}
|
mit
|
1bd7c71166552f81481b18f64e3b8e4b
| 31.932584 | 160 | 0.58086 | 4.738884 | false | false | false | false |
duming91/Hear-You
|
Hear You/ViewControllers/Main/MenuViewController.swift
|
1
|
3193
|
//
// MenuViewController.swift
// Hear You
//
// Created by 董亚珣 on 16/4/9.
// Copyright © 2016年 snow. All rights reserved.
//
import UIKit
import RESideMenu
class MenuViewController: UIViewController {
private let cellIdentifier = "Cell"
override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView(frame: CGRect(x: 0, y: 20, width: view.frame.width, height: view.frame.height))
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
tableView.autoresizingMask = [.FlexibleTopMargin, .FlexibleBottomMargin, .FlexibleWidth]
tableView.delegate = self
tableView.dataSource = self
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.separatorStyle = .SingleLine
tableView.separatorColor = UIColor.defaultBlackColor()
tableView.bounces = false
view.addSubview(tableView)
}
}
extension MenuViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return 8
default:
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 14)
cell.textLabel?.textColor = UIColor.defaultWhiteColor()
cell.textLabel?.highlightedTextColor = UIColor.lightGrayColor()
cell.selectedBackgroundView = UIView()
let titles = ["Home","Calendar","Profile","Settings","Log Out","Home","Calendar","Profile","Settings","Log Out"]
cell.textLabel?.text = titles[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
defer {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
switch (indexPath.row) {
case 0:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
self.sideMenuViewController.setContentViewController(vc, animated: true)
self.sideMenuViewController.hideMenuViewController()
case 1:
println("1")
default:
println("false")
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch indexPath.section {
case 0:
return 88
case 1:
return 44
default:
return 0
}
}
}
|
gpl-3.0
|
c135918f7e6223c710b82cebeb1d4d55
| 31.824742 | 120 | 0.639447 | 5.595782 | false | false | false | false |
chenchangqing/travelMapMvvm
|
travelMapMvvm/travelMapMvvm/General/ASMapLauncher/ASMapLauncher.swift
|
2
|
8773
|
//
// ASMapLauncher.swift
// ASMapLauncher
//
// Created by Abdullah Selek on 06/06/15.
// Copyright (c) 2015 Abdullah Selek. All rights reserved.
//
// The MIT License (MIT)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import MapKit
enum ASMapApp : String {
case ASMapAppAppleMaps = "Apple Maps",
ASMapAppGoogleMaps = "Google Maps",
ASMapAppYandexNavigator = "Yandex Navigator",
ASMapAppCitymapper = "Citymapper",
ASMapAppNavigon = "Navigon",
ASMapAppTheTransitApp = "The Transit App",
ASMapAppWaze = "Waze"
static let allValues = [ASMapAppAppleMaps, ASMapAppGoogleMaps, ASMapAppYandexNavigator, ASMapAppCitymapper, ASMapAppNavigon, ASMapAppTheTransitApp, ASMapAppWaze]
}
class ASMapLauncher {
private var availableMapApps: NSMutableArray!
init() {
getAvailableNavigationApps()
}
// MARK: Get Available Navigation Apps
func getAvailableNavigationApps() {
self.availableMapApps = NSMutableArray()
for type in ASMapApp.allValues {
if isMapAppInstalled(type) {
self.availableMapApps.addObject(type.rawValue)
}
}
}
func urlPrefixForMapApp(mapApp: ASMapApp) -> String {
switch(mapApp) {
case .ASMapAppGoogleMaps:
return "comgooglemaps://"
case .ASMapAppYandexNavigator:
return "yandexnavi://"
case .ASMapAppCitymapper:
return "citymapper://"
case .ASMapAppNavigon:
return "navigon://"
case .ASMapAppTheTransitApp:
return "transit://"
case .ASMapAppWaze:
return "waze://"
default:
return ""
}
}
func isMapAppInstalled(mapApp: ASMapApp) -> Bool {
if mapApp == .ASMapAppAppleMaps {
return true
}
var urlPrefix: String = urlPrefixForMapApp(mapApp)
if urlPrefix.isEmpty {
return false
}
return UIApplication.sharedApplication().canOpenURL(NSURL(string: urlPrefix)!)
}
func launchMapApp(mapApp: ASMapApp, fromDirections: ASMapPoint!, toDirection: ASMapPoint!) -> Bool {
if !isMapAppInstalled(mapApp) {
return false
}
switch(mapApp) {
case .ASMapAppAppleMaps:
var url: String = NSString(format: "http://maps.apple.com/?saddr=%@&daddr=%@&z=14", googleMapsString(fromDirections), googleMapsString(toDirection)) as String
return UIApplication.sharedApplication().openURL(NSURL(string: url)!)
case .ASMapAppGoogleMaps:
var url: String = NSString(format: "comgooglemaps://?saddr=%@&daddr=%@", googleMapsString(fromDirections), googleMapsString(toDirection)) as String
return UIApplication.sharedApplication().openURL(NSURL(string: url)!)
case .ASMapAppYandexNavigator:
var url: String = NSString(format: "yandexnavi://build_route_on_map?lat_to=%f&lon_to=%f&lat_from=%f&lon_from=%f",
toDirection.location.coordinate.latitude, toDirection.location.coordinate.longitude, fromDirections.location.coordinate.latitude, fromDirections.location.coordinate.longitude) as String
return UIApplication.sharedApplication().openURL(NSURL(string: url)!)
case .ASMapAppCitymapper:
var params: NSMutableArray! = NSMutableArray(capacity: 10)
if CLLocationCoordinate2DIsValid(fromDirections.location.coordinate) {
params.addObject(NSString(format: "startcoord=%f,%f", fromDirections.location.coordinate.latitude, fromDirections.location.coordinate.longitude))
if !fromDirections.name.isEmpty {
params.addObject(NSString(format: "startname=%@", urlEncode(fromDirections.name)))
}
if !fromDirections.address.isEmpty {
params.addObject(NSString(format: "startaddress=%@", urlEncode(fromDirections.address)))
}
}
if CLLocationCoordinate2DIsValid(toDirection.location.coordinate) {
params.addObject(NSString(format: "endcoord=%f,%f", toDirection.location.coordinate.latitude, toDirection.location.coordinate.longitude))
if !toDirection.name.isEmpty {
params.addObject(NSString(format: "endname=%@", urlEncode(toDirection.name)))
}
if !toDirection.address.isEmpty {
params.addObject(NSString(format: "endaddress=%@", urlEncode(toDirection.address)))
}
}
var url: String = NSString(format: "citymapper://directions?%@", params.componentsJoinedByString("&")) as String
return UIApplication.sharedApplication().openURL(NSURL(string: url)!)
case .ASMapAppNavigon:
var name: String = "Destination"
if !toDirection.name.isEmpty {
name = toDirection.name
}
var url: String = NSString(format: "navigon://coordinate/%@/%f/%f", urlEncode(name), toDirection.location.coordinate.longitude, toDirection.location.coordinate.latitude) as String
return UIApplication.sharedApplication().openURL(NSURL(string: url)!)
case .ASMapAppTheTransitApp:
var params = NSMutableArray(capacity: 2)
if fromDirections != nil {
params.addObject(NSString(format: "from=%f,%f", fromDirections.location.coordinate.latitude, fromDirections.location.coordinate.longitude))
}
if toDirection != nil {
params.addObject(NSString(format: "to=%f,%f", toDirection.location.coordinate.latitude, toDirection.location.coordinate.longitude))
}
var url: String = NSString(format: "transit://directions?%@", params.componentsJoinedByString("&")) as String
return UIApplication.sharedApplication().openURL(NSURL(string: url)!)
case .ASMapAppWaze:
var url: String = NSString(format: "waze://?ll=%f,%f&navigate=yes", toDirection.location.coordinate.latitude, toDirection.location.coordinate.longitude) as String
return UIApplication.sharedApplication().openURL(NSURL(string: url)!)
default:
return false
}
}
func googleMapsString(mapPoint: ASMapPoint) -> NSString {
if !CLLocationCoordinate2DIsValid(mapPoint.location.coordinate) {
return ""
}
if !mapPoint.name.isEmpty {
var encodedName = mapPoint.name.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
return NSString(format: "%f,%f+(%@)", mapPoint.location.coordinate.latitude, mapPoint.location.coordinate.longitude, encodedName!)
}
return NSString(format: "%f,%f", mapPoint.location.coordinate.latitude, mapPoint.location.coordinate.longitude)
}
func urlEncode(name: NSString) -> NSString {
return name.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
}
// MARK: Map Apps Getter
func getMapApps() -> NSMutableArray! {
if self.availableMapApps == nil {
self.availableMapApps = NSMutableArray()
}
return self.availableMapApps
}
}
class ASMapPoint: NSObject {
var location: CLLocation!
var name: String!
var address: String!
init(location: CLLocation!, name: String!, address: String!) {
self.location = location
self.name = name
self.address = address
super.init()
}
}
|
apache-2.0
|
69bf0b10865f351fc35c86402e286810
| 42.216749 | 201 | 0.652114 | 4.654111 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard
|
GrandCentralBoardTests/BillableDatesTests.swift
|
2
|
2180
|
//
// BillableDatesTests.swift
// GrandCentralBoard
//
// Created by Maciek Grzybowski on 03.06.2016.
// Copyright © 2016 Oktawian Chojnacki. All rights reserved.
//
import XCTest
import Nimble
@testable import GrandCentralBoard
class BillableDatesTests: XCTestCase {
func testOneDaySetting() {
let someMonday = dateFromDay(30, month: 5, year: 2016)
let sundayBeforeSomeMonday = dateFromDay(29, month: 5, year: 2016)
let fridayBeforeSomeMonday = dateFromDay(27, month: 5, year: 2016)
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let billableDatesIncludingWeekend = calendar.previousDays(1, beforeDate: someMonday, ignoreWeekends: false)
let billableDatesExcludingWeekend = calendar.previousDays(1, beforeDate: someMonday, ignoreWeekends: true)
expect(billableDatesIncludingWeekend) == [sundayBeforeSomeMonday]
expect(billableDatesExcludingWeekend) == [fridayBeforeSomeMonday]
}
func testMultipleDaysSetting() {
let someWednesday = dateFromDay(1, month: 6, year: 2016)
let sixDaysBeforeSomeWednesday = [31, 30, 29, 28, 27, 26].map { dateFromDay($0, month: 5, year: 2016) }
let sixDaysBeforeSomeWednesdayExcludingWeekend = [31, 30, 27, 26, 25, 24].map { dateFromDay($0, month: 5, year: 2016) }
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let billableDatesIncludingWeekend = calendar.previousDays(6, beforeDate: someWednesday, ignoreWeekends: false)
let billableDatesExcludingWeekend = calendar.previousDays(6, beforeDate: someWednesday, ignoreWeekends: true)
expect(billableDatesIncludingWeekend) == sixDaysBeforeSomeWednesday
expect(billableDatesExcludingWeekend) == sixDaysBeforeSomeWednesdayExcludingWeekend
}
}
// MARK: Helpers
private func dateFromDay(day: Int, month: Int, year: Int) -> NSDate {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
return calendar.dateFromComponents(components)!
}
|
gpl-3.0
|
68573a208bf67cf543aa40bd7ce1fbd2
| 37.910714 | 127 | 0.736576 | 4.306324 | false | true | false | false |
longsirhero/DinDinShop
|
DinDinShopDemo/DinDinShopDemo/海外/Views/WCSeasCountryShopCell.swift
|
1
|
5293
|
//
// WCSeasCountryShopCell.swift
// DinDinShopDemo
//
// Created by longsirHERO on 2017/8/24.
// Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved.
//
import UIKit
class WCSeasCountryShopCell: UICollectionViewCell {
var mainImageV:UIImageView = UIImageView()
var topImageV:UIImageView = UIImageView()
var backGView1:UIImageView = UIImageView()
var backGView2:UIImageView = UIImageView()
var imageView1:UIImageView = UIImageView()
var imageView2:UIImageView = UIImageView()
var titleLab1:UILabel = UILabel()
var detailLab1:UILabel = UILabel()
var titleLab2:UILabel = UILabel()
var detailLab2:UILabel = UILabel()
var dataSource:NSArray = NSArray() {
didSet {
let model1:WCSeasDailyModel = dataSource[0] as! WCSeasDailyModel
let model2:WCSeasDailyModel = dataSource[1] as! WCSeasDailyModel
let model3:WCSeasDailyModel = dataSource[2] as! WCSeasDailyModel
let model4:WCSeasDailyModel = dataSource[3] as! WCSeasDailyModel
mainImageV.kf.setImage(with: URL(string: model1.picPath!))
topImageV.kf.setImage(with: URL(string: model2.picPath!))
imageView1.kf.setImage(with: URL(string: model3.picPath!))
imageView2.kf.setImage(with: URL(string: model4.picPath!))
titleLab1.text = model3.picTitle
detailLab1.text = "¥" + model3.primalPrice!
titleLab2.text = model4.picTitle
detailLab2.text = "¥" + model4.primalPrice!
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.backgroundColor = UIColor.white
self.contentView.addSubview(mainImageV)
self.contentView.addSubview(topImageV)
self.contentView.addSubview(backGView1)
self.contentView.addSubview(backGView2)
backGView1.addSubview(imageView1)
backGView2.addSubview(imageView2)
titleLab1.textAlignment = NSTextAlignment.center
titleLab1.font = UIFont.systemFont(ofSize: 14.0)
backGView1.addSubview(titleLab1)
detailLab1.textAlignment = .center
detailLab1.font = UIFont.systemFont(ofSize: 13.0)
detailLab1.textColor = UIColor.flatRed()
backGView1.addSubview(detailLab1)
titleLab2.textAlignment = NSTextAlignment.center
titleLab2.font = UIFont.systemFont(ofSize: 14.0)
backGView2.addSubview(titleLab2)
detailLab2.textAlignment = .center
detailLab2.font = UIFont.systemFont(ofSize: 13.0)
detailLab2.textColor = UIColor.flatRed()
backGView2.addSubview(detailLab2)
mainImageV.snp.makeConstraints { (make) in
make.top.left.bottom.equalToSuperview()
make.width.equalTo(self.contentView.bounds.width / 3.0)
}
topImageV.snp.makeConstraints { (make) in
make.top.right.equalToSuperview()
make.left.equalTo(mainImageV.snp.right).offset(0)
make.bottom.equalTo(self.contentView.snp.centerY)
}
backGView1.snp.makeConstraints { (make) in
make.top.equalTo(topImageV.snp.bottom).offset(0)
make.left.equalTo(mainImageV.snp.right).offset(0)
make.bottom.equalToSuperview()
make.width.equalTo(self.contentView.bounds.width / 6.0 * 2.0)
}
backGView2.snp.makeConstraints { (make) in
make.top.equalTo(topImageV.snp.bottom).offset(0)
make.left.equalTo(backGView1.snp.right).offset(0)
make.right.bottom.equalToSuperview()
}
imageView1.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.left.equalToSuperview().offset(5)
make.right.equalToSuperview().offset(-5)
make.bottom.equalTo(titleLab1.snp.top).offset(0)
}
detailLab1.snp.makeConstraints { (make) in
make.left.right.equalToSuperview()
make.bottom.equalToSuperview()
make.height.equalTo(15)
}
titleLab1.snp.makeConstraints { (make) in
make.bottom.equalTo(detailLab1.snp.top).offset(0)
make.left.right.equalToSuperview()
make.height.equalTo(15)
}
imageView2.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.left.equalToSuperview().offset(5)
make.right.equalToSuperview().offset(-5)
make.bottom.equalTo(titleLab2.snp.top).offset(0)
}
detailLab2.snp.makeConstraints { (make) in
make.left.right.equalToSuperview()
make.bottom.equalToSuperview()
make.height.equalTo(15)
}
titleLab2.snp.makeConstraints { (make) in
make.bottom.equalTo(detailLab2.snp.top).offset(0)
make.left.right.equalToSuperview()
make.height.equalTo(15)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
5a50039dc68b52398421e951f3524db6
| 33.562092 | 86 | 0.614977 | 4.147451 | false | false | false | false |
OptTrader/Download-Indicator
|
RMDownloadIndicator-Swift/RMDownloadIndicator-Swift/ViewController.swift
|
2
|
6076
|
//
// ViewController.swift
// RMDownloadIndicator-Swift
//
// Created by Mahesh Shanbhag on 10/08/15.
// Copyright (c) 2015 Mahesh Shanbhag. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var animationSwitch: UISwitch!
var closedIndicator: RMDownloadIndicator!
var filledIndicator: RMDownloadIndicator!
var mixedIndicator: RMDownloadIndicator!
var downloadedBytes: CGFloat = 0.0
override func viewDidLoad() {
super.viewDidLoad()
self.settingChanged(self.animationSwitch)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func addDownloadIndicators() {
if self.closedIndicator != nil {
self.closedIndicator.removeFromSuperview()
self.closedIndicator = nil
}
if self.filledIndicator != nil {
self.filledIndicator.removeFromSuperview()
self.filledIndicator = nil
}
if self.mixedIndicator != nil {
self.mixedIndicator.removeFromSuperview()
self.mixedIndicator = nil
}
var closedIndicator: RMDownloadIndicator = RMDownloadIndicator(rectframe: CGRectMake((CGRectGetWidth(self.view.bounds) - 80) / 2, CGRectGetMaxY(self.animationSwitch.frame) + 60.0, 80, 80), type: RMIndicatorType.kRMClosedIndicator)
closedIndicator.backgroundColor = UIColor.whiteColor()
closedIndicator.fillColor = UIColor(red: 16/255, green: 119/255, blue: 234/255, alpha: 1.0)
closedIndicator.strokeColor = UIColor(red:16/255, green: 119/255, blue: 234/255, alpha: 1.0)
closedIndicator.radiusPercent = 0.45
self.view.addSubview(closedIndicator)
closedIndicator.loadIndicator()
self.closedIndicator = closedIndicator
var filledIndicator: RMDownloadIndicator = RMDownloadIndicator(rectframe: CGRectMake((CGRectGetWidth(self.view.bounds) - 80) / 2, CGRectGetMaxY(self.closedIndicator.frame) + 40.0, 80, 80), type: RMIndicatorType.kRMFilledIndicator)
filledIndicator.backgroundColor = UIColor.whiteColor()
filledIndicator.fillColor = UIColor(red: 16.0/255, green: 119.0/255.0, blue: 234.0/255.0, alpha: 1.0)
filledIndicator.strokeColor = UIColor(red: 16.0/255.0, green: 119.0/255.0, blue: 234.0/255.0, alpha: 1.0)
filledIndicator.radiusPercent = 0.45
self.view.addSubview(filledIndicator)
filledIndicator.loadIndicator()
self.filledIndicator = filledIndicator
var mixedIndicator: RMDownloadIndicator = RMDownloadIndicator(rectframe: CGRectMake((CGRectGetWidth(self.view.bounds) - 80) / 2, CGRectGetMaxY(self.filledIndicator.frame) + 40.0, 80, 80), type: RMIndicatorType.kRMMixedIndictor)
mixedIndicator.backgroundColor = UIColor.whiteColor()
mixedIndicator.fillColor = UIColor(red: 16.0/255.0, green: 119.0/255.0, blue: 234.0/255.0, alpha: 1.0)
mixedIndicator.strokeColor = UIColor(red: 16.0/255.0, green: 119.0/255.0, blue: 234.0/255.0, alpha: 1.0)
mixedIndicator.closedIndicatorBackgroundStrokeColor = UIColor(red:16.0/255.0, green: 119.0/255.0, blue: 234.0/255.0, alpha: 1.0)
mixedIndicator.radiusPercent = 0.45
self.view.addSubview(mixedIndicator)
mixedIndicator.loadIndicator()
self.mixedIndicator = mixedIndicator
}
func startAnimation() {
self.addDownloadIndicators()
if !animationSwitch.on {
self.updateViewOneTime()
return
}
self.downloadedBytes = 0
self.animationSwitch.userInteractionEnabled = false
var delayInSeconds: Int64 = 1
var popTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Int64(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue(), {() in self.updateView(10.0)
})
var delayInSeconds1: Int64 = delayInSeconds + 1
var popTime1: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds1 * Int64(NSEC_PER_SEC)))
dispatch_after(popTime1, dispatch_get_main_queue(), {() in self.updateView(30.0)
})
var delayInSeconds2: Int64 = delayInSeconds1 + 1
var popTime2: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds2 * Int64(NSEC_PER_SEC)))
dispatch_after(popTime2, dispatch_get_main_queue(), {() in self.updateView(10.0)
})
var delayInSeconds3: Int64 = delayInSeconds2 + 1
var popTime3: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds3 * Int64(NSEC_PER_SEC)))
dispatch_after(popTime3, dispatch_get_main_queue(), {() in self.updateView(50.0)
self.animationSwitch.userInteractionEnabled = true
})
}
func updateView(val: CGFloat) {
self.downloadedBytes += val
closedIndicator.updateWithTotalBytes(100, downloadedBytes: self.downloadedBytes)
filledIndicator.updateWithTotalBytes(100, downloadedBytes: self.downloadedBytes)
mixedIndicator.updateWithTotalBytes(100, downloadedBytes: self.downloadedBytes)
}
func updateViewOneTime() {
closedIndicator.setIndicatorAnimationDuration(1.0)
filledIndicator.setIndicatorAnimationDuration(1.0)
mixedIndicator.setIndicatorAnimationDuration(1.0)
closedIndicator.updateWithTotalBytes(100, downloadedBytes: 100)
filledIndicator.updateWithTotalBytes(100, downloadedBytes: self.downloadedBytes)
mixedIndicator.updateWithTotalBytes(100, downloadedBytes: self.downloadedBytes)
}
@IBAction func settingChanged(sender: UISwitch) {
if self.animationSwitch.on {
//self.settings.setText("Multi Time Animation")
self.startAnimation()
}
else {
//self.settings.setText("One Time Animation")
self.startAnimation()
}
}
}
|
mit
|
2db830f9ba96f5d129fc428a75242b56
| 43.350365 | 238 | 0.669026 | 4.254902 | false | false | false | false |
micazeve/iOS-CustomLocalisator
|
Localisator/Localisator.swift
|
1
|
4117
|
//
// Localisator.swift
// Localisator_Demo-swift
//
// Created by Michaël Azevedo on 10/02/2015.
// Copyright (c) 2015 Michaël Azevedo. All rights reserved.
//
import UIKit
let kNotificationLanguageChanged = NSNotification.Name(rawValue:"kNotificationLanguageChanged")
func Localization(_ string:String) -> String{
return Localisator.sharedInstance.localizedStringForKey(string)
}
func SetLanguage(_ language:String) -> Bool {
return Localisator.sharedInstance.setLanguage(language)
}
class Localisator {
// MARK: - Private properties
private let userDefaults = UserDefaults.standard
private var availableLanguagesArray = ["DeviceLanguage", "English_en", "French_fr"]
private var dicoLocalisation:NSDictionary!
private let kSaveLanguageDefaultKey = "kSaveLanguageDefaultKey"
// MARK: - Public properties
var currentLanguage = "DeviceLanguage"
// MARK: - Public computed properties
var saveInUserDefaults:Bool {
get {
return (userDefaults.object(forKey: kSaveLanguageDefaultKey) != nil)
}
set {
if newValue {
userDefaults.set(currentLanguage, forKey: kSaveLanguageDefaultKey)
} else {
userDefaults.removeObject(forKey: kSaveLanguageDefaultKey)
}
userDefaults.synchronize()
}
}
// MARK: - Singleton method
class var sharedInstance :Localisator {
struct Singleton {
static let instance = Localisator()
}
return Singleton.instance
}
// MARK: - Init method
init() {
if let languageSaved = userDefaults.object(forKey: kSaveLanguageDefaultKey) as? String {
if languageSaved != "DeviceLanguage" {
_ = self.loadDictionaryForLanguage(languageSaved)
}
}
}
// MARK: - Public custom getter
func getArrayAvailableLanguages() -> [String] {
return availableLanguagesArray
}
// MARK: - Private instance methods
fileprivate func loadDictionaryForLanguage(_ newLanguage:String) -> Bool {
let arrayExt = newLanguage.components(separatedBy: "_")
for ext in arrayExt {
if let path = Bundle(for:object_getClass(self)).url(forResource: "Localizable", withExtension: "strings", subdirectory: nil, localization: ext)?.path {
if FileManager.default.fileExists(atPath: path) {
currentLanguage = newLanguage
dicoLocalisation = NSDictionary(contentsOfFile: path)
return true
}
}
}
return false
}
fileprivate func localizedStringForKey(_ key:String) -> String {
if let dico = dicoLocalisation {
if let localizedString = dico[key] as? String {
return localizedString
} else {
return key
}
} else {
return NSLocalizedString(key, comment: key)
}
}
fileprivate func setLanguage(_ newLanguage:String) -> Bool {
if (newLanguage == currentLanguage) || !availableLanguagesArray.contains(newLanguage) {
return false
}
if newLanguage == "DeviceLanguage" {
currentLanguage = newLanguage
dicoLocalisation = nil
userDefaults.removeObject(forKey: kSaveLanguageDefaultKey)
NotificationCenter.default.post(name: kNotificationLanguageChanged, object: nil)
return true
} else if loadDictionaryForLanguage(newLanguage) {
NotificationCenter.default.post(name: kNotificationLanguageChanged, object: nil)
if saveInUserDefaults {
userDefaults.set(currentLanguage, forKey: kSaveLanguageDefaultKey)
userDefaults.synchronize()
}
return true
}
return false
}
}
|
mit
|
44821fcc5ef806933fa61002f6a9c6cc
| 30.174242 | 163 | 0.595869 | 5.29601 | false | false | false | false |
swiftcode/swapscroll
|
swapscroll/swapscroll/Regex.swift
|
1
|
977
|
//
// Regex.swift
// swapscroll
//
// Created by mpc on 4/12/15.
// Copyright (c) 2015 mpc. All rights reserved.
//
import Foundation
class Regex {
let expression: NSRegularExpression?
let pattern: String
init(_ pattern: String) {
self.pattern = pattern
var error : NSError?
do {
self.expression = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
} catch let error1 as NSError {
error = error1
self.expression = nil
}
if error != nil {
if let _ = expression {
print("Regex error")
}
}
}
func test(_ input: String) -> Bool {
if let expression = self.expression {
let matches = expression.matches(in: input, options: [], range:NSMakeRange(0, input.characters.count))
return matches.count > 0
}
return false
}
}
|
mit
|
7339d6eee658df9b665bc32e9ef7c3ad
| 22.829268 | 115 | 0.534289 | 4.523148 | false | false | false | false |
AlesTsurko/DNMKit
|
DNM_iOS/DNM_iOS/SystemLayer.swift
|
1
|
71720
|
//
// SystemLayer.swift
// denm_view
//
// Created by James Bean on 8/19/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
import DNMModel
// THIS IS BEING REFACTORED INTO SYSTEMVIEW (UIVIEW): 2015-11-30
/// A Musical SystemLayer (container of a single line's worth of music)
public class SystemLayer: ViewNode, BuildPattern, DurationSpanning {
// DESTROY --------------------------------------------------------------------------------
public var rhythmCueGraphByID: [String : RhythmCueGraph] = [:]
// DESTROY --------------------------------------------------------------------------------
/// String representation of SystemLayer
public override var description: String { get { return getDescription() } }
public var viewerID: String?
/// PageLayer containing this SystemLayer
public var page: PageLayer?
public var system: System!
/// If this SystemLayer has been built yet
public var hasBeenBuilt: Bool = false
/// All GraphEvents contained within this SystemLayer
public var graphEvents: [GraphEvent] { return getGraphEvents() }
/**
Collection of InstrumentIDsWithInstrumentType, organized by PerformerID.
These values ensure PerformerView order and InstrumentView order,
while making it still possible to call for this information by key identifiers.
*/
public var instrumentIDsAndInstrumentTypesByPerformerID = OrderedDictionary<
String, OrderedDictionary<String, InstrumentType>
>()
/**
All component types (as `String`) by ID.
Currently, this is a PerformerID, however,
this is to be extended to be more generalized at flexibility increases with identifiers.
Examples of these component types are: "dynamics", "articulations", "pitch", etc..
*/
public var componentTypesByID: [String : [String]] = [:]
/// Component types currently displayed
public var componentTypesShownByID: [String : [String]] = [:]
/// Identifiers organizaed by component type (as `String`)
private var idsByComponentType: [String : [String]] = [:]
/// Identifiers that are currently showing a given component type (as `String`)
private var idsShownByComponentType: [String : [String]] = [:]
/// Identifiers that are currently not showing a given component type (as `String`)
private var idsHiddenByComponentType: [String : [String]] = [:]
/// DynamicMarkingNodes organized by identifier `String`
public var dmNodeByID: [String : DMNode] = [:]
/// All Performers in this SystemLayer.
public var performers: [PerformerView] = []
/// Performers organized by identifier `String` -- MAKE ORDERED DICTIONARY
public var performerByID: [String: PerformerView] = [:]
/// SlurHandlers organizaed by identifier `String`
public var slurHandlersByID: [String : [SlurHandler]] = [:]
/// All InstrumentEventHandlers in this SystemLayer
public var instrumentEventHandlers: [InstrumentEventHandler] = []
/** TemporalInfoNode of this SystemLayer. Contains:
- TimeSignatureNode
- MeasureNumberNode
- TempoMarkingsNode
*/
public var temporalInfoNode = TemporalInfoNode(height: 75)
/**
EventsNode of SystemLayer. Stacked after the `temporalInfoNode`.
Contains all non-temporal musical information (`Performers`, `BGStrata`, `DMNodes`, etc).
*/
public var eventsNode = ViewNode(accumulateVerticallyFrom: .Top)
/// Layer for Barlines. First (most background) layer of EventsNode
private let barlinesLayer = CALayer()
/// All Measures (model) contained in this SystemLayer
public var measures: [Measure] = [] { didSet { setMeasuresWithMeasures(measures) } }
/// All MeasureViews contained in this SystemLayer
public var measureViews: [MeasureView] = []
/// All DurationNodes contained in this SystemLayer
public var durationNodes: [DurationNode] = []
/// Graphical height of a single Guidonian staff space
public var g: CGFloat = 0
/// Graphical width of a single 8th-note
public var beatWidth: CGFloat = 0
/// Horiztonal starting point of musical information
public var infoStartX: CGFloat = 50
/// Duration that the beginning of this SystemLayer is offset from the beginning of the piece.
public var offsetDuration: Duration = DurationZero
/// The Duration of this SystemLayer
public var totalDuration: Duration = DurationZero
// make a better interface for this
public var durationInterval: DurationInterval { return system.durationInterval }
/* = DurationIntervalZero {
return DurationInterval(duration: totalDuration, startDuration: offsetDuration)
}*/
/// DurationSpan of SystemLayer
//public var durationSpan: DurationSpan { get { return DurationSpan() } }
/// SystemLayer following this SystemLayer on the PageLayer containing this SystemLayer. May be `nil`.
public var nextSystem: SystemLayer? { get { return getNextSystem() } }
/// SystemLayer preceeding this SystemLayer on the PageLayer containing this SystemLayer. May be `nil`.
public var previousSystem: SystemLayer? { get { return getPreviousSystem() } }
/**
All BGStrata organized by identifier `String`.
This is a temporary implementation that assumes that there is only one PerformerID
per BGStrata (and therefore BGStratum, and therefore BGEvent, etc.).
*/
public var bgStrataByID: [String : [BGStratum]] = [:]
/// All BGStrata in this SystemLayer
public var bgStrata: [BGStratum] = []
/// All Stems in this SystemLayer
public var stems: [Stem] = []
/// All Barlines in this SystemLayer
private var barlines: [Barline] = []
/**
Minimum vertical value for PerformerView, for the purposes of Barline placement.
This is the highest graphTop contained within the
PerformerView -> InstrumentView -> Graph hierarchy.
*/
public var minPerformersTop: CGFloat? { get { return getMinPerformersTop() } }
/**
Maximum vertical value for PerformerView, for the purposes of Barline placement.
This is the lowest graphBottom contained within the
PerformerView -> InstrumentView -> Graph hierarchy.
*/
public var maxPerformersBottom: CGFloat? { get { return getMaxPerformersBottom() } }
/**
Get an array of Systems, starting at a given index, and not exceeding a given maximumHeight.
TODO: throws in the case of single System too large
- parameter systems: The entire reservoir of Systems from which to choose
- parameter index: Index of first SystemLayer in the output range
- parameter maximumHeight: Height which is not to be exceeded by range of Systems
- returns: Array of Systems fulfilling these requirements
*/
public class func rangeFromSystemLayers(
systems: [SystemLayer],
startingAtIndex index: Int,
constrainedByMaximumTotalHeight maximumHeight: CGFloat
) throws -> [SystemLayer]
{
enum SystemRangeError: ErrorType { case Error }
var systemRange: [SystemLayer] = []
var s: Int = index
var accumHeight: CGFloat = 0
while s < systems.count && accumHeight < maximumHeight {
if accumHeight + systems[s].frame.height <= maximumHeight {
systemRange.append(systems[s])
accumHeight += systems[s].frame.height + systems[s].pad_bottom
s++
}
else { break }
}
if systemRange.count == 0 { throw SystemRangeError.Error }
return systemRange
}
// TODO
public init(system: System, g: CGFloat, beatWidth: CGFloat, viewerID: String? = nil) {
self.system = system
// perhaps not necessary -- just reference self.system
self.instrumentIDsAndInstrumentTypesByPerformerID = system.scoreModel.instrumentIDsAndInstrumentTypesByPerformerID
self.durationNodes = system.scoreModel.durationNodes
self.g = g
self.beatWidth = beatWidth
self.viewerID = viewerID
super.init(accumulateVerticallyFrom: .Top)
setsWidthWithContents = true
pad_bottom = 2 * g
self.setMeasuresWithMeasures(system.scoreModel.measures)
}
/**
Create a SystemLayer.
- parameter coder: NSCoder
- returns: SystemLayer
*/
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
/**
Create a SystemLayer
- parameter layer: AnyObject
- returns: SystemLayer
*/
public override init(layer: AnyObject) { super.init(layer: layer) }
// TODO: documentation
public func getDurationAtX(x: CGFloat) -> Duration {
if x <= infoStartX { return DurationZero }
let infoX = round(((x - infoStartX) / beatWidth) * 16) / 16
let floatValue = Float(infoX)
let duration = Duration(floatValue: floatValue) + offsetDuration
return duration
}
/**
Add a MeasureNumber to this SystemLayer
- parameter measureNumber: MeasureNumber to be added
- parameter x: Horizontal placement of MeasureNumber
*/
public func addMeasureNumber(measureNumber: MeasureNumber, atX x: CGFloat) {
temporalInfoNode.addMeasureNumber(measureNumber, atX: x)
}
/**
Add a TimeSignature to this SystemLayer
- parameter timeSignature: TimeSignature to be added
- parameter x: Horizontal placement of TimeSignature
*/
public func addTimeSignature(timeSignature: TimeSignature, atX x: CGFloat) {
temporalInfoNode.addTimeSignature(timeSignature, atX: x)
}
/**
Add a BeamGroupStratum to this SystemLayer
- parameter bgStratum: BeamGroupStratum
*/
public func addBGStratum(bgStratum: BGStratum) {
bgStrata.append(bgStratum)
eventsNode.addNode(bgStratum)
}
/**
Add a PerformerView to this SystemLayer
- parameter performer: PerformerView to be added
*/
public func addPerformer(performer: PerformerView) {
performers.append(performer)
performerByID[performer.id] = performer
eventsNode.addNode(performer)
}
public func addMeasure(measure: MeasureView) {
addMeasureComponentsFromMeasure(measure, atX: measure.frame.minX)
}
/**
Add a TempoMarking
- parameter value: Beats-per-minute value of Tempo
- parameter subdivisionLevel: SubdivisionLevel (1: 1/16th note, etc)
- parameter x: Horizontal placement of TempoMarking
*/
public func addTempoMarkingWithValue(value: Int,
andSubdivisionValue subdivisionValue: Int, atX x: CGFloat
)
{
temporalInfoNode.addTempoMarkingWithValue(value,
andSubdivisionValue: subdivisionValue, atX: x
)
}
/**
Add a RehearsalMarking
- parameter index: Index of the RehearsalMarking
- parameter type: RehearsalMarkingType (.Alphabetical, .Numerical)
- parameter x: Horizonatal placement of RehearsalMarking
*/
public func addRehearsalMarkingWithIndex(index: Int,
type: RehearsalMarkingType, atX x: CGFloat
) {
temporalInfoNode.addRehearsalMarkingWithIndex(index, type: type, atX: x)
}
/**
Set MeasureViews with MeasureViews. Manages the handing-off of Measure-related
graphical components (Barlines, TimeSignatures, MeasureNumbers)
- parameter measures: All MeasureViews in this SystemLayer
*/
public func setMeasuresWithMeasures(measures: [Measure]) {
// create MeasureViews with Measures
self.measureViews = makeMeasureViewsWithMeasures(measures) // ivar necessary?
// don't set
var accumLeft: CGFloat = infoStartX
var accumDur: Duration = DurationZero
for measureView in measureViews {
measureView.system = self
setGraphicalAttributesOfMeasureView(measureView, left: accumLeft)
handoffTimeSignatureFromMeasureView(measureView)
handoffMeasureNumberFromMeasureView(measureView)
addBarlinesForMeasureView(measureView)
accumLeft += measureView.frame.width
accumDur += measureView.dur!
}
totalDuration = accumDur
}
private func makeMeasureViewsWithMeasures(measures: [Measure]) -> [MeasureView] {
let measureViews: [MeasureView] = measures.map { MeasureView(measure: $0) }
return measureViews
}
/**
Add component types (as `String`) with an identifier.
- parameter type: Component type (as `String`). E.g., "dynamics", "articulations", etc.
- parameter id: Identifier by which this component type shall be organized
*/
public func addComponentType(type: String, withID id: String) {
if componentTypesByID[id] == nil {
componentTypesByID[id] = [type]
}
else {
if componentTypesByID[id]!.count == 0 { componentTypesByID[id] = [type] }
else {
if !componentTypesByID[id]!.contains(type) {
componentTypesByID[id]!.append(type)
}
}
}
}
/**
Create Stems.
This is currently `public`, as the SystemLayer `build()` process is fragmented externally.
As the SystemLayer `build()` process becomes clearer, this shall be made `private`,
and called only within the SystemLayer itself.
*/
public func createStems() {
for eventHandler in instrumentEventHandlers {
let stem = eventHandler.makeStemInContext(eventsNode)
let stem_width: CGFloat = 0.0618 * g
stem.lineWidth = stem_width
let hue = HueByTupletDepth[eventHandler.bgEvent!.depth! - 1]
stem.color = UIColor.colorWithHue(hue, andDepthOfField: .MostForeground).CGColor
eventHandler.repositionStemInContext(eventsNode)
stems.append(stem) // addStem()
}
}
// Encapsulate into own Class
/**
Arrange all ViewNodes contained within this SystemLayer to show only those selected.
*/
public func arrangeNodesWithComponentTypesPresent() {
print("arrangeNodesWithComponentTypesPresent: viewerID: \(viewerID); componentTypesShownByID: \(componentTypesShownByID)")
organizeIDsByComponentType()
func addPerformersShown() {
if let performersIDsShown = idsShownByComponentType["pitches"] {
for performerIDShown in performersIDsShown {
if let performer = performerByID[performerIDShown] {
// clean up rhythm cue graph shit // clean this up
if let rhythmCueGraphWithID = rhythmCueGraphByID[performerIDShown] {
if eventsNode.hasNode(rhythmCueGraphWithID) {
eventsNode.removeNode(rhythmCueGraphWithID)
}
}
// anyway, just add the fucking normal thing
eventsNode.addNode(performer)
}
}
}
}
func removeComponentsAsNecessary() {
for (componentTypeHidden, ids) in idsHiddenByComponentType {
for id in ids {
switch componentTypeHidden {
case "performer":
if let performer = performerByID[id] where eventsNode.hasNode(performer) {
eventsNode.removeNode(performer)
}
case "pitches":
if let performer = performerByID[id] where eventsNode.hasNode(performer) {
if let instrument = performer.instrumentByID[id] {
if let staff = instrument.graphByID["staff"]
where instrument.hasNode(staff)
{
let rhythmCueGraph: RhythmCueGraph
if let rCG = rhythmCueGraphByID[id] {
rhythmCueGraph = rCG
}
else {
let rCG = RhythmCueGraph(height: 20, g: g)
rCG.addClefAtX(15) // hack
rhythmCueGraphByID[id] = rCG
rhythmCueGraph = rCG
// add new stems
/*
if let bgStratum = bgStratumByID[id]
where eventsNode.hasNode(bgStratum)
{
// right now this creates WAY too many bgEvents
for _ in bgStratum.bgEvents {
//let x = bgEvent.x_objective!
//let graphEvent = rhythmCueGraph.startEventAtX(x)
/*
let eventHandler = EventHandler(
bgEvent: bgEvent, graphEvent: graphEvent, system: self
)
*/
//print("making rhythm cue graph stem:")
//let stem = eventHandler.makeStemInContext(eventsNode)
// encapsulate within init
//var stem_width: CGFloat = 0.0618 * g
//stem.lineWidth = stem_width
// this will be changed
//stem.strokeColor = colors[eventHandler.bgEvent!.depth! - 1].CGColor
//eventHandlers.append(eventHandler)
}
}
*/
}
rhythmCueGraph.instrument = instrument
instrument.replaceNode(staff, withNode: rhythmCueGraph)
}
}
}
case "rhythm":
// temp usage of bgStrataByID[id]
if let bgStrata = bgStrataByID[id] {
for bgStratum in bgStrata {
if eventsNode.hasNode(bgStratum) {
eventsNode.removeNode(bgStratum)
}
}
}
case "dynamics":
if let dmNode = dmNodeByID[id] {
if eventsNode.hasNode(dmNode) {
eventsNode.removeNode(dmNode, andLayout: false)
}
}
case "articulations":
if let performer = performerByID[id] {
if eventsNode.hasNode(performer) {
for instrument in performer.instruments {
for graph in instrument.graphs {
for event in graph.events {
event.hideArticulations()
}
}
}
}
}
case "slurs":
if let slurHandlers = slurHandlersByID[id] {
for slurHandler in slurHandlers {
if let slur = slurHandler.slur {
slur.removeFromSuperlayer()
}
}
}
default: break
}
}
}
}
func addComponentsAsNecessary() {
for (componentTypeShown, ids) in idsShownByComponentType {
for id in ids {
switch componentTypeShown {
case "performer":
if let performer = performerByID[id] where !eventsNode.hasNode(performer) {
eventsNode.addNode(performer)
}
case "pitches":
if let performer = performerByID[id] where eventsNode.hasNode(performer) {
if let instrument = performer.instruments.first { // hack
if let rhythmCueGraph = rhythmCueGraphByID[id] {
if instrument.hasNode(rhythmCueGraph) {
if let staff = instrument.graphByID["staff"] {
instrument.replaceNode(rhythmCueGraph, withNode: staff)
}
}
}
}
}
case "rhythm":
if let bgStrata = bgStrataByID[id] {
for bgStratum in bgStrata {
if !eventsNode.hasNode(bgStratum) {
eventsNode.addNode(bgStratum, andLayout: false)
}
}
}
case "dynamics":
if let dmNode = dmNodeByID[id] {
if !eventsNode.hasNode(dmNode) {
eventsNode.addNode(dmNode, andLayout: false)
}
}
case "articulations":
if let performer = performerByID[id] {
if eventsNode.hasNode(performer) {
for instrument in performer.instruments {
for graph in instrument.graphs {
for event in graph.events {
event.showArticulations()
}
}
}
}
}
case "slurs":
if let slurHandlers = slurHandlersByID[id] {
for slurHandler in slurHandlers {
if let slur = slurHandler.slur { eventsNode.addSublayer(slur) }
}
}
default: break
}
}
}
}
func sortComponents() {
let sortedPIDs = instrumentIDsAndInstrumentTypesByPerformerID.map { $0.0 }
var sortedPerformers = sortedPIDs
if let viewerID = viewerID where viewerID != "omni" {
sortedPerformers.remove(viewerID)
sortedPerformers.append(viewerID)
}
var index: Int = 0
for id in sortedPIDs {
// ASSUMING STEM DIRECTION IS DESIRED AS IT IS CURRENTLY SET
if id == viewerID {
if let performer = performerByID[id] where eventsNode.hasNode(performer) {
eventsNode.removeNode(performer)
eventsNode.insertNode(performer, atIndex: index, andLayout: false)
index++
}
if let rhythmCueGraph = rhythmCueGraphByID[id] where eventsNode.hasNode(rhythmCueGraph)
{
eventsNode.removeNode(rhythmCueGraph, andLayout: false)
eventsNode.insertNode(rhythmCueGraph, atIndex: index, andLayout: false)
index++
}
if let bgStrata = bgStrataByID[id] {
for bgStratum in bgStrata {
if eventsNode.hasNode(bgStratum) {
eventsNode.removeNode(bgStratum, andLayout: false)
eventsNode.insertNode(bgStratum, atIndex: index, andLayout: false)
index++
}
}
}
if let dmNode = dmNodeByID[id] where eventsNode.hasNode(dmNode) {
eventsNode.removeNode(dmNode, andLayout: false)
eventsNode.insertNode(dmNode, atIndex: index, andLayout: false)
index++
}
}
// ASSUMING STEM DIRECTION IS DESIRED AS IT IS CURRENTLY SET
else {
if let bgStrata = bgStrataByID[id] {
for bgStratum in bgStrata {
if eventsNode.hasNode(bgStratum) {
eventsNode.removeNode(bgStratum, andLayout: false)
eventsNode.insertNode(bgStratum, atIndex: index, andLayout: false)
index++
}
}
}
if let performer = performerByID[id] where eventsNode.hasNode(performer) {
eventsNode.removeNode(performer)
eventsNode.insertNode(performer, atIndex: index, andLayout: false)
index++
}
if let rhythmCueGraph = rhythmCueGraphByID[id] where eventsNode.hasNode(rhythmCueGraph)
{
eventsNode.removeNode(rhythmCueGraph, andLayout: false)
eventsNode.insertNode(rhythmCueGraph, atIndex: index, andLayout: false)
index++
}
if let dmNode = dmNodeByID[id] where eventsNode.hasNode(dmNode) {
eventsNode.removeNode(dmNode, andLayout: false)
eventsNode.insertNode(dmNode, atIndex: index, andLayout: false)
index++
}
}
}
CATransaction.setDisableActions(true)
eventsNode.layout()
CATransaction.setDisableActions(false)
}
removeComponentsAsNecessary()
addComponentsAsNecessary()
sortComponents()
}
/**
Layout this SystemLayer. Calls `ViewNode.layout()`, then adjusts Ligatures.
*/
public override func layout() {
super.layout()
// hack
eventsNode.frame = CGRectMake(
eventsNode.frame.minX,
eventsNode.frame.minY,
self.frame.width,
eventsNode.frame.height
)
adjustLigatures()
}
private func adjustLigatures() {
adjustStems()
adjustSlurs()
adjustBarlines()
// adjustPerformerBrackets()
// adjustMetronomeGridRects()
}
private func organizeIDsByComponentType() {
addPerfomerComponentTypeToComponentTypesByID()
createIDsByComponentType()
createIDsShownByComponentType()
createIDsHiddenByComponentType()
}
private func addPerfomerComponentTypeToComponentTypesByID() {
for (id, componentTypes) in componentTypesByID {
if !componentTypes.contains("performer") {
componentTypesByID[id]!.append("performer")
}
}
}
// user .filter { }
private func createIDsByComponentType() {
idsByComponentType = [:]
for (id, componentTypes) in componentTypesByID {
for componentType in componentTypes {
if idsByComponentType[componentType] == nil {
idsByComponentType[componentType] = [id]
}
else { idsByComponentType[componentType]!.append(id) }
}
}
}
// use .filter { }
private func createIDsShownByComponentType() {
idsShownByComponentType = [:]
for (id, componentTypesShown) in componentTypesShownByID {
for componentTypeShown in componentTypesShown {
if idsShownByComponentType[componentTypeShown] == nil {
idsShownByComponentType[componentTypeShown] = [id]
}
else { idsShownByComponentType[componentTypeShown]!.append(id) }
}
}
}
private func createIDsHiddenByComponentType() {
idsHiddenByComponentType = [:]
for (componentType, ids) in idsByComponentType {
for id in ids {
if let idsShownWithComponentType = idsShownByComponentType[componentType] {
if !idsShownWithComponentType.contains(id) {
if idsHiddenByComponentType[componentType] == nil {
idsHiddenByComponentType[componentType] = [id]
}
else { idsHiddenByComponentType[componentType]!.append(id) }
}
}
else {
// if there isn't even idsShownWithComponentTypeAtAll!
if idsHiddenByComponentType[componentType] == nil {
idsHiddenByComponentType[componentType] = [id]
}
else { idsHiddenByComponentType[componentType]!.append(id) }
}
}
}
}
// TODO: now with OrderedDictionary
private func makePerformerByIDWithBGStrata(bgStrata: [BGStratum]) -> [String : PerformerView] {
var performerByID: [String : PerformerView] = [:]
for bgStratum in bgStrata {
for (performerID, instrumentIDs) in bgStratum.iIDsByPID {
var instrumentTypeByInstrumentID = OrderedDictionary<String, InstrumentType>()
for instrumentID in instrumentIDs {
if let instrumentType = instrumentIDsAndInstrumentTypesByPerformerID[performerID]?[instrumentID]
{
instrumentTypeByInstrumentID[instrumentID] = instrumentType
}
}
/*
var idsAndInstrumentTypes: [(String, InstrumentType)] = []
for iID in instrumentIDs {
if let instrumentType = instrumentTypeByIIDByPID[pID]?[iID] {
idsAndInstrumentTypes.append((iID, instrumentType))
}
}
*/
if let performer = performerByID[performerID] {
performer.addInstrumentsWithInsturmentTypeByInstrumentID(
instrumentTypeByInstrumentID
)
}
else {
let performer = PerformerView(id: performerID)
performer.addInstrumentsWithInsturmentTypeByInstrumentID(
instrumentTypeByInstrumentID
)
performer.pad_bottom = g // HACK
performerByID[performerID] = performer
performers.append(performer)
eventsNode.addNode(performer)
}
/*
if let performer = performerByID[performerID] {
performer.addInstrumentsWithIDsAndInstrumentTypes(idsAndInstrumentTypes)
}
else {
let performer = PerformerView(id: performerID)
performer.addInstrumentsWithIDsAndInstrumentTypes(idsAndInstrumentTypes)
performer.pad_bottom = g // HACK
performerByID[performerID] = performer
performers.append(performer)
eventsNode.addNode(performer)
}
*/
}
}
return performerByID
}
private func sortIDs(ids: [String], withOrderedIDs orderedIDs: [String]) -> [String] {
var ids_sorted: [String] = []
for id in ids {
if ids_sorted.count == 0 { ids_sorted = [id] }
else {
var id_shallBeAppended: Bool = true
if let preferenceIndex: Int = orderedIDs.indexOf(id) {
for i in 0..<ids_sorted.count {
if i > preferenceIndex {
ids_sorted.insert(id, atIndex: i)
id_shallBeAppended = false
break
}
}
}
if id_shallBeAppended { ids_sorted.append(id) }
}
}
return ids_sorted
}
/*
// TODO: reimplement with InstrumentEventHandlers
private func getBGStratumRepresentationByPerformer() -> [PerformerView : [BGStratum : Int]] {
var bgStratumRepresentationByPerformer: [PerformerView : [BGStratum : Int]] = [:]
for eventHandler in eventHandlers {
if eventHandler.bgEvent == nil { continue }
if eventHandler.graphEvent == nil { continue }
let bgStratum = eventHandler.bgEvent!.bgStratum!
let performer = eventHandler.graphEvent!.graph!.instrument!.performer!
if bgStratumRepresentationByPerformer[performer] == nil {
bgStratumRepresentationByPerformer[performer] = [bgStratum : 1]
}
else if bgStratumRepresentationByPerformer[performer]![bgStratum] == nil {
bgStratumRepresentationByPerformer[performer]![bgStratum] = 1
}
else { bgStratumRepresentationByPerformer[performer]![bgStratum]!++ }
}
return bgStratumRepresentationByPerformer
}
*/
/*
// TODO: reimplement: see above
private func arrangeBGStrataAroundPerformers() {
let bgStratumRepresentationByPerformer = getBGStratumRepresentationByPerformer()
for (performer, representationByBGStratum) in bgStratumRepresentationByPerformer {
let bgStrataSorted: [(BGStratum, Int)] = representationByBGStratum.sort({$0.1 > $1.1})
for (bgStratum, representation) in Array(bgStrataSorted.reverse()) {
eventsNode.removeNode(bgStratum)
eventsNode.insertNode(bgStratum, beforeNode: performer)
}
// not sure what this is for, but i could imagine it being worthwhile?
//let mostRepresented = bgStrataSorted.first!.0
}
}
*/
/*
private func getDMNodeRepresentationByPerformer() -> [PerformerView: [DMNode : Int]] {
var dmNodeRepresentationByPerformer: [PerformerView : [DMNode : Int]] = [:]
for eventHandler in eventHandlers {
if eventHandler.bgEvent == nil { continue }
if eventHandler.graphEvent == nil { continue }
let performer = eventHandler.graphEvent!.graph!.instrument!.performer!
for component in eventHandler.bgEvent!.durationNode.components {
if let componentDynamic = component as? ComponentDynamic {
assert(dmNodeByID[componentDynamic.id] != nil,
"dmNodeByID[\(componentDynamic.id)] must exist"
)
let dmNode = dmNodeByID[componentDynamic.id]!
if dmNodeRepresentationByPerformer[performer] == nil {
dmNodeRepresentationByPerformer[performer] = [dmNode : 1]
}
else if dmNodeRepresentationByPerformer[performer]![dmNode] == nil {
dmNodeRepresentationByPerformer[performer]![dmNode] = 1
}
else { dmNodeRepresentationByPerformer[performer]![dmNode]!++ }
}
}
}
return dmNodeRepresentationByPerformer
}
*/
private func getInfoEndYFromGraphEvent(
graphEvent: GraphEvent,
withStemDirection stemDirection: StemDirection
) -> CGFloat
{
let infoEndY = stemDirection == .Down
? convertY(graphEvent.maxInfoY, fromLayer: graphEvent)
: convertY(graphEvent.minInfoY, fromLayer: graphEvent)
return infoEndY
}
private func getBeamEndYFromBGStratum(bgStratum: BGStratum) -> CGFloat {
let beamEndY = bgStratum.stemDirection == .Down
? convertY(bgStratum.beamsLayerGroup!.frame.minY, fromLayer: bgStratum)
: convertY(bgStratum.beamsLayerGroup!.frame.maxY, fromLayer: bgStratum)
return beamEndY
}
private func makeDurationNodesByID(durationNodes: [DurationNode]) -> [String : [DurationNode]] {
var durationNodesByID: [String : [DurationNode]] = [:]
for durationNode in durationNodes {
if let id = durationNode.id {
if durationNodesByID[id] == nil { durationNodesByID[id] = [durationNode] }
else { durationNodesByID[id]!.append(durationNode) }
}
}
return durationNodesByID
}
private func addBeamGroupsToBGStratum(bgStratum: BGStratum,
withDurationNodes durationNodes: [DurationNode]
)
{
var accumLeft: CGFloat = infoStartX
for durationNode in durationNodes {
bgStratum.addBeamGroupWithDurationNode(durationNode, atX: accumLeft)
accumLeft += durationNode.width(beatWidth: beatWidth)
}
}
override func setWidthWithContents() {
if measures.count > 0 {
frame = CGRectMake(frame.minX, frame.minY, measureViews.last!.frame.maxX, frame.height)
}
else {
frame = CGRectMake(frame.minX, frame.minY, 1000, frame.height)
}
}
private func setGraphicalAttributesOfMeasureView(measureView: MeasureView, left: CGFloat) {
measureView.g = g
measureView.beatWidth = beatWidth
measureView.build()
measureView.moveHorizontallyToX(left, animated: false)
}
// takes in a graphically built measure, that has been positioned within the system
private func addBarlinesForMeasureView(measureView: MeasureView) {
addBarlineLeftForMeasureView(measureView)
if measureView === measureViews.last! { addBarlineRightForMeasureView(measureView) }
}
private func addBarlineLeftForMeasureView(measureView: MeasureView) {
let barlineLeft = Barline(x: measureView.frame.minX, top: 0, bottom: frame.height)
barlineLeft.lineWidth = 6
barlineLeft.strokeColor = UIColor.grayscaleColorWithDepthOfField(.Background).CGColor
barlineLeft.opacity = 0.5
barlines.append(barlineLeft)
barlinesLayer.insertSublayer(barlineLeft, atIndex: 0)
}
private func addBarlineRightForMeasureView(measureView: MeasureView) {
let barlineRight = Barline(x: measureView.frame.maxX, top: 0, bottom: frame.height)
barlineRight.lineWidth = 6
barlineRight.strokeColor = UIColor.grayscaleColorWithDepthOfField(.Background).CGColor
barlineRight.opacity = 0.5
barlines.append(barlineRight)
barlinesLayer.insertSublayer(barlineRight, atIndex: 0)
}
private func addMGRectsForMeasure(measure: MeasureView) {
}
private func addMeasureComponentsFromMeasure(measure: MeasureView, atX x: CGFloat) {
if let timeSignature = measure.timeSignature { addTimeSignature(timeSignature, atX: x) }
if let measureNumber = measure.measureNumber { addMeasureNumber(measureNumber, atX: x) }
// barline will become a more complex object -- barline segments, etc
// add barlineLeft
let barlineLeft = Barline(x: x, top: 0, bottom: frame.height)
barlineLeft.lineWidth = 6
barlineLeft.opacity = 0.236
barlines.append(barlineLeft)
insertSublayer(barlineLeft, atIndex: 0)
}
private func addBarline(barline: Barline, atX x: CGFloat) {
barlines.append(barline)
barline.x = x
insertSublayer(barline, atIndex: 0)
}
private func addStem(stem: Stem) {
//eventsNode.insertSublayer(stem, atIndex: 0)
//stems.append(stem)
}
private func addStems(stems: [Stem]) {
for stem in stems { addStem(stem) }
}
public func build() {
clearNodes()
createTemporalInfoNode() // change name of this: // tempo always above?
createEventsNode()
createBGStrata()
createPerformers()
createInstrumentEventHandlers()
decorateInstrumentEvents()
createStemArticulations()
manageGraphLines()
createDMNodes()
createSlurHandlers()
addSlurs()
setDefaultComponentTypesShownByID()
hasBeenBuilt = true
}
private func setDefaultComponentTypesShownByID() {
// make sure "performer" is in all component types
for (id, _) in componentTypesByID {
if !componentTypesByID[id]!.contains("performer") {
componentTypesByID[id]!.append("performer")
}
}
// then transfer all to componentTypesShown
for (id, componentTypes) in componentTypesByID {
componentTypesShownByID[id] = componentTypes
}
// filter out everyone by viewerID
if viewerID != "omni" {
let peerIDs = performerByID.keys.filter { $0 != self.viewerID }
for id in peerIDs { componentTypesShownByID[id] = [] }
}
}
private func addSlurs() {
for (_, slurHandlers) in slurHandlersByID {
for slurHandler in slurHandlers {
if let slur = slurHandler.makeSlurInContext(eventsNode) {
eventsNode.insertSublayer(slur, atIndex: 0)
}
}
}
}
private func createStemArticulations() {
for bgStratum in bgStrata {
for bgEvent in bgStratum.bgEvents {
for saType in bgEvent.stemArticulationTypes {
if bgStratum.saNodeByType[saType] == nil {
let saNode = SANode(left: 0, top: 0, height: 20)
bgStratum.saNodeByType[saType] = saNode
}
bgStratum.saNodeByType[saType]!.addTremoloAtX(bgEvent.x_inBGStratum!)
}
}
for (_, saNode) in bgStratum.saNodeByType {
saNode.layout()
bgStratum.addNode(saNode)
}
}
}
private func manageGraphLines() {
// WRAP: manage graph lines for empty measures
for measureView in measureViews {
var eventsContainedInMeasureByInstrument: [InstrumentView : [InstrumentEventHandler]] = [:]
// initialize each array for each instrument (on the way, flattening all instr.)
for performer in performers {
for (_, instrument) in performer.instrumentByID {
eventsContainedInMeasureByInstrument[instrument] = []
}
}
for eventHandler in instrumentEventHandlers {
// if eventhandler exists within measure...
if eventHandler.isContainedWithinDurationInterval(measureView.measure!.durationInterval) {
if let instrument = eventHandler.instrumentEvent?.instrument {
eventsContainedInMeasureByInstrument[instrument]!.append(eventHandler)
}
}
}
for (instrument, eventHandlers) in eventsContainedInMeasureByInstrument {
if eventHandlers.count == 0 {
for (_, graph) in instrument.graphByID {
let x = measureView.frame.minX
graph.stopLinesAtX(x)
}
}
}
}
// WRAP
// does graph contain any events within the measure? if not: stop lines at measure
for (_, performer) in performerByID {
for (_, instrument) in performer.instrumentByID {
for (_, graph) in instrument.graphByID {
if measureViews.count > 0 {
let x = measureViews.last!.frame.maxX
graph.stopLinesAtX(x)
}
else {
graph.stopLinesAtX(frame.width)
}
graph.build()
}
instrument.layout()
}
}
}
private func decorateInstrumentEvents() {
for instrumentEventHandler in instrumentEventHandlers {
instrumentEventHandler.decorateInstrumentEvent()
}
}
private func getStemDirectionAndGForPID(pID: String) -> (StemDirection, CGFloat) {
let s = getStemDirectionForPID(pID)
let g = getGForPID(pID)
return (s, g)
}
private func getStemDirectionForPID(pID: String) -> StemDirection {
return pID == viewerID ? .Up : .Down
}
private func getGForPID(pID: String) -> CGFloat {
return pID == viewerID ? self.g : 0.75 * self.g
}
// get this out of here
private func createInstrumentEventHandlers() {
var instrumentEventHandlers: [InstrumentEventHandler] = []
func addInstrumentEventHandlerWithBGEvent(bgEvent: BGEvent?,
andInstrumentEvent instrumentEvent: InstrumentEvent?
)
{
let instrumentEventHandler = InstrumentEventHandler(
bgEvent: bgEvent,
instrumentEvent: instrumentEvent,
system: self
)
instrumentEventHandlers.append(instrumentEventHandler)
}
for bgStratum in bgStrata {
for bgEvent in bgStratum.bgEvents {
let durationNode = bgEvent.durationNode
// If DurationNode has no graphBearing components, don't try to populate graphs
if durationNode.hasOnlyExtensionComponents || durationNode.components.count == 0 {
addInstrumentEventHandlerWithBGEvent(bgEvent, andInstrumentEvent: nil)
continue
}
for component in bgEvent.durationNode.components {
var instrumentEventHandlerSuccessfullyCreated: Bool = false
let pID = component.performerID, iID = component.instrumentID
let x: CGFloat = bgEvent.x_objective!
if let performer = performerByID[pID],
instrument = performer.instrumentByID[iID]
{
let (stemDirection, g) = getStemDirectionAndGForPID(pID)
if component.isGraphBearing {
instrument.createGraphsWithComponent(component, andG: g)
if let instrumentEvent = instrument.createInstrumentEventWithComponent(
component,
atX: x,
withStemDirection: stemDirection
)
{
addInstrumentEventHandlerWithBGEvent(bgEvent,
andInstrumentEvent: instrumentEvent
)
// this whole thing is prolly unnecessary
instrumentEventHandlerSuccessfullyCreated = true
}
}
}
else { fatalError("Unable to find PerformerView or InstrumentView") }
// clean up
if !instrumentEventHandlerSuccessfullyCreated {
//print("instrument event unsuccessfully created!")
}
}
}
}
self.instrumentEventHandlers = instrumentEventHandlers
}
private func createSlurHandlers() {
func addSlurHandler(slurHandler: SlurHandler) {
slurHandler.g = slurHandler.id == viewerID ? g : 0.618 * g
if slurHandlersByID[slurHandler.id] == nil {
slurHandlersByID[slurHandler.id] = [slurHandler]
}
else { slurHandlersByID[slurHandler.id]!.append(slurHandler) }
}
func getLastIncompleteSlurHandlerWithID(id: String) -> SlurHandler? {
var lastIncomplete: SlurHandler?
if let slurHandlersWithID = slurHandlersByID[id] {
for slurHandler in slurHandlersWithID {
if slurHandler.graphEvent1 == nil {
lastIncomplete = slurHandler
break
}
}
}
return lastIncomplete
}
for eventHandler in instrumentEventHandlers {
if let instrumentEvent = eventHandler.instrumentEvent, bgEvent = eventHandler.bgEvent {
for graphEvent in instrumentEvent.graphEvents {
for component in bgEvent.durationNode.components {
if let componentSlurStart = component as? ComponentSlurStart {
// TODO: check that this is a valid id!
let id = componentSlurStart.performerID
let slurHandler = SlurHandler(id: id, graphEvent0: graphEvent)
addSlurHandler(slurHandler)
}
else if let componentSlurStop = component as? ComponentSlurStop {
// TODO: check that this is a valid id!
let id = componentSlurStop.performerID
if let lastIncomplete = getLastIncompleteSlurHandlerWithID(id) {
lastIncomplete.graphEvent1 = graphEvent
} else {
let slurHandler = SlurHandler(id: id, graphEvent1: graphEvent)
addSlurHandler(slurHandler)
}
}
}
}
}
}
for (id, _) in slurHandlersByID {
if componentTypesByID[id] == nil { componentTypesByID[id] = [] }
componentTypesByID[id]!.append("slurs")
}
}
private func createPerformers() {
performerByID = makePerformerByIDWithBGStrata(bgStrata) // clean
}
// Encapsulate in BGStratumFactory or something
private func createBGStrata() {
print("create BGStrata")
// get this out of here
func makeBGStrataFromDurationNodeStrata(durationNodeStrata: [[DurationNode]])
-> [BGStratum]
{
// temp
func performerIDsInStratum(stratum: DurationNodeStratum) -> [String] {
var performerIDs: [String] = []
for dn in stratum { performerIDs += performerIDsInDurationNode(dn) }
return performerIDs
}
// temp
func performerIDsInDurationNode(durationNode: DurationNode) -> [String] {
return Array<String>(durationNode.instrumentIDsByPerformerID.keys)
}
// isolate sizing
var bgStrata: [BGStratum] = []
for durationNodeStratum in durationNodeStrata {
// wrap --------------->
let pIDs = performerIDsInStratum(durationNodeStratum)
guard let firstValue = pIDs.first else { continue }
var onlyOnePID: Bool {
for pID in pIDs { if pID != firstValue { return false } }
return true
}
var stemDirection: StemDirection = .Down
var bgStratum_g: CGFloat = g
if onlyOnePID {
let (s, g) = getStemDirectionAndGForPID(firstValue)
stemDirection = s
bgStratum_g = g
}
// <----------------- wrap
// wrap --------------------->
let bgStratum = BGStratum(stemDirection: stemDirection, g: bgStratum_g)
bgStratum.system = self
bgStratum.beatWidth = beatWidth
bgStratum.pad_bottom = 0.5 * g
// <----------------- wrap
for durationNode in durationNodeStratum {
let offset_fromSystem = durationNode.durationInterval.startDuration - system.durationInterval.startDuration
let x = infoStartX + offset_fromSystem.width(beatWidth: beatWidth)
bgStratum.addBeamGroupWithDurationNode(durationNode, atX: x)
}
if !bgStratum.hasBeenBuilt { bgStratum.build() }
bgStrata.append(bgStratum)
}
return bgStrata
}
let durationNodeArranger = DurationNodeStratumArranger(durationNodes: durationNodes)
let durationNodeStrata = durationNodeArranger.makeDurationNodeStrata()
let bgStrata = makeBGStrataFromDurationNodeStrata(durationNodeStrata)
// encapsulate: set initial bgStratum "rhythm" by id
for bgStratum in bgStrata {
// HACK for now
if bgStratum.iIDsByPID.count == 1 {
let id = bgStratum.iIDsByPID.first!.0
if bgStrataByID[id] == nil { bgStrataByID[id] = [bgStratum] }
else { bgStrataByID[id]!.append(bgStratum) }
}
}
addRhythmComponentTypesForBGStrata(bgStrata)
self.bgStrata = bgStrata
}
private func addRhythmComponentTypesForBGStrata(bgStrata: [BGStratum]) {
for bgStratum in bgStrata {
for (pID, _) in bgStratum.iIDsByPID { addComponentType("rhythm", withID: pID) }
}
}
private func createTemporalInfoNode() {
temporalInfoNode.pad_bottom = 0.1236 * temporalInfoNode.frame.height
temporalInfoNode.layout()
addNode(temporalInfoNode)
}
private func createEventsNode() {
addNode(eventsNode)
eventsNode.insertSublayer(barlinesLayer, atIndex: 0)
}
// ENCAPSULATE WITH DMNodeFactory()
private func createDMNodes() {
struct DMComponentContext {
var eventHandler: InstrumentEventHandler
var componentDynamic: ComponentDynamicMarking?
var componentDMLigatures: [ComponentDynamicMarkingSpanner] = []
init(eventHandler: InstrumentEventHandler) {
self.eventHandler = eventHandler
}
}
struct DMComponentContextDyad {
var dmComponentContext0: DMComponentContext?
var dmComponentContext1: DMComponentContext?
init(
dmComponentContext0: DMComponentContext? = nil,
dmComponentContext1: DMComponentContext? = nil
)
{
self.dmComponentContext0 = dmComponentContext0
self.dmComponentContext1 = dmComponentContext1
}
}
func directionFromType(type: Float) -> DMLigatureDirection {
return type == 0 ? .Static : type < 0 ? .Decrescendo : .Crescendo
}
var dmNodeByID: [String : DMNode] = [:]
// deal with DYNAMIC MARKINGS
for eventHandler in instrumentEventHandlers {
// encapsulate in EVENT HANDLER?
if eventHandler.bgEvent == nil || eventHandler.instrumentEvent == nil { continue
}
// create dmComponentContext
var dmComponentContext = DMComponentContext(eventHandler: eventHandler)
for component in eventHandler.bgEvent!.durationNode.components {
if let componentDMLigature = component as? ComponentDynamicMarkingSpanner {
dmComponentContext.componentDMLigatures.append(componentDMLigature)
}
else if let componentDynamic = component as? ComponentDynamicMarking {
dmComponentContext.componentDynamic = componentDynamic
}
}
// Create DynamicMarkings, ensuring DMNodes (no ligature consideration yet)
if dmComponentContext.componentDynamic != nil {
let x = eventHandler.bgEvent!.x_objective!
// TODO: verify as valid (though temporary ) id
let id = dmComponentContext.componentDynamic!.performerID // unsafe
var dmNode_height: CGFloat = 2.5 * g
// HACK, terrible, awful hack
if let bgContainer = eventHandler.bgEvent!.bgContainer {
dmNode_height = 2.5 * bgContainer.g
}
// ensure dmNodeByID
if dmNodeByID[id] == nil {
dmNodeByID[id] = DMNode(height: dmNode_height)
dmNodeByID[id]!.pad_bottom = 0.5 * dmNode_height
} // hack
let marking = dmComponentContext.componentDynamic!.value
dmNodeByID[id]!.addDynamicMarkingsWithString(marking, atX: x)
// this is why we are refactoring this...
// -- you shouldn't have to switch it to extract the property
/*
switch dmComponentContext.componentDynamic!.property {
case .Dynamic(let marking):
dmNodeByID[id]!.addDynamicMarkingsWithString(marking, atX: x)
default: break
}
*/
}
// Create DMLigatures only if they are not frayed
if dmComponentContext.componentDMLigatures.count > 0 {
let x = eventHandler.bgEvent!.x_objective!
// if there is a DynamicMarking
if let componentDynamic = dmComponentContext.componentDynamic {
// TODO: verify is valid ID!
let id = componentDynamic.performerID
var start_intValue: Int?
var stop_intValue: Int?
let start_x: CGFloat!
let stop_x: CGFloat!
if let dynamicMarking = dmNodeByID[id]!.getDynamicMarkingAtX(x) {
let pad = 0.236 * dynamicMarking.height // kerning, etc: refine!
stop_x = dynamicMarking.frame.minX - pad
start_x = dynamicMarking.frame.maxX + pad
start_intValue = dynamicMarking.finalIntValue
stop_intValue = dynamicMarking.initialIntValue
}
else {
start_x = x
stop_x = x
}
for componentDMLigature in dmComponentContext.componentDMLigatures {
switch componentDMLigature {
case is ComponentDynamicMarkingSpannerStart:
if let start_intValue = start_intValue {
dmNodeByID[id]!.startLigatureAtX(start_x,
withDynamicMarkingIntValue: start_intValue
)
}
case is ComponentDynamicMarkingSpannerStop:
if let stop_intValue = stop_intValue {
dmNodeByID[id]!.stopCurrentLigatureAtX(stop_x,
withDynamicMarkingIntValue: stop_intValue
)
}
default: break
}
}
}
}
}
// eek temporary // be explicit about local / semi-global declarations
self.dmNodeByID = dmNodeByID
// build DMNodes
for (id, dmNode) in dmNodeByID {
addComponentType("dynamics", withID: id)
dmNode.build()
}
}
/*
private func handoffMGRectsFromMeasure(measure: MeasureView) {
// hand off mg rects
var accumLeft: CGFloat = measure.frame.minX
for mgRect in measure.mgRects {
mgRect.position.x = accumLeft + 0.5 * mgRect.frame.width
mgRects.append(mgRect)
addSublayer(mgRect)
accumLeft += mgRect.frame.width
}
}
*/
private func handoffTimeSignatureFromMeasureView(measureView: MeasureView) {
if let timeSignature = measureView.timeSignature {
addTimeSignature(timeSignature, atX: measureView.frame.minX)
}
}
private func handoffMeasureNumberFromMeasureView(measureView: MeasureView) {
if measureView.measureNumber != nil {
addMeasureNumber(measureView.measureNumber!, atX: measureView.frame.minX)
}
}
// Must clean up
private func adjustSlurs() {
for (_, slurHandlers) in slurHandlersByID {
// this works, but jesus...clean up
for slurHandler in slurHandlers {
if let graphEvent0 = slurHandler.graphEvent0, graphEvent1 = slurHandler.graphEvent1 {
if let graph0 = graphEvent0.graph, graph1 = graphEvent1.graph {
if let instrument0 = graph0.instrument, instrument1 = graph1.instrument {
if let performer0 = instrument0.performer, performer1 = instrument1.performer {
if eventsNode.hasNode(performer0) &&
eventsNode.hasNode(performer1) &&
performer0.hasNode(instrument0) &&
performer1.hasNode(instrument1) &&
instrument0.hasNode(graph0) &&
instrument1.hasNode(graph1)
{
if let slur = slurHandler.slur where slur.superlayer == nil {
eventsNode.addSublayer(slur)
}
}
else if let slur = slurHandler.slur where slur.superlayer != nil {
slur.removeFromSuperlayer()
}
}
}
}
}
else if let graphEvent0 = slurHandler.graphEvent0 {
if let graph0 = graphEvent0.graph {
if let instrument0 = graph0.instrument {
if let performer0 = instrument0.performer {
if eventsNode.hasNode(performer0) &&
performer0.hasNode(instrument0) &&
instrument0.hasNode(graph0)
{
if let slur = slurHandler.slur where slur.superlayer == nil {
eventsNode.addSublayer(slur)
}
}
else if let slur = slurHandler.slur where slur.superlayer != nil {
slur.removeFromSuperlayer()
}
}
}
}
}
else if let graphEvent1 = slurHandler.graphEvent1 {
if let graph1 = graphEvent1.graph {
if let instrument1 = graph1.instrument {
if let performer1 = instrument1.performer {
if eventsNode.hasNode(performer1) &&
performer1.hasNode(instrument1) &&
instrument1.hasNode(graph1)
{
if let slur = slurHandler.slur where slur.superlayer == nil {
eventsNode.addSublayer(slur)
}
}
else if let slur = slurHandler.slur where slur.superlayer != nil {
slur.removeFromSuperlayer()
}
}
}
}
}
slurHandler.repositionInContext(eventsNode)
}
}
}
private func getMinPerformersTop() -> CGFloat? {
if performers.count == 0 { return 0 }
var minY: CGFloat?
for performer in performers {
if !eventsNode.hasNode(performer) { continue }
if let minInstrumentsTop = performer.minInstrumentsTop {
let performerTop = eventsNode.convertY(minInstrumentsTop, fromLayer: performer)
if minY == nil { minY = performerTop }
else if performerTop < minY! { minY = performerTop }
}
}
return minY
}
private func getMaxPerformersBottom() -> CGFloat? {
var maxY: CGFloat?
for performer in performers {
if !eventsNode.hasNode(performer) { continue }
if let maxInstrumentsBottom = performer.maxInstrumentsBottom {
let performerBottom = eventsNode.convertY(maxInstrumentsBottom,
fromLayer: performer
)
if maxY == nil { maxY = performerBottom }
else if performerBottom > maxY! { maxY = performerBottom }
}
}
return maxY
}
private func adjustBarlines() {
for barline in barlines {
if let minPerformersTop = minPerformersTop, maxPerformersBottom = maxPerformersBottom {
barline.setTop(minPerformersTop, andBottom: maxPerformersBottom)
}
}
}
private func adjustStems() {
for eventHandler in instrumentEventHandlers {
eventHandler.repositionStemInContext(eventsNode)
}
}
private func getInfoEndYForGraphEvent(graphEvent: GraphEvent) -> CGFloat {
return 0
}
private func getBeamEndYForBGEvent(bgEvent: BGEvent) -> CGFloat {
return 0
}
// refine, move down
private func getDurationSpan() -> DurationSpan {
if measures.count == 0 { return DurationSpan() }
let durationSpan = DurationSpan(duration: totalDuration, startDuration: offsetDuration)
return durationSpan
}
private func getGraphEvents() -> [GraphEvent] {
var graphEvents: [GraphEvent] = []
for performer in performers where eventsNode.hasNode(performer) {
for instrument in performer.instruments where performer.hasNode(instrument) {
for graph in instrument.graphs where instrument.hasNode(graph) {
for event in graph.events { graphEvents.append(event) }
}
}
}
return graphEvents.sort {$0.x < $1.x }
}
/*
// TODO:
private func getInstrumentTypeAndIIDByPID() -> [String : [String : InstrumentType]] {
var instrumentTypeByIIDByPID: [String : [String : InstrumentType]] = [:]
for dict in iIDsAndInstrumentTypesByPID {
for (pID, arrayOfIIDsAndInstruments) in dict {
for tuple in arrayOfIIDsAndInstruments {
let iID = tuple.0
let instrumentType = tuple.1
if instrumentTypeByIIDByPID[pID] == nil {
instrumentTypeByIIDByPID[pID] = [iID : instrumentType]
}
else { instrumentTypeByIIDByPID[pID]![iID] = instrumentType }
}
}
}
return instrumentTypeByIIDByPID
}
*/
private func getNextSystem() -> SystemLayer? {
if page == nil { return nil }
if let index = page!.systemLayers.indexOfObject(self) {
if index < page!.systemLayers.count - 1 { return page!.systemLayers[index + 1] }
}
return nil
}
private func getPreviousSystem() -> SystemLayer? {
if page == nil { return nil }
if let index = page?.systemLayers.indexOfObject(self) {
if index > 0 { return page!.systemLayers[index - 1] }
}
return nil
}
/*
// TODO: reimplement when the time is right
private func adjustMetronomeGridRects() {
for mgRect in mgRects {
let f = mgRect.frame
let h = frame.height - timeSignatureNode!.frame.maxY
mgRect.frame = CGRectMake(f.minX, timeSignatureNode!.frame.maxY, f.width, h)
mgRect.path = mgRect.makePath()
}
}
*/
private func getDescription() -> String {
return "SystemLayer: totalDuration: \(totalDuration), offsetDuration: \(offsetDuration)"
}
}
|
gpl-2.0
|
39e1ca76c1a601aebf9c61ad77deeea0
| 40.337176 | 130 | 0.530055 | 5.335838 | false | false | false | false |
huonw/swift
|
test/attr/attr_convention.swift
|
39
|
324
|
// RUN: %target-typecheck-verify-swift
let f1: (Int) -> Int = { $0 }
let f2: @convention(swift) (Int) -> Int = { $0 }
let f3: @convention(block) (Int) -> Int = { $0 }
let f4: @convention(c) (Int) -> Int = { $0 }
let f5: @convention(INTERCAL) (Int) -> Int = { $0 } // expected-error{{convention 'INTERCAL' not supported}}
|
apache-2.0
|
673d6f1720be1f377ebe07c488dcb48e
| 35 | 108 | 0.589506 | 2.634146 | false | false | false | false |
iandundas/Loca
|
LocaExample/LocaExample/LocationsViewController.swift
|
1
|
2270
|
//
// LocationsViewController.swift
// LocaExample
//
// Created by Ian Dundas on 24/11/2016.
// Copyright © 2016 Tacks. All rights reserved.
//
import UIKit
import Loca
import ReactiveKit
class LocationsViewController: UIViewController{
var locationProvider: LocationProvider? = nil
@IBOutlet var lastKnownLabel: UILabel!
@IBOutlet var stackView: UIStackView!
@IBAction func didTapStart(_ sender: AnyObject) {
start()
}
func start() {
guard let locationProvider = locationProvider else {return}
let operation = locationProvider.accurateLocation(meterAccuracy: 10, distanceFilter: 5, maximumAge: 10)
.timeout(after: 15, with: LocationProviderError.timeout, on: DispatchQueue.main)
.observeIn(DispatchQueue.main.context)
.shareReplay()
operation.observe { [weak self] event in
switch event {
case let .next(accuracy):
self?.addMessage(accuracy.debugDescription)
case let .failed(error):
self?.addMessage("💔 Failure: \(error)")
case .completed:
self?.addMessage("Completed.")
}
}.dispose(in: reactive.bag)
operation.suppressError(logging: true)
.map { accuracy -> String in
switch accuracy {
case let .accurate(to: _, at: location):
return location.timestamp.description
case let .inaccurate(to: _, at: location):
return location.timestamp.description
}
}
.map { (date: String) -> String in
return "Last updated: \(date)"
}
.combineLatest(with: SafeSignal<UILabel>.just(lastKnownLabel))
.observeNext { (string: String, label: UILabel) in
label.text = string
}.dispose(in: reactive.bag)
}
func addMessage(_ message: String) {
let label = UILabel()
label.text = message
label.numberOfLines = 0
label.sizeToFit()
stackView.insertArrangedSubview(label, at: 0)
}
}
|
apache-2.0
|
2b082374c0edb65db211872dfe767c5f
| 29.621622 | 111 | 0.558694 | 5.115124 | false | false | false | false |
SeriousChoice/SCSwift
|
Example/scswift-example/AppDelegate.swift
|
1
|
2742
|
//
// AppDelegate.swift
// SCSwift
//
// Created by Nicola Innocenti on 08/01/2022.
// Copyright © 2022 Nicola Innocenti. All rights reserved.
//
import UIKit
import SCSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
if #available(iOS 15, *) {
let navAppearance = UINavigationBarAppearance()
navAppearance.backgroundColor = .white
UINavigationBar.appearance().standardAppearance = navAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navAppearance
} else {
UINavigationBar.appearance().isTranslucent = false
}
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UINavigationController(rootViewController: ViewController())
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
f3faaaadba96599219c37eceb7d79559
| 45.457627 | 285 | 0.729296 | 5.881974 | false | false | false | false |
eofster/Telephone
|
Telephone/PresentationCallHistoryRecord.swift
|
1
|
2437
|
//
// PresentationCallHistoryRecord.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Cocoa
import UseCases
final class PresentationCallHistoryRecord: NSObject {
let identifier: String
@objc let contact: PresentationContact
@objc let date: String
@objc let duration: String
@objc let isIncoming: Bool
init(identifier: String, contact: PresentationContact, date: String, duration: String, isIncoming: Bool) {
self.identifier = identifier
self.contact = contact
self.date = date
self.duration = duration
self.isIncoming = isIncoming
}
}
extension PresentationCallHistoryRecord {
override func isEqual(_ object: Any?) -> Bool {
guard let record = object as? PresentationCallHistoryRecord else { return false }
return isEqual(to: record)
}
override var hash: Int {
var hasher = Hasher()
hasher.combine(identifier)
hasher.combine(contact)
hasher.combine(date)
hasher.combine(duration)
hasher.combine(isIncoming)
return hasher.finalize()
}
private func isEqual(to record: PresentationCallHistoryRecord) -> Bool {
return
identifier == record.identifier &&
contact == record.contact &&
date == record.date &&
duration == record.duration &&
isIncoming == record.isIncoming
}
}
extension PresentationCallHistoryRecord: NSPasteboardWriting {
func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] {
return [.string]
}
func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? {
return contact.address
}
}
extension PresentationCallHistoryRecord {
var name: String {
return contact.title.isEmpty ? date : "\(contact.title), \(date)"
}
}
|
gpl-3.0
|
9eec1f1c7e2bdaa3817c367b387ce27e
| 30.217949 | 110 | 0.679261 | 4.78389 | false | false | false | false |
RoverPlatform/rover-ios
|
Sources/Notifications/Services/InfluenceTracker/InfluenceTrackerService.swift
|
1
|
3012
|
//
// InfluenceTrackerService.swift
// RoverNotifications
//
// Created by Sean Rucker on 2018-03-11.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
import UIKit
#if !COCOAPODS
import RoverFoundation
import RoverData
#endif
class InfluenceTrackerService: InfluenceTracker {
let influenceTime: Int
let eventQueue: EventQueue?
let notificationCenter: NotificationCenter
let userDefaults: UserDefaults
var didBecomeActiveObserver: NSObjectProtocol?
init(influenceTime: Int, eventQueue: EventQueue?, notificationCenter: NotificationCenter, userDefaults: UserDefaults) {
self.influenceTime = influenceTime
self.eventQueue = eventQueue
self.notificationCenter = notificationCenter
self.userDefaults = userDefaults
}
deinit {
self.stopMonitoring()
}
func startMonitoring() {
self.didBecomeActiveObserver = notificationCenter.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: OperationQueue.main) { [weak self] _ in
self?.trackInfluencedOpen()
}
}
func stopMonitoring() {
if let didBecomeActiveObserver = self.didBecomeActiveObserver {
notificationCenter.removeObserver(didBecomeActiveObserver)
}
}
func trackInfluencedOpen() {
guard let data = userDefaults.value(forKey: "io.rover.lastReceivedNotification") as? Data else {
return
}
defer {
clearLastReceivedNotification()
}
struct NotificationReceipt: Decodable {
var notificationID: String
var campaignID: String
var receivedAt: Date
var attributes: Attributes {
return [
"id": notificationID,
"campaignID": campaignID
]
}
}
guard let lastReceivedNotification = try? PropertyListDecoder().decode(NotificationReceipt.self, from: data) else {
return
}
let now = Date().timeIntervalSince1970
// If its been more than the alloted influence time since the notification was received, don't consider this an influenced open
if now - lastReceivedNotification.receivedAt.timeIntervalSince1970 > TimeInterval(influenceTime) {
return
}
guard let eventQueue = eventQueue else {
return
}
let attributes: Attributes = [
"notification": lastReceivedNotification.attributes,
"source": NotificationSource.influencedOpen.rawValue
]
let event = EventInfo(name: "Notification Opened", namespace: "rover", attributes: attributes)
eventQueue.addEvent(event)
}
func clearLastReceivedNotification() {
userDefaults.removeObject(forKey: "io.rover.lastReceivedNotification")
}
}
|
apache-2.0
|
29e6f6315419400cb9be8e35ebd6d62d
| 30.364583 | 181 | 0.631352 | 5.54512 | false | false | false | false |
nbhasin2/NBNavigationController
|
NBNavigationController/BottomUpTransition.swift
|
2
|
2458
|
//
// BottomUpTransition.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Nishant Bhasin. <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
public class BottomUpTransition: BaseTransition, UIViewControllerAnimatedTransitioning {
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return transitionDuration
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to),
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
else {
transitionContext.completeTransition(true)
return
}
toView.frame = container.frame
toView.frame.origin.y = container.frame.maxY
container.addSubview(toView)
UIView.animate(
withDuration: transitionDuration,
animations: {
fromViewController.view.frame.origin.y = -container.frame.maxY
toView.frame = container.frame
},
completion: { _ in
transitionContext.completeTransition(true)
}
)
}
}
|
mit
|
29f0f4aec3e2ddba5dc81c0ee1bf0aef
| 38.645161 | 120 | 0.71074 | 5.274678 | false | false | false | false |
LeeMinglu/Swift-Statement
|
Swift Statement/Swift Statement/Person.swift
|
1
|
1237
|
//
// Person.swift
// Swift Statement
//
// Created by 李明禄 on 2017/4/3.
// Copyright © 2017年 SocererGroup. All rights reserved.
//
import UIKit
/**
1.定义模型属性的时候,如果是对象,通常是可选的;
-在需要的时候创建
-避免写构造函数,可以简化代码
2.如果是基本数据类型,不能设置为可选的,而且要设置初始值。
3.如果需要使用KVC设置数值,属性不能是private
4.使用KVC方法之前,应该调用super.init,保证对象实例化完成。
*/
class Person: NSObject {
var name: String?
var age: Int = 0
var title: String?
init(dict:[String: Any]) {
super.init()
setValuesForKeys(dict)
}
class func porpertyList() -> [String] {
var count: UInt32 = 0
var nameList: [String] = []
let list = class_copyPropertyList(self, &count)
for i in 0..<Int(count) {
let pty = list?[i]
let cName = property_getName(pty!)
let name = String(utf8String: cName!)
nameList.append(name!)
}
return [nameList]
}
}
|
apache-2.0
|
9e6825333bad752411ed19de1cb5618a
| 18.018868 | 56 | 0.530754 | 3.536842 | false | false | false | false |
maxep/MXParallaxBackground
|
Examples/swift/MXHorizontalViewController.swift
|
1
|
3877
|
// MXHorizontalViewController.swift
//
// Copyright (c) 2019 Maxime Epain
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import MXParallaxBackground
class MXHorizontalViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
loadPages()
// Sets backgrounds
let clouds1 = MXParallaxBackground()
clouds1.view = Bundle.main.loadNibNamed("Clouds1", owner: self, options: nil)?[0] as? UIView
clouds1.intensity = 0.25
scrollView.add(background: clouds1)
let clouds2 = MXParallaxBackground()
clouds2.view = Bundle.main.loadNibNamed("Clouds2", owner: self, options: nil)?[0] as? UIView
clouds2.intensity = 0.5
clouds2.isReverse = true
scrollView.add(background: clouds2)
scrollView.bringBackground(toFront: clouds2)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate func loadPages() {
var views = Dictionary<String,UIView>()
var format = "H:|"
for i in 1...3 {
let imageName = "Balloon\(i)"
let imageView = UIImageView()
imageView.image = UIImage(named: imageName);
imageView.contentMode = UIViewContentMode.center
imageView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(imageView)
views[imageName] = imageView
scrollView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:|[\(imageName)]|",
options: .directionLeadingToTrailing,
metrics: nil,
views: views)
)
scrollView.addConstraint( NSLayoutConstraint(
item: imageView,
attribute: .centerY,
relatedBy: .equal,
toItem: scrollView,
attribute: .centerY,
multiplier: 1,
constant: 0)
)
view.addConstraint( NSLayoutConstraint(
item: imageView,
attribute: .width,
relatedBy: .equal,
toItem: view,
attribute: .width,
multiplier: 1,
constant: 0)
)
format += "[\(imageName)]"
}
format += "|"
scrollView.addConstraints( NSLayoutConstraint.constraints(
withVisualFormat: format,
options: .directionLeadingToTrailing,
metrics: nil,
views: views)
)
}
}
|
mit
|
bbaad89c4d500721953bfe218642657f
| 35.233645 | 100 | 0.607944 | 5.407252 | false | false | false | false |
liufengting/FTChatMessageDemoProject
|
FTChatMessage/FTChatMessageTableViewController+DataSource.swift
|
1
|
11931
|
//
// FTChatMessageTableViewController+DataSource.swift
// Demo
//
// Created by liufengting on 16/9/27.
// Copyright © 2016年 liufengting <https://github.com/liufengting>. All rights reserved.
//
import UIKit
extension FTChatMessageTableViewController{
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboradWillChangeFrame(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
//MARK: - scrollToBottom -
func scrollToBottom(_ animated: Bool) {
if self.messageArray.count > 0 {
let lastSection = self.messageArray.count - 1
let lastSectionMessageCount = messageArray[lastSection].count - 1
self.messageTableView.scrollToRow(at: IndexPath(row: lastSectionMessageCount, section: lastSection), at: UITableViewScrollPosition.top, animated: animated)
}
}
//MARK: - keyborad notification functions -
@objc fileprivate func keyboradWillChangeFrame(_ notification : Notification) {
if messageInputMode == FTChatMessageInputMode.keyboard {
if let userInfo = (notification as NSNotification).userInfo {
let duration = (userInfo["UIKeyboardAnimationDurationUserInfoKey"]! as AnyObject).doubleValue
let keyFrame : CGRect = (userInfo["UIKeyboardFrameEndUserInfoKey"]! as AnyObject).cgRectValue
let keyboradOriginY = min(keyFrame.origin.y, FTScreenHeight)
let inputBarHeight = messageInputView.frame.height
UIView.animate(withDuration: duration!, animations: {
self.messageTableView.frame = CGRect(x: 0 , y: 0 , width: FTScreenWidth, height: keyboradOriginY)
self.messageInputView.frame = CGRect(x: 0, y: keyboradOriginY - inputBarHeight, width: FTScreenWidth, height: inputBarHeight)
self.scrollToBottom(true)
}, completion: { (finished) in
if finished {
if self.messageInputView.inputTextView.isFirstResponder {
self.dismissInputRecordView()
self.dismissInputAccessoryView()
}
}
})
}
}
}
//MARK: - FTChatMessageInputViewDelegate -
internal func ft_chatMessageInputViewShouldBeginEditing() {
let originMode = messageInputMode
messageInputMode = FTChatMessageInputMode.keyboard;
switch originMode {
case .keyboard: break
case .accessory:
self.dismissInputAccessoryView()
case .record:
self.dismissInputRecordView()
case .none: break
}
}
internal func ft_chatMessageInputViewShouldEndEditing() {
messageInputMode = FTChatMessageInputMode.none;
}
internal func ft_chatMessageInputViewShouldUpdateHeight(_ desiredHeight: CGFloat) {
var origin = messageInputView.frame;
origin.origin.y = origin.origin.y + origin.size.height - desiredHeight;
origin.size.height = desiredHeight;
messageTableView.frame = CGRect(x: 0, y: 0, width: FTScreenWidth, height: origin.origin.y + FTDefaultInputViewHeight)
messageInputView.frame = origin
self.scrollToBottom(true)
messageInputView.layoutIfNeeded()
}
internal func ft_chatMessageInputViewShouldDoneWithText(_ textString: String) {
let message8 = FTChatMessageModel(data: textString, time: "4.12 22:42", from: sender2, type: .text)
self.addNewMessage(message8)
}
internal func ft_chatMessageInputViewShouldShowRecordView(){
let originMode = messageInputMode
let inputViewFrameHeight = self.messageInputView.frame.size.height
if originMode == FTChatMessageInputMode.record {
messageInputMode = FTChatMessageInputMode.none
UIView.animate(withDuration: FTDefaultMessageDefaultAnimationDuration, animations: {
self.messageTableView.frame = CGRect(x: 0, y: 0, width: FTScreenWidth, height: FTScreenHeight - inputViewFrameHeight + FTDefaultInputViewHeight )
self.messageInputView.frame = CGRect(x: 0, y: FTScreenHeight - inputViewFrameHeight, width: FTScreenWidth, height: inputViewFrameHeight)
self.messageRecordView.frame = CGRect(x: 0, y: FTScreenHeight, width: FTScreenWidth, height: FTDefaultAccessoryViewHeight)
self.scrollToBottom(true)
}, completion: { (finished) in
})
}else{
switch originMode {
case .keyboard:
self.messageInputView.inputTextView.resignFirstResponder()
case .accessory:
self.dismissInputAccessoryView()
case .none: break
case .record: break
}
messageInputMode = FTChatMessageInputMode.record
UIView.animate(withDuration: FTDefaultMessageDefaultAnimationDuration, animations: {
self.messageTableView.frame = CGRect(x: 0, y: 0, width: FTScreenWidth, height: FTScreenHeight - inputViewFrameHeight - FTDefaultAccessoryViewHeight + FTDefaultInputViewHeight )
self.messageInputView.frame = CGRect(x: 0, y: FTScreenHeight - inputViewFrameHeight - FTDefaultAccessoryViewHeight, width: FTScreenWidth, height: inputViewFrameHeight)
self.messageRecordView.frame = CGRect(x: 0, y: FTScreenHeight - FTDefaultAccessoryViewHeight, width: FTScreenWidth, height: FTDefaultAccessoryViewHeight)
self.scrollToBottom(true)
}, completion: { (finished) in
})
}
}
internal func ft_chatMessageInputViewShouldShowAccessoryView(){
let originMode = messageInputMode
let inputViewFrameHeight = self.messageInputView.frame.size.height
if originMode == FTChatMessageInputMode.accessory {
messageInputMode = FTChatMessageInputMode.none
UIView.animate(withDuration: FTDefaultMessageDefaultAnimationDuration, animations: {
self.messageTableView.frame = CGRect(x: 0, y: 0, width: FTScreenWidth, height: FTScreenHeight - inputViewFrameHeight + FTDefaultInputViewHeight )
self.messageInputView.frame = CGRect(x: 0, y: FTScreenHeight - inputViewFrameHeight, width: FTScreenWidth, height: inputViewFrameHeight)
self.messageAccessoryView.frame = CGRect(x: 0, y: FTScreenHeight, width: FTScreenWidth, height: FTDefaultAccessoryViewHeight)
self.scrollToBottom(true)
}, completion: { (finished) in
})
}else{
switch originMode {
case .keyboard:
self.messageInputView.inputTextView.resignFirstResponder()
case .record:
self.dismissInputRecordView()
case .none: break
case .accessory: break
}
messageInputMode = FTChatMessageInputMode.accessory
UIView.animate(withDuration: FTDefaultMessageDefaultAnimationDuration, animations: {
self.messageTableView.frame = CGRect(x: 0, y: 0, width: FTScreenWidth, height: FTScreenHeight - inputViewFrameHeight - FTDefaultAccessoryViewHeight + FTDefaultInputViewHeight )
self.messageInputView.frame = CGRect(x: 0, y: FTScreenHeight - inputViewFrameHeight - FTDefaultAccessoryViewHeight, width: FTScreenWidth, height: inputViewFrameHeight)
self.messageAccessoryView.frame = CGRect(x: 0, y: FTScreenHeight - FTDefaultAccessoryViewHeight, width: FTScreenWidth, height: FTDefaultAccessoryViewHeight)
self.scrollToBottom(true)
}, completion: { (finished) in
})
}
}
//MARK: - dismissInputRecordView -
fileprivate func dismissInputRecordView(){
UIView.animate(withDuration: FTDefaultMessageDefaultAnimationDuration, animations: {
self.messageRecordView.frame = CGRect(x: 0, y: FTScreenHeight, width: FTScreenWidth, height: FTDefaultAccessoryViewHeight)
})
}
//MARK: - dismissInputAccessoryView -
fileprivate func dismissInputAccessoryView(){
UIView.animate(withDuration: FTDefaultMessageDefaultAnimationDuration, animations: {
self.messageAccessoryView.frame = CGRect(x: 0, y: FTScreenHeight, width: FTScreenWidth, height: FTDefaultAccessoryViewHeight)
})
}
//MARK: - UITableViewDelegate,UITableViewDataSource -
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
switch self.messageInputMode {
case .accessory:
self.ft_chatMessageInputViewShouldShowAccessoryView()
case .record:
self.ft_chatMessageInputViewShouldShowRecordView()
default:
break;
}
}
@objc(numberOfSectionsInTableView:)
func numberOfSections(in tableView: UITableView) -> Int {
return messageArray.count;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let messages : [FTChatMessageModel] = messageArray[section]
return messages.count;
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let message = messageArray[section][0]
let header = FTChatMessageHeader(frame: CGRect(x: 0,y: 0,width: tableView.frame.width,height: FTDefaultSectionHeight), senderModel: message.messageSender)
header.headerViewDelegate = self
return header
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return FTDefaultSectionHeight
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0
}
@objc(tableView:heightForRowAtIndexPath:)
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let message = messageArray[indexPath.section][indexPath.row]
return FTChatMessageCell.getCellHeightWithMessage(message, for: indexPath)
}
@objc(tableView:cellForRowAtIndexPath:)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let message = messageArray[indexPath.section][indexPath.row]
let cell = FTChatMessageCell(style: UITableViewCellStyle.default, reuseIdentifier: FTDefaultMessageCellReuseIndentifier, theMessage: message, for: indexPath)
return cell
}
@objc(tableView:didSelectRowAtIndexPath:)
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
//MARK: - FTChatMessageHeaderDelegate -
func ft_chatMessageHeaderDidTappedOnIcon(_ messageSenderModel: FTChatMessageUserModel) {
print("tapped at user icon : \(messageSenderModel.senderName!)")
}
//MARK: - preferredInterfaceOrientationForPresentation -
override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation {
return UIInterfaceOrientation.portrait
}
}
|
mit
|
95ad339f22f9dd1afedab4837aae06d4
| 44.353612 | 192 | 0.655349 | 5.504384 | false | false | false | false |
leo150/Pelican
|
Sources/Pelican/Pelican/Builder/Spawn.swift
|
1
|
4258
|
//
// Builder+Spawn.swift
// Pelican
//
// Created by Takanu Kyriako on 20/08/2017.
//
import Foundation
import Vapor
/**
Defines a collection of functions that generate filtering closures.
A function that's used as a Spawner must always return a function of type `(Update) -> String?`.
*/
public class Spawn {
/**
A spawner that returns Chat IDs, that are tied to specific update types, originating from specific chat types.
- parameter updateType: The update types the spawner is looking for. If nil, all update types will be accepted.
- parameter chatType: The types of chat the update originated from that the spawner is looking for. If nil, all chat types will be accepted.
*/
public static func perChatID(updateType: [UpdateType]?, chatType: [ChatType]?) -> ((Update) -> Int?) {
return { update in
if update.chat == nil { return nil }
if updateType != nil {
if updateType!.contains(update.type) == false { return nil }
}
if chatType != nil {
if chatType!.contains(update.chat!.type) == false { return nil }
}
return update.chat!.tgID
}
}
/**
A spawner that returns Chat IDs if they both match the inclusion list, and that match the defines update and chat types.
- parameter include: The Chat IDs that are allowed to pass-through this spawner.
- parameter updateType: The update types the spawner is looking for. If nil, all update types will be accepted.
- parameter chatType: The types of chat the update originated from that the spawner is looking for. If nil, all chat types will be accepted.
*/
public static func perChatID(include: [Int], updateType: [UpdateType]?, chatType: [ChatType]?) -> ((Update) -> Int?) {
return { update in
if update.chat == nil { return nil }
if include.count > 0 {
if include.contains(update.chat!.tgID) == false { return nil }
}
if updateType != nil {
if updateType!.contains(update.type) == false { return nil }
}
if chatType != nil {
if chatType!.contains(update.chat!.type) == false { return nil }
}
return update.chat!.tgID
}
}
/**
A spawner that returns Chat IDs if they both **do not** match the excluision list, and that match the defines update and chat types.
- parameter exclude: The Chat IDs that are not allowed to pass-through this spawner.
- parameter updateType: The update types the spawner is looking for. If nil, all update types will be accepted.
- parameter chatType: The types of chat the update originated from that the spawner is looking for. If nil, all chat types will be accepted.
*/
public static func perChatID(exclude: [Int], updateType: [UpdateType]?, chatType: [ChatType]?) -> ((Update) -> Int?) {
return { update in
if update.chat == nil { return nil }
if exclude.count > 0 {
if exclude.contains(update.chat!.tgID) == true { return nil }
}
if updateType != nil {
if updateType!.contains(update.type) == false { return nil }
}
if chatType != nil {
if chatType!.contains(update.chat!.type) == false { return nil }
}
return update.chat!.tgID
}
}
public static func perUserID(updateType: [UpdateType]?) -> ((Update) -> Int?) {
return { update in
if update.from == nil { return nil }
if updateType == nil { return update.from!.tgID }
else if updateType!.contains(update.type) == true { return update.from!.tgID }
return nil
}
}
public static func perUserID(include: [Int], updateType: [UpdateType]?) -> ((Update) -> Int?) {
return { update in
if update.chat == nil { return nil }
if include.count > 0 {
if include.contains(update.from!.tgID) == false { return nil }
}
if updateType != nil {
if updateType!.contains(update.type) == false { return nil }
}
return update.from!.tgID
}
}
public static func perUserID(exclude: [Int], updateType: [UpdateType]?) -> ((Update) -> Int?) {
return { update in
if update.chat == nil { return nil }
if exclude.count > 0 {
if exclude.contains(update.from!.tgID) == true { return nil }
}
if updateType != nil {
if updateType!.contains(update.type) == false { return nil }
}
return update.from!.tgID
}
}
}
|
mit
|
be77af7195729f9d1dcb32650e85ec9d
| 28.569444 | 142 | 0.657116 | 3.593249 | false | false | false | false |
kciter/KCSelectionDialog
|
SelectionDialog/SelectionDialog.swift
|
1
|
10874
|
//
// SelectionDialog.swift
// Sample
//
// Created by LeeSunhyoup on 2015. 9. 28..
// Copyright © 2015년 SelectionView. All rights reserved.
//
import UIKit
open class SelectionDialog: UIView {
open var items: [SelectionDialogItem] = []
open var titleHeight: CGFloat = 50
open var buttonHeight: CGFloat = 50
open var cornerRadius: CGFloat = 7
open var itemPadding: CGFloat = 10
open var minHeight: CGFloat = 300
open var useMotionEffects: Bool = true
open var motionEffectExtent: Int = 10
open var title: String? = "Title"
open var closeButtonTitle: String? = "Close"
open var closeButtonColor: UIColor?
open var closeButtonColorHighlighted: UIColor?
fileprivate var dialogView: UIView?
public init() {
super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
setObservers()
}
public init(title: String, closeButtonTitle cancelString: String) {
self.title = title
self.closeButtonTitle = cancelString
super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
setObservers()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setObservers()
}
open func show() {
dialogView = createDialogView()
guard let dialogView = dialogView else { return }
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
self.backgroundColor = UIColor(white: 0, alpha: 0)
dialogView.layer.opacity = 0.5
dialogView.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1)
self.addSubview(dialogView)
self.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
UIApplication.shared.keyWindow?.addSubview(self)
UIView.animate(withDuration: 0.2, delay: 0, animations: {
self.backgroundColor = UIColor(white: 0, alpha: 0.4)
dialogView.layer.opacity = 1
dialogView.layer.transform = CATransform3DMakeScale(1, 1, 1)
}, completion: nil)
}
@objc open func close() {
guard let dialogView = dialogView else { return }
let currentTransform = dialogView.layer.transform
dialogView.layer.opacity = 1
UIView.animate(withDuration: 0.2, delay: 0, animations: {
self.backgroundColor = UIColor(white: 0, alpha: 0)
dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1))
dialogView.layer.opacity = 0
}, completion: { (finished: Bool) in
for view in self.subviews {
view.removeFromSuperview()
}
self.removeFromSuperview()
})
}
open func addItem(item itemTitle: String) {
let item = SelectionDialogItem(item: itemTitle)
items.append(item)
}
open func addItem(item itemTitle: String, icon: UIImage) {
let item = SelectionDialogItem(item: itemTitle, icon: icon)
items.append(item)
}
open func addItem(item itemTitle: String, didTapHandler: @escaping (() -> Void)) {
let item = SelectionDialogItem(item: itemTitle, didTapHandler: didTapHandler)
items.append(item)
}
open func addItem(item itemTitle: String, icon: UIImage, didTapHandler: @escaping (() -> Void)) {
let item = SelectionDialogItem(item: itemTitle, icon: icon, didTapHandler: didTapHandler)
items.append(item)
}
open func addItem(_ item: SelectionDialogItem) {
items.append(item)
}
fileprivate func setObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(SelectionDialog.deviceOrientationDidChange(_:)),
name: UIDevice.orientationDidChangeNotification,
object: nil)
}
fileprivate func createDialogView() -> UIView {
let screenSize = self.calculateScreenSize()
let dialogSize = self.calculateDialogSize()
let view = UIView(frame: CGRect(
x: (screenSize.width - dialogSize.width) / 2,
y: (screenSize.height - dialogSize.height) / 2,
width: dialogSize.width,
height: dialogSize.height
))
view.layer.cornerRadius = cornerRadius
view.backgroundColor = UIColor.white
view.layer.shadowRadius = cornerRadius
view.layer.shadowOpacity = 0.2
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shouldRasterize = true
view.layer.rasterizationScale = UIScreen.main.scale
if useMotionEffects {
applyMotionEffects(view)
}
view.addSubview(createTitleLabel())
view.addSubview(createContainerView())
view.addSubview(createCloseButton())
return view
}
fileprivate func createContainerView() -> UIScrollView {
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: CGFloat(items.count * 50)))
for (index, item) in items.enumerated() {
let itemButton = UIButton(frame: CGRect(x: 0, y: CGFloat(index * 50), width: 300, height: 50))
let itemTitleLabel = UILabel(frame: CGRect(x: itemPadding, y: 0, width: 255, height: 50))
itemTitleLabel.text = item.itemTitle
itemTitleLabel.textColor = UIColor.black
itemButton.addSubview(itemTitleLabel)
itemButton.setBackgroundImage(UIImage.createImageWithColor(UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1)), for: .highlighted)
itemButton.addTarget(item, action: #selector(SelectionDialogItem.handlerTap), for: .touchUpInside)
if item.icon != nil {
itemTitleLabel.frame.origin.x = 34 + itemPadding*2
let itemIcon = UIImageView(frame: CGRect(x: itemPadding, y: 8, width: 34, height: 34))
itemIcon.image = item.icon
itemButton.addSubview(itemIcon)
}
containerView.addSubview(itemButton)
let divider = UIView(frame: CGRect(x: 0, y: CGFloat(index*50)+50, width: 300, height: 0.5))
divider.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1)
containerView.addSubview(divider)
containerView.frame.size.height += 50
}
let scrollView = UIScrollView(frame: CGRect(x: 0, y: titleHeight, width: 300, height: minHeight))
scrollView.contentSize.height = CGFloat(items.count*50)
scrollView.addSubview(containerView)
return scrollView
}
fileprivate func createTitleLabel() -> UIView {
let view = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: titleHeight))
view.text = title
view.textAlignment = .center
view.font = UIFont.boldSystemFont(ofSize: 18.0)
let bottomLayer = CALayer()
bottomLayer.frame = CGRect(x: 0, y: view.bounds.size.height, width: view.bounds.size.width, height: 0.5)
bottomLayer.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).cgColor
view.layer.addSublayer(bottomLayer)
return view
}
fileprivate func createCloseButton() -> UIButton {
let minValue = min(CGFloat(items.count) * 50.0, minHeight)
let button = UIButton(frame: CGRect(x: 0, y: titleHeight + minValue, width: 300, height: buttonHeight))
button.addTarget(self,
action: #selector(SelectionDialog.close),
for: .touchUpInside)
let colorNormal = closeButtonColor != nil ? closeButtonColor : button.tintColor
let colorHighlighted = closeButtonColorHighlighted != nil ? closeButtonColorHighlighted : colorNormal?.withAlphaComponent(0.5)
button.setTitle(closeButtonTitle, for: .normal)
button.setTitleColor(colorNormal, for: .normal)
button.setTitleColor(colorHighlighted, for: .highlighted)
button.setTitleColor(colorHighlighted, for: .disabled)
let topLayer = CALayer()
topLayer.frame = CGRect(x: 0, y: 0, width: 300, height: 0.5)
topLayer.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).cgColor
button.layer.addSublayer(topLayer)
return button
}
fileprivate func calculateDialogSize() -> CGSize {
let minValue = min(CGFloat(items.count)*50.0, minHeight)
return CGSize(width: 300, height: minValue + titleHeight + buttonHeight)
}
fileprivate func calculateScreenSize() -> CGSize {
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
return CGSize(width: width, height: height)
}
fileprivate func applyMotionEffects(_ view: UIView) {
let horizontalEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
horizontalEffect.minimumRelativeValue = -motionEffectExtent
horizontalEffect.maximumRelativeValue = +motionEffectExtent
let verticalEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis)
verticalEffect.minimumRelativeValue = -motionEffectExtent
verticalEffect.maximumRelativeValue = +motionEffectExtent
let motionEffectGroup = UIMotionEffectGroup()
motionEffectGroup.motionEffects = [horizontalEffect, verticalEffect]
view.addMotionEffect(motionEffectGroup)
}
@objc internal func deviceOrientationDidChange(_ notification: Notification) {
self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
let screenSize = self.calculateScreenSize()
let dialogSize = self.calculateDialogSize()
dialogView?.frame = CGRect(
x: (screenSize.width - dialogSize.width) / 2,
y: (screenSize.height - dialogSize.height) / 2,
width: dialogSize.width,
height: dialogSize.height
)
}
deinit {
NotificationCenter.default.removeObserver(self,
name: UIDevice.orientationDidChangeNotification,
object: nil)
}
}
|
mit
|
72968cd83af000edcb7cc06b59e49694
| 39.412639 | 142 | 0.617974 | 4.720365 | false | false | false | false |
CSSE497/pathfinder-ios
|
framework/Pathfinder/Cluster.swift
|
1
|
5606
|
//
// Cluster.swift
// Pathfinder
//
// Created by Adam Michael on 10/15/15.
// Copyright © 2015 Pathfinder. All rights reserved.
//
import Foundation
import CoreLocation
/**
A container in which transports are routed to transport commodities. Every registered Pathfinder application is created one default cluster. Additional sub-clusters can be created by the developer through the Pathfinder web interface.
This class should not be instantiated directly since it represents the state of the Pathfinder backend service. Instead, use the factory methods in the Pathfinder class. The typical use case of creating a Cluster object is to set a delegate for it which will receive all of the updates defined in `ClusterDelegate`.
*/
public class Cluster {
// MARK: - Class Properties -
/// The path to the default cluster for an application.
public static let defaultPath = "/root"
// MARK: - Instance Variables
/// The path to the cluster within the application.
public let id: String
/// True if the connection to Pathfinder is active.
public var connected: Bool
/// All of the routes that are currently in progress for the cluster.
public var routes: [Route]
/// The transports that are currently online within the cluster.
public var transports: [Transport]
/// The commodities that are currently waiting on transit or are in transit within the cluster.
public var commodities: [Commodity]
/// The delegate that will receive notifications when any aspect of the cluster is updated.
public var delegate: ClusterDelegate?
// MARK: - Methods -
/**
Attempts to authenticate and retrieve a reference to the requested cluster. If the connection succeeds, the corresponding method on the delegate will be executed.
If successful, the fields of the instance will be replaced by the Pathfinder-backed values, e.g. the list of transports. However, these will not be kept up to date unless you subscribe.
*/
public func connect() {
connect { _ in }
}
/**
Requests that the Pathfinder server send push notifications to the cluster's delegate whenever any information changes in the cluster.
Push notifications will be sent when:
* New commodities or transports are created within the cluster.
* Commodities request transportation within the cluster.
* Commodities cancel their transportation request.
* Transports in the cluster receive a new route.
* Transports pick up or drop off commodities.
*/
public func subscribe() {
conn.subscribe(self)
}
/// Stops the Pathfinder service from sending update notifications.
public func unsubscribe() {
}
/**
Registers the current device as a transport with the Pathfinder service or uses the user's authentication to determine if an existing transport record exists and retrieves it. This will NOT set the transport to the online state. No routes will be generated for the transport until it is set to online. If the connection is authenticated and succeeds, the corresponding method on the delegate will be executed.
- Parameter capacities: The limiting constraints of the transport of the parameters of your application's routing calculations. The set of parameters needs to be defined and prioritized via the Pathfinder web interface in advance. All transports will be routed while keeping their sum occupant parameters to be less than or equal to their limiting constraints.
*/
public func createTransport(status: Transport.Status, metadata: [String:AnyObject]) -> Transport {
return Transport(cluster: self, metadata: metadata, status: status)
}
/**
Constructs a reference to a previously created transport within the cluster. T
*/
public func getTransport(id: Int) -> Transport {
return Transport(cluster: self, id: id)
}
/**
Requests transportation for a physical entity from one geographical location to another. This will immediately route a transport to pick up the commodity if one is available that can hold the commodities parameters within the transports capacity. If the connection is authenticated and succeeds, the corresponding method on the delegate of the returned commodity will be executed.
- Parameter start: The starting location of the commodity.
- Parameter destination: The destination location of the commodity.
- Parameter parameters: The quantities the parameters of your application's routing calculations. The set of parameters needs to be defined and prioritized via the Pathfinder web interface in advance.
*/
public func createCommodity(start: CLLocationCoordinate2D, destination: CLLocationCoordinate2D, metadata: [String:AnyObject]) -> Commodity {
return Commodity(cluster: self, start: start, destination: destination, metadata: metadata)
}
public func getCommodity(id: Int) -> Commodity {
return Commodity(cluster: self, id: id)
}
let conn: PathfinderConnection
convenience init(conn: PathfinderConnection) {
self.init(conn: conn, path: Cluster.defaultPath)
}
init(conn: PathfinderConnection, path: String) {
self.id = path
self.transports = [Transport]()
self.commodities = [Commodity]()
self.routes = [Route]()
self.conn = conn
self.connected = false
}
func connect(callback: (cluster: Cluster) -> Void) {
if !connected {
conn.getClusterById(id) { (resp: ClusterResponse) -> Void in
self.connected = true
self.transports = resp.transports
self.commodities = resp.commodities
self.delegate?.connected(self)
callback(cluster: self)
}
}
}
}
|
mit
|
0f3a43ee17aa2d3ddd333c7d435a5493
| 41.469697 | 411 | 0.74719 | 4.609375 | false | false | false | false |
material-components/material-components-ios
|
catalog/MDCCatalog/AppTheme.swift
|
2
|
1789
|
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import MaterialComponents.MaterialButtons_ButtonThemer
import MaterialComponents.MaterialColorScheme
import MaterialComponents.MaterialContainerScheme
import MaterialComponents.MaterialShapeScheme
import MaterialComponents.MaterialTypographyScheme
final class AppTheme {
static var containerScheme: MDCContainerScheming = DefaultContainerScheme() {
didSet {
NotificationCenter.default.post(name: AppTheme.didChangeGlobalThemeNotificationName,
object: nil,
userInfo: nil)
}
}
static let didChangeGlobalThemeNotificationName =
Notification.Name("MDCCatalogDidChangeGlobalTheme")
private init() {
// An AppTheme is not intended to be created; use the static APIs instead.
}
}
func DefaultContainerScheme() -> MDCContainerScheme {
let containerScheme = MDCContainerScheme()
containerScheme.colorScheme = MDCSemanticColorScheme(defaults: .material201907)
containerScheme.typographyScheme = MDCTypographyScheme(defaults: .material201902)
containerScheme.shapeScheme = MDCShapeScheme()
return containerScheme
}
|
apache-2.0
|
0b7d5cbdbc83a55540bca7165987ed4c
| 37.06383 | 90 | 0.762437 | 5.15562 | false | false | false | false |
apple/swift
|
test/SILOptimizer/devirt_specialized_conformance.swift
|
2
|
2247
|
// RUN: %target-swift-frontend -O -Xllvm -sil-inline-generics=false -Xllvm -sil-disable-pass=ObjectOutliner %s -emit-sil -sil-verify-all | %FileCheck %s
// Make sure that we completely inline/devirtualize/substitute all the way down
// to unknown1.
// CHECK-LABEL: sil {{.*}}@main
// CHECK: bb0({{.*}}):
// CHECK: function_ref @unknown1
// CHECK: apply
// CHECK: apply
// CHECK: return
struct Int32 {}
@_silgen_name("unknown1")
func unknown1() -> ()
protocol P {
func doSomething(_ x : Int32)
}
struct X {}
class B<T> : P {
func doSomething(_ x : Int32) {
unknown1()
}
}
func doSomething(_ p : P, _ x : Int32) {
p.doSomething(x)
}
func doSomething2<T : P>(_ t : T, _ x : Int32) {
t.doSomething(x)
}
func driver() {
var b2 = B<X>()
var x = Int32()
doSomething(b2, x)
doSomething2(b2, x)
}
driver()
// <rdar://problem/46322928> Failure to devirtualize a protocol method
// applied to an opened existential blocks implementation of
// DataProtocol.
public protocol ContiguousBytes {
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R
}
extension Array : ContiguousBytes {}
extension ContiguousArray : ContiguousBytes {}
@inline(never)
func takesPointer(_ p: UnsafeRawBufferPointer) {}
// In specialized testWithUnsafeBytes<A>(_:), the conditional case and call to withUnsafeBytes must be eliminated.
// Normally, we expect Array.withUnsafeBytes to be inlined so we would see:
// [[TAKES_PTR:%.*]] = function_ref @$s30devirt_specialized_conformance12takesPointeryySWF : $@convention(thin) (UnsafeRawBufferPointer) -> ()
// apply [[TAKES_PTR]](%{{.*}}) : $@convention(thin) (UnsafeRawBufferPointer) -> ()
// But the inlining isn't consistent across builds with and without debug info.
//
// CHECK-LABEL: sil shared [noinline] @$s30devirt_specialized_conformance19testWithUnsafeBytesyyxlFSayypG_Tg5 : $@convention(thin) (@guaranteed Array<Any>) -> () {
// CHECK: bb0
// CHECK-NOT: witness_method
// CHECK-LABEL: } // end sil function '$s30devirt_specialized_conformance19testWithUnsafeBytesyyxlFSayypG_Tg5'
@inline(never)
func testWithUnsafeBytes<T>(_ t: T) {
if let cb = t as? ContiguousBytes {
cb.withUnsafeBytes { takesPointer($0) }
}
}
testWithUnsafeBytes([])
|
apache-2.0
|
f8a446d19f534b060dced6ff03ad78ae
| 28.565789 | 163 | 0.697374 | 3.544164 | false | true | false | false |
Liuyingao/SwiftRepository
|
ARC.swift
|
1
|
4224
|
//: Playground - noun: a place where people can play
import UIKit
//在被捕获的引用可能会变为nil时,将闭包内的捕获定义为弱引用。
//弱引用总是可选类型,并且当引用的实例被销毁后,弱引用的值会自动置为nil。
//Person和Apartment的例子展示了两个属性的值都允许为nil,并会潜在的产生循环强引用。
//这种场景最适合用弱引用来解决。
class Person{
var name: String
var apartment: Apartment?
init(name: String){
self.name = name
}
deinit{
print("\(self.name) is being deinitialized")
}
}
class Apartment{
var unit: String
weak var tenant: Person?
init(unit: String){
self.unit = unit
}
deinit{
print("\(self.unit) is being deinitialized")
}
}
var john: Person? = Person(name: "John")
var unit4A: Apartment? = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john
john = nil
print("\(unit4A?.tenant) is living in")
unit4A = nil
print("-----------------------------------------")
//和弱引用类似,无主引用不会牢牢保持住引用的实例。和弱引用不同的是,无主引用是永远有值的。
//因此,无主引用总是被定义为非可选类型(non-optional type)。
//还需要注意的是如果你试图访问实例已经被销毁的无主引用
//Swift 确保程序会直接崩溃,而不会发生无法预期的行为。
//Customer和CreditCard的例子展示了一个属性的值允许为nil,
//而另一个属性的值不允许为nil,这也可能会产生循环强引用。
//这种场景最适合通过无主引用来解决。
class Customer{
var name: String
var card: Card?
init(name: String){
self.name = name
}
deinit{
print("\(self.name) is being deinitialized")
}
}
class Card{
var number: Int
unowned var customer: Customer
init(number: Int, customer: Customer){
self.number = number
self.customer = customer
}
deinit{
print("\(self.number) is being deinitialized")
}
}
var leo: Customer? = Customer(name: "Leo")
var card: Card? = Card(number: 99887766, customer: leo!)
leo?.card = card
leo = nil
//print("Customer's name is \(card?.customer.name)")
card = nil
print("-----------------------------------------")
//两个属性都必须有值,并且初始化完成后永远不会为nil。
//在这种场景中,需要一个类使用无主属性,而另外一个类使用隐式解析可选属性。
class Country{
let name: String
var captialCity: City!
init(name: String, city: String){
self.name = name
self.captialCity = City(name: city, country: self)
}
deinit{
print("\(self.name) is being deinitialized")
}
}
class City{
let name: String
unowned let country: Country
init(name: String, country: Country){
self.name = name
self.country = country
}
deinit{
print("\(self.name) is being deinitialized")
}
}
var china: Country? = Country(name: "China", city: "Beijing")
print(china?.captialCity?.name)
china = nil
print("-----------------------------------------")
//在闭包和捕获的实例总是互相引用并且总是同时销毁时,将闭包内的捕获定义为无主引用。
//相反的,在被捕获的引用可能会变为nil时,将闭包内的捕获定义为弱引用。
//弱引用总是可选类型,并且当引用的实例被销毁后,弱引用的值会自动置为nil。
//这使我们可以在闭包体内检查它们是否存在。
class HTMLElement{
var name: String
var text: String?
lazy var asHTML: Void -> String = {
[unowned self] in
if let i = self.text{
return "<\(self.name)>\(i)</\(self.name)>"
}else{
return "<\(self.name)></\(self.name)>"
}
}
init(name: String, text: String? = nil){
self.name = name
self.text = text
}
deinit{
print("\(self.name) is being deinitialized")
}
}
var p: HTMLElement? = HTMLElement(name: "P", text: "Hello")
print(p!.asHTML())
p = nil
|
gpl-2.0
|
12c0b2ce687ff9cf5adfcc65bd227cf2
| 21.216216 | 61 | 0.601277 | 3.249012 | false | false | false | false |
TG908/iOS
|
TUM Campus App/PersonDetailTableViewController.swift
|
1
|
3276
|
//
// PersonDetailTableViewController.swift
// TUM Campus App
//
// Created by Mathias Quintero on 12/23/15.
// Copyright © 2015 LS1 TUM. All rights reserved.
//
import UIKit
class PersonDetailTableViewController: UITableViewController, DetailView {
var user: DataElement?
var delegate: DetailViewDelegate?
var contactInfo = [(ContactInfoType,String)]()
var addingContact = false
func addContact(_ sender: AnyObject?) {
let handler = { () in
DoneHUD.showInView(self.view, message: "Contact Added")
}
if let data = user as? UserData {
if data.contactsLoaded {
addingContact = false
data.addContact(handler)
} else {
addingContact = true
}
}
}
}
extension PersonDetailTableViewController: TumDataReceiver {
func receiveData(_ data: [DataElement]) {
if let data = user as? UserData {
contactInfo = data.contactInfo
}
if addingContact {
addContact(nil)
}
tableView.reloadData()
}
}
extension PersonDetailTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
title = user?.text
let barItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(PersonDetailTableViewController.addContact(_:)))
navigationItem.rightBarButtonItem = barItem
if let data = user as? UserData {
delegate?.dataManager().getPersonDetails(self.receiveData, user: data)
contactInfo = data.contactInfo
}
}
}
extension PersonDetailTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
return contactInfo.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 1 && !contactInfo.isEmpty {
return "Contact Info"
}
return nil
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if let data = user {
let cell = tableView.dequeueReusableCell(withIdentifier: data.getCellIdentifier()) as? CardTableViewCell ?? CardTableViewCell()
cell.setElement(data)
return cell
}
}
let cell = tableView.dequeueReusableCell(withIdentifier: "contact") ?? UITableViewCell()
cell.textLabel?.text = contactInfo[indexPath.row].0.rawValue
cell.detailTextLabel?.text = contactInfo[indexPath.row].1
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 1 {
contactInfo[indexPath.row].0.handle(contactInfo[indexPath.row].1)
}
}
}
|
gpl-3.0
|
951e8d29abf9cad08aa14f086c328110
| 29.607477 | 145 | 0.620153 | 5.248397 | false | false | false | false |
indragiek/Ares
|
client/iOS/ViewController.swift
|
1
|
7654
|
//
// ViewController.swift
// Ares-iOS
//
// Created by Indragie on 1/30/16.
// Copyright © 2016 Indragie Karunaratne. All rights reserved.
//
import UIKit
import AresKit
import KVOController
import QuickLook
class ViewController: UIViewController, LoginViewControllerDelegate, ConnectionManagerDelegate, IncomingFileTransferDelegate, QLPreviewControllerDelegate {
private enum State {
case Default
case WaitingForDiscovery
case Transferring
}
private let credentialStorage: CredentialStorage
private let apnsManager: APNSManager
private let client: Client
private var _KVOController: FBKVOController!
private var connectionManager: ConnectionManager?
private var queuedPushNotifications = [PushNotification]()
private var temporaryFileURL: NSURL?
private var state = State.Default {
didSet {
loadViewIfNeeded()
switch state {
case .Default:
placeholderImageView.hidden = false
determinateProgressStackView.hidden = true
indeterminateProgressStackView.hidden = true
activityIndicator.stopAnimating()
case .WaitingForDiscovery:
placeholderImageView.hidden = true
determinateProgressStackView.hidden = true
indeterminateProgressStackView.hidden = false
activityIndicator.startAnimating()
case .Transferring:
placeholderImageView.hidden = true
determinateProgressStackView.hidden = false
indeterminateProgressStackView.hidden = true
activityIndicator.stopAnimating()
}
}
}
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var determinateProgressStackView: UIStackView!
@IBOutlet weak var indeterminateProgressStackView: UIStackView!
@IBOutlet weak var placeholderImageView: UIImageView!
init(client: Client, credentialStorage: CredentialStorage, apnsManager: APNSManager) {
self.client = client
self.credentialStorage = credentialStorage
self.apnsManager = apnsManager
super.init(nibName: nil, bundle: nil)
self._KVOController = FBKVOController(observer: self)
title = "🚀 Ares"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
if let token = credentialStorage.activeToken {
completeSetupWithToken(token)
} else {
dispatch_async(dispatch_get_main_queue()) {
self.presentLoginViewController()
}
}
}
// MARK: Login
private func presentLoginViewController() {
let loginViewController = LoginViewController(apnsManager: apnsManager)
loginViewController.client = client
loginViewController.delegate = self
let navigationController = UINavigationController(rootViewController: loginViewController)
presentViewController(navigationController, animated: true, completion: nil)
}
private func completeSetupWithToken(token: AccessToken) {
let connectionManager = ConnectionManager(client: client, token: token)
connectionManager.delegate = self
connectionManager.incomingFileTransferDelegate = self
connectionManager.getDeviceList {
connectionManager.startMonitoring()
self.queuedPushNotifications.forEach(connectionManager.queueNotification)
self.queuedPushNotifications.removeAll()
}
self.connectionManager = connectionManager
}
// MARK: Notification Handling
func handlePushNotification(notification: PushNotification) {
state = .WaitingForDiscovery
if let connectionManager = connectionManager {
connectionManager.queueNotification(notification)
} else {
queuedPushNotifications.append(notification)
}
}
// MARK: LoginViewControllerDelegae
func loginViewController(controller: LoginViewController, authenticatedWithToken token: AccessToken) {
credentialStorage.activeToken = token
completeSetupWithToken(token)
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: ConnectionManagerDelegate
func connectionManager(manager: ConnectionManager, willBeginOutgoingFileTransfer transfer: OutgoingFileTransfer) {}
func connectionManager(manager: ConnectionManager, willBeginIncomingFileTransfer transfer: IncomingFileTransfer) {
print("Receiving \(transfer.context.filePath)")
}
func connectionManager(manager: ConnectionManager, didFailWithError error: NSError) {
print(error)
}
func connectionManager(manager: ConnectionManager, didUpdateDevices devices: [Device]) {}
// MARK: IncomingFileTransferDelegate
func incomingFileTransfer(transfer: IncomingFileTransfer, didStartReceivingFileWithName name: String, progress: NSProgress) {
let fileName = (transfer.context.filePath as NSString).lastPathComponent
dispatch_async(dispatch_get_main_queue()) {
self.progressLabel.text = "Receiving \(fileName)..."
self.state = .Transferring
}
_KVOController.observe(progress, keyPath: "fractionCompleted", options: []) { (_, _, _) in
dispatch_async(dispatch_get_main_queue()) {
self.progressView.progress = Float(progress.fractionCompleted)
}
}
}
func incomingFileTransfer(transfer: IncomingFileTransfer, didFailToReceiveFileWithName name: String, error: NSError) {
print("Failed to receive \(name): \(error)")
}
func incomingFileTransfer(transfer: IncomingFileTransfer, didReceiveFileWithName name: String, URL: NSURL) {
if let _ = presentedViewController {
dismissViewControllerAnimated(true) {
self.showPreviewControllerForFileName(name, URL: URL)
}
} else {
showPreviewControllerForFileName(name, URL: URL)
}
}
private func showPreviewControllerForFileName(name: String, URL: NSURL) {
guard let directoryURL = URL.URLByDeletingLastPathComponent else { return }
let fixedURL = directoryURL.URLByAppendingPathComponent(name)
temporaryFileURL = fixedURL
let fm = NSFileManager.defaultManager()
do { try fm.removeItemAtURL(fixedURL) } catch _ {}
do {
try fm.moveItemAtURL(URL, toURL: fixedURL)
} catch let error {
fatalError("Error moving \(URL) to \(fixedURL): \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
let previewController = PreviewViewController(fileName: name, URL: fixedURL)
previewController.delegate = self
self.presentViewController(previewController, animated: true) {
self.state = .Default
}
}
}
// MARK: QLPreviewControllerDelegate
func previewControllerDidDismiss(controller: QLPreviewController) {
guard let fileURL = temporaryFileURL else { return }
do {
try NSFileManager.defaultManager().removeItemAtURL(fileURL)
} catch _ {}
}
}
|
mit
|
f4d4b031db2df4125d6ab7848d2f812b
| 36.317073 | 155 | 0.663007 | 5.848624 | false | false | false | false |
OscarSwanros/swift
|
stdlib/public/core/ManagedBuffer.swift
|
2
|
22447
|
//===--- ManagedBuffer.swift - variable-sized buffer of aligned memory ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
@_silgen_name("swift_bufferAllocate")
internal func _swift_bufferAllocate(
bufferType type: AnyClass,
size: Int,
alignmentMask: Int
) -> AnyObject
/// A class whose instances contain a property of type `Header` and raw
/// storage for an array of `Element`, whose size is determined at
/// instance creation.
///
/// Note that the `Element` array is suitably-aligned **raw memory**.
/// You are expected to construct and---if necessary---destroy objects
/// there yourself, using the APIs on `UnsafeMutablePointer<Element>`.
/// Typical usage stores a count and capacity in `Header` and destroys
/// any live elements in the `deinit` of a subclass.
/// - Note: Subclasses must not have any stored properties; any storage
/// needed should be included in `Header`.
@_fixed_layout // FIXME(sil-serialize-all)
open class ManagedBuffer<Header, Element> {
/// Create a new instance of the most-derived class, calling
/// `factory` on the partially-constructed object to generate
/// an initial `Header`.
@_inlineable // FIXME(sil-serialize-all)
public final class func create(
minimumCapacity: Int,
makingHeaderWith factory: (
ManagedBuffer<Header, Element>) throws -> Header
) rethrows -> ManagedBuffer<Header, Element> {
let p = Builtin.allocWithTailElems_1(
self,
minimumCapacity._builtinWordValue, Element.self)
let initHeaderVal = try factory(p)
p.headerAddress.initialize(to: initHeaderVal)
// The _fixLifetime is not really needed, because p is used afterwards.
// But let's be conservative and fix the lifetime after we use the
// headerAddress.
_fixLifetime(p)
return p
}
/// The actual number of elements that can be stored in this object.
///
/// This header may be nontrivial to compute; it is usually a good
/// idea to store this information in the "header" area when
/// an instance is created.
@_inlineable // FIXME(sil-serialize-all)
public final var capacity: Int {
let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(self))
let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr)
let realCapacity = endAddr.assumingMemoryBound(to: Element.self) -
firstElementAddress
return realCapacity
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal final var firstElementAddress: UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(Builtin.projectTailElems(self,
Element.self))
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal final var headerAddress: UnsafeMutablePointer<Header> {
return UnsafeMutablePointer<Header>(Builtin.addressof(&header))
}
/// Call `body` with an `UnsafeMutablePointer` to the stored
/// `Header`.
///
/// - Note: This pointer is valid only for the duration of the
/// call to `body`.
@_inlineable // FIXME(sil-serialize-all)
public final func withUnsafeMutablePointerToHeader<R>(
_ body: (UnsafeMutablePointer<Header>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { (v, _) in return try body(v) }
}
/// Call `body` with an `UnsafeMutablePointer` to the `Element`
/// storage.
///
/// - Note: This pointer is valid only for the duration of the
/// call to `body`.
@_inlineable // FIXME(sil-serialize-all)
public final func withUnsafeMutablePointerToElements<R>(
_ body: (UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { return try body($1) }
}
/// Call `body` with `UnsafeMutablePointer`s to the stored `Header`
/// and raw `Element` storage.
///
/// - Note: These pointers are valid only for the duration of the
/// call to `body`.
@_inlineable // FIXME(sil-serialize-all)
public final func withUnsafeMutablePointers<R>(
_ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(self) }
return try body(headerAddress, firstElementAddress)
}
/// The stored `Header` instance.
///
/// During instance creation, in particular during
/// `ManagedBuffer.create`'s call to initialize, `ManagedBuffer`'s
/// `header` property is as-yet uninitialized, and therefore
/// reading the `header` property during `ManagedBuffer.create` is undefined.
public final var header: Header
//===--- internal/private API -------------------------------------------===//
/// Make ordinary initialization unavailable
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(_doNotCallMe: ()) {
_sanityCheckFailure("Only initialize these by calling create")
}
}
/// Contains a buffer object, and provides access to an instance of
/// `Header` and contiguous storage for an arbitrary number of
/// `Element` instances stored in that buffer.
///
/// For most purposes, the `ManagedBuffer` class works fine for this
/// purpose, and can simply be used on its own. However, in cases
/// where objects of various different classes must serve as storage,
/// `ManagedBufferPointer` is needed.
///
/// A valid buffer class is non-`@objc`, with no declared stored
/// properties. Its `deinit` must destroy its
/// stored `Header` and any constructed `Element`s.
///
/// Example Buffer Class
/// --------------------
///
/// class MyBuffer<Element> { // non-@objc
/// typealias Manager = ManagedBufferPointer<(Int, String), Element>
/// deinit {
/// Manager(unsafeBufferObject: self).withUnsafeMutablePointers {
/// (pointerToHeader, pointerToElements) -> Void in
/// pointerToElements.deinitialize(count: self.count)
/// pointerToHeader.deinitialize()
/// }
/// }
///
/// // All properties are *computed* based on members of the Header
/// var count: Int {
/// return Manager(unsafeBufferObject: self).header.0
/// }
/// var name: String {
/// return Manager(unsafeBufferObject: self).header.1
/// }
/// }
///
@_fixed_layout
public struct ManagedBufferPointer<Header, Element> : Equatable {
/// Create with new storage containing an initial `Header` and space
/// for at least `minimumCapacity` `element`s.
///
/// - parameter bufferClass: The class of the object used for storage.
/// - parameter minimumCapacity: The minimum number of `Element`s that
/// must be able to be stored in the new buffer.
/// - parameter factory: A function that produces the initial
/// `Header` instance stored in the buffer, given the `buffer`
/// object and a function that can be called on it to get the actual
/// number of allocated elements.
///
/// - Precondition: `minimumCapacity >= 0`, and the type indicated by
/// `bufferClass` is a non-`@objc` class with no declared stored
/// properties. The `deinit` of `bufferClass` must destroy its
/// stored `Header` and any constructed `Element`s.
@_inlineable // FIXME(sil-serialize-all)
public init(
bufferClass: AnyClass,
minimumCapacity: Int,
makingHeaderWith factory:
(_ buffer: AnyObject, _ capacity: (AnyObject) -> Int) throws -> Header
) rethrows {
self = ManagedBufferPointer(
bufferClass: bufferClass, minimumCapacity: minimumCapacity)
// initialize the header field
try withUnsafeMutablePointerToHeader {
$0.initialize(to:
try factory(
self.buffer,
{
ManagedBufferPointer(unsafeBufferObject: $0).capacity
}))
}
// FIXME: workaround for <rdar://problem/18619176>. If we don't
// access header somewhere, its addressor gets linked away
_ = header
}
/// Manage the given `buffer`.
///
/// - Precondition: `buffer` is an instance of a non-`@objc` class whose
/// `deinit` destroys its stored `Header` and any constructed `Element`s.
@_inlineable // FIXME(sil-serialize-all)
public init(unsafeBufferObject buffer: AnyObject) {
ManagedBufferPointer._checkValidBufferClass(type(of: buffer))
self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)
}
/// Internal version for use by _ContiguousArrayBuffer where we know that we
/// have a valid buffer class.
/// This version of the init function gets called from
/// _ContiguousArrayBuffer's deinit function. Since 'deinit' does not get
/// specialized with current versions of the compiler, we can't get rid of the
/// _debugPreconditions in _checkValidBufferClass for any array. Since we know
/// for the _ContiguousArrayBuffer that this check must always succeed we omit
/// it in this specialized constructor.
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal init(_uncheckedUnsafeBufferObject buffer: AnyObject) {
ManagedBufferPointer._sanityCheckValidBufferClass(type(of: buffer))
self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)
}
/// The stored `Header` instance.
@_inlineable // FIXME(sil-serialize-all)
public var header: Header {
addressWithNativeOwner {
return (UnsafePointer(_headerPointer), _nativeBuffer)
}
mutableAddressWithNativeOwner {
return (_headerPointer, _nativeBuffer)
}
}
/// Returns the object instance being used for storage.
@_inlineable // FIXME(sil-serialize-all)
public var buffer: AnyObject {
return Builtin.castFromNativeObject(_nativeBuffer)
}
/// The actual number of elements that can be stored in this object.
///
/// This value may be nontrivial to compute; it is usually a good
/// idea to store this information in the "header" area when
/// an instance is created.
@_inlineable // FIXME(sil-serialize-all)
public var capacity: Int {
return (_capacityInBytes &- _My._elementOffset) / MemoryLayout<Element>.stride
}
/// Call `body` with an `UnsafeMutablePointer` to the stored
/// `Header`.
///
/// - Note: This pointer is valid only
/// for the duration of the call to `body`.
@_inlineable // FIXME(sil-serialize-all)
public func withUnsafeMutablePointerToHeader<R>(
_ body: (UnsafeMutablePointer<Header>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { (v, _) in return try body(v) }
}
/// Call `body` with an `UnsafeMutablePointer` to the `Element`
/// storage.
///
/// - Note: This pointer is valid only for the duration of the
/// call to `body`.
@_inlineable // FIXME(sil-serialize-all)
public func withUnsafeMutablePointerToElements<R>(
_ body: (UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { return try body($1) }
}
/// Call `body` with `UnsafeMutablePointer`s to the stored `Header`
/// and raw `Element` storage.
///
/// - Note: These pointers are valid only for the duration of the
/// call to `body`.
@_inlineable // FIXME(sil-serialize-all)
public func withUnsafeMutablePointers<R>(
_ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(_nativeBuffer) }
return try body(_headerPointer, _elementPointer)
}
/// Returns `true` iff `self` holds the only strong reference to its buffer.
///
/// See `isUniquelyReferenced` for details.
@_inlineable // FIXME(sil-serialize-all)
public mutating func isUniqueReference() -> Bool {
return _isUnique(&_nativeBuffer)
}
//===--- internal/private API -------------------------------------------===//
/// Create with new storage containing space for an initial `Header`
/// and at least `minimumCapacity` `element`s.
///
/// - parameter bufferClass: The class of the object used for storage.
/// - parameter minimumCapacity: The minimum number of `Element`s that
/// must be able to be stored in the new buffer.
///
/// - Precondition: `minimumCapacity >= 0`, and the type indicated by
/// `bufferClass` is a non-`@objc` class with no declared stored
/// properties. The `deinit` of `bufferClass` must destroy its
/// stored `Header` and any constructed `Element`s.
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(
bufferClass: AnyClass,
minimumCapacity: Int
) {
ManagedBufferPointer._checkValidBufferClass(bufferClass, creating: true)
_precondition(
minimumCapacity >= 0,
"ManagedBufferPointer must have non-negative capacity")
self.init(
_uncheckedBufferClass: bufferClass, minimumCapacity: minimumCapacity)
}
/// Internal version for use by _ContiguousArrayBuffer.init where we know that
/// we have a valid buffer class and that the capacity is >= 0.
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal init(
_uncheckedBufferClass: AnyClass,
minimumCapacity: Int
) {
ManagedBufferPointer._sanityCheckValidBufferClass(_uncheckedBufferClass, creating: true)
_sanityCheck(
minimumCapacity >= 0,
"ManagedBufferPointer must have non-negative capacity")
let totalSize = _My._elementOffset
+ minimumCapacity * MemoryLayout<Element>.stride
let newBuffer: AnyObject = _swift_bufferAllocate(
bufferType: _uncheckedBufferClass,
size: totalSize,
alignmentMask: _My._alignmentMask)
self._nativeBuffer = Builtin.unsafeCastToNativeObject(newBuffer)
}
/// Manage the given `buffer`.
///
/// - Note: It is an error to use the `header` property of the resulting
/// instance unless it has been initialized.
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal init(_ buffer: ManagedBuffer<Header, Element>) {
_nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)
}
internal typealias _My = ManagedBufferPointer
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal static func _checkValidBufferClass(
_ bufferClass: AnyClass, creating: Bool = false
) {
_debugPrecondition(
_class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size
|| (
(!creating || bufferClass is ManagedBuffer<Header, Element>.Type)
&& _class_getInstancePositiveExtentSize(bufferClass)
== _headerOffset + MemoryLayout<Header>.size),
"ManagedBufferPointer buffer class has illegal stored properties"
)
_debugPrecondition(
_usesNativeSwiftReferenceCounting(bufferClass),
"ManagedBufferPointer buffer class must be non-@objc"
)
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal static func _sanityCheckValidBufferClass(
_ bufferClass: AnyClass, creating: Bool = false
) {
_sanityCheck(
_class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size
|| (
(!creating || bufferClass is ManagedBuffer<Header, Element>.Type)
&& _class_getInstancePositiveExtentSize(bufferClass)
== _headerOffset + MemoryLayout<Header>.size),
"ManagedBufferPointer buffer class has illegal stored properties"
)
_sanityCheck(
_usesNativeSwiftReferenceCounting(bufferClass),
"ManagedBufferPointer buffer class must be non-@objc"
)
}
/// The required alignment for allocations of this type, minus 1
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal static var _alignmentMask: Int {
return max(
MemoryLayout<_HeapObject>.alignment,
max(MemoryLayout<Header>.alignment, MemoryLayout<Element>.alignment)) &- 1
}
/// The actual number of bytes allocated for this object.
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var _capacityInBytes: Int {
return _swift_stdlib_malloc_size(_address)
}
/// The address of this instance in a convenient pointer-to-bytes form
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var _address: UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_nativeBuffer))
}
/// Offset from the allocated storage for `self` to the stored `Header`
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal static var _headerOffset: Int {
_onFastPath()
return _roundUp(
MemoryLayout<_HeapObject>.size,
toAlignment: MemoryLayout<Header>.alignment)
}
/// An **unmanaged** pointer to the storage for the `Header`
/// instance. Not safe to use without _fixLifetime calls to
/// guarantee it doesn't dangle
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var _headerPointer: UnsafeMutablePointer<Header> {
_onFastPath()
return (_address + _My._headerOffset).assumingMemoryBound(
to: Header.self)
}
/// An **unmanaged** pointer to the storage for `Element`s. Not
/// safe to use without _fixLifetime calls to guarantee it doesn't
/// dangle.
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var _elementPointer: UnsafeMutablePointer<Element> {
_onFastPath()
return (_address + _My._elementOffset).assumingMemoryBound(
to: Element.self)
}
/// Offset from the allocated storage for `self` to the `Element` storage
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal static var _elementOffset: Int {
_onFastPath()
return _roundUp(
_headerOffset + MemoryLayout<Header>.size,
toAlignment: MemoryLayout<Element>.alignment)
}
@_inlineable // FIXME(sil-serialize-all)
public static func == (
lhs: ManagedBufferPointer, rhs: ManagedBufferPointer
) -> Bool {
return lhs._address == rhs._address
}
@_versioned // FIXME(sil-serialize-all)
internal var _nativeBuffer: Builtin.NativeObject
}
// FIXME: when our calling convention changes to pass self at +0,
// inout should be dropped from the arguments to these functions.
// FIXME(docs): isKnownUniquelyReferenced should check weak/unowned counts too,
// but currently does not. rdar://problem/29341361
/// Returns a Boolean value indicating whether the given object is known to
/// have a single strong reference.
///
/// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the
/// copy-on-write optimization for the deep storage of value types:
///
/// mutating func update(withValue value: T) {
/// if !isKnownUniquelyReferenced(&myStorage) {
/// myStorage = self.copiedStorage()
/// }
/// myStorage.update(withValue: value)
/// }
///
/// `isKnownUniquelyReferenced(_:)` checks only for strong references to the
/// given object---if `object` has additional weak or unowned references, the
/// result may still be `true`. Because weak and unowned references cannot be
/// the only reference to an object, passing a weak or unowned reference as
/// `object` always results in `false`.
///
/// If the instance passed as `object` is being accessed by multiple threads
/// simultaneously, this function may still return `true`. Therefore, you must
/// only call this function from mutating methods with appropriate thread
/// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)`
/// only returns `true` when there is really one accessor, or when there is a
/// race condition, which is already undefined behavior.
///
/// - Parameter object: An instance of a class. This function does *not* modify
/// `object`; the use of `inout` is an implementation artifact.
/// - Returns: `true` if `object` is known to have a single strong reference;
/// otherwise, `false`.
@_inlineable
public func isKnownUniquelyReferenced<T : AnyObject>(_ object: inout T) -> Bool
{
return _isUnique(&object)
}
@_inlineable
@_versioned
internal func _isKnownUniquelyReferencedOrPinned<T : AnyObject>(_ object: inout T) -> Bool {
return _isUniqueOrPinned(&object)
}
/// Returns a Boolean value indicating whether the given object is known to
/// have a single strong reference.
///
/// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the
/// copy-on-write optimization for the deep storage of value types:
///
/// mutating func update(withValue value: T) {
/// if !isKnownUniquelyReferenced(&myStorage) {
/// myStorage = self.copiedStorage()
/// }
/// myStorage.update(withValue: value)
/// }
///
/// `isKnownUniquelyReferenced(_:)` checks only for strong references to the
/// given object---if `object` has additional weak or unowned references, the
/// result may still be `true`. Because weak and unowned references cannot be
/// the only reference to an object, passing a weak or unowned reference as
/// `object` always results in `false`.
///
/// If the instance passed as `object` is being accessed by multiple threads
/// simultaneously, this function may still return `true`. Therefore, you must
/// only call this function from mutating methods with appropriate thread
/// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)`
/// only returns `true` when there is really one accessor, or when there is a
/// race condition, which is already undefined behavior.
///
/// - Parameter object: An instance of a class. This function does *not* modify
/// `object`; the use of `inout` is an implementation artifact.
/// - Returns: `true` if `object` is known to have a single strong reference;
/// otherwise, `false`. If `object` is `nil`, the return value is `false`.
@_inlineable
public func isKnownUniquelyReferenced<T : AnyObject>(
_ object: inout T?
) -> Bool {
return _isUnique(&object)
}
|
apache-2.0
|
b2a0482af17c742800a297c83c861d9d
| 37.83564 | 92 | 0.689179 | 4.614926 | false | false | false | false |
OscarSwanros/swift
|
stdlib/public/core/LazySequence.swift
|
3
|
7738
|
//===--- LazySequence.swift -----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A sequence on which normally-eager operations such as `map` and
/// `filter` are implemented lazily.
///
/// Lazy sequences can be used to avoid needless storage allocation
/// and computation, because they use an underlying sequence for
/// storage and compute their elements on demand. For example,
///
/// [1, 2, 3].lazy.map { $0 * 2 }
///
/// is a sequence containing { `2`, `4`, `6` }. Each time an element
/// of the lazy sequence is accessed, an element of the underlying
/// array is accessed and transformed by the closure.
///
/// Sequence operations taking closure arguments, such as `map` and
/// `filter`, are normally eager: they use the closure immediately and
/// return a new array. Using the `lazy` property gives the standard
/// library explicit permission to store the closure and the sequence
/// in the result, and defer computation until it is needed.
///
/// To add new lazy sequence operations, extend this protocol with
/// methods that return lazy wrappers that are themselves
/// `LazySequenceProtocol`s. For example, given an eager `scan`
/// method defined as follows
///
/// extension Sequence {
/// /// Returns an array containing the results of
/// ///
/// /// p.reduce(initial, nextPartialResult)
/// ///
/// /// for each prefix `p` of `self`, in order from shortest to
/// /// longest. For example:
/// ///
/// /// (1..<6).scan(0, +) // [0, 1, 3, 6, 10, 15]
/// ///
/// /// - Complexity: O(n)
/// func scan<ResultElement>(
/// _ initial: ResultElement,
/// _ nextPartialResult: (ResultElement, Element) -> ResultElement
/// ) -> [ResultElement] {
/// var result = [initial]
/// for x in self {
/// result.append(nextPartialResult(result.last!, x))
/// }
/// return result
/// }
/// }
///
/// we can build a sequence that lazily computes the elements in the
/// result of `scan`:
///
/// struct LazyScanIterator<Base : IteratorProtocol, ResultElement>
/// : IteratorProtocol {
/// mutating func next() -> ResultElement? {
/// return nextElement.map { result in
/// nextElement = base.next().map { nextPartialResult(result, $0) }
/// return result
/// }
/// }
/// private var nextElement: ResultElement? // The next result of next().
/// private var base: Base // The underlying iterator.
/// private let nextPartialResult: (ResultElement, Base.Element) -> ResultElement
/// }
///
/// struct LazyScanSequence<Base: Sequence, ResultElement>
/// : LazySequenceProtocol // Chained operations on self are lazy, too
/// {
/// func makeIterator() -> LazyScanIterator<Base.Iterator, ResultElement> {
/// return LazyScanIterator(
/// nextElement: initial, base: base.makeIterator(), nextPartialResult)
/// }
/// private let initial: ResultElement
/// private let base: Base
/// private let nextPartialResult:
/// (ResultElement, Base.Element) -> ResultElement
/// }
///
/// and finally, we can give all lazy sequences a lazy `scan` method:
///
/// extension LazySequenceProtocol {
/// /// Returns a sequence containing the results of
/// ///
/// /// p.reduce(initial, nextPartialResult)
/// ///
/// /// for each prefix `p` of `self`, in order from shortest to
/// /// longest. For example:
/// ///
/// /// Array((1..<6).lazy.scan(0, +)) // [0, 1, 3, 6, 10, 15]
/// ///
/// /// - Complexity: O(1)
/// func scan<ResultElement>(
/// _ initial: ResultElement,
/// _ nextPartialResult: (ResultElement, Element) -> ResultElement
/// ) -> LazyScanSequence<Self, ResultElement> {
/// return LazyScanSequence(
/// initial: initial, base: self, nextPartialResult)
/// }
/// }
///
/// - See also: `LazySequence`, `LazyCollectionProtocol`, `LazyCollection`
///
/// - Note: The explicit permission to implement further operations
/// lazily applies only in contexts where the sequence is statically
/// known to conform to `LazySequenceProtocol`. Thus, side-effects such
/// as the accumulation of `result` below are never unexpectedly
/// dropped or deferred:
///
/// extension Sequence where Element == Int {
/// func sum() -> Int {
/// var result = 0
/// _ = self.map { result += $0 }
/// return result
/// }
/// }
///
/// [We don't recommend that you use `map` this way, because it
/// creates and discards an array. `sum` would be better implemented
/// using `reduce`].
public protocol LazySequenceProtocol : Sequence {
/// A `Sequence` that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// - See also: `elements`
associatedtype Elements : Sequence = Self
where Elements.Iterator.Element == Iterator.Element
/// A sequence containing the same elements as this one, possibly with
/// a simpler type.
///
/// When implementing lazy operations, wrapping `elements` instead
/// of `self` can prevent result types from growing an extra
/// `LazySequence` layer. For example,
///
/// _prext_ example needed
///
/// Note: this property need not be implemented by conforming types,
/// it has a default implementation in a protocol extension that
/// just returns `self`.
var elements: Elements { get }
}
/// When there's no special associated `Elements` type, the `elements`
/// property is provided.
extension LazySequenceProtocol where Elements == Self {
/// Identical to `self`.
@_inlineable // FIXME(sil-serialize-all)
public var elements: Self { return self }
}
/// A sequence containing the same elements as a `Base` sequence, but
/// on which some operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See also: `LazySequenceProtocol`
@_fixed_layout // FIXME(sil-serialize-all)
public struct LazySequence<Base : Sequence>
: LazySequenceProtocol, _SequenceWrapper {
/// Creates a sequence that has the same elements as `base`, but on
/// which some operations such as `map` and `filter` are implemented
/// lazily.
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(_base: Base) {
self._base = _base
}
public var _base: Base
/// The `Base` (presumably non-lazy) sequence from which `self` was created.
@_inlineable // FIXME(sil-serialize-all)
public var elements: Base { return _base }
}
extension Sequence {
/// A sequence containing the same elements as this sequence,
/// but on which some operations, such as `map` and `filter`, are
/// implemented lazily.
@_inlineable // FIXME(sil-serialize-all)
public var lazy: LazySequence<Self> {
return LazySequence(_base: self)
}
}
/// Avoid creating multiple layers of `LazySequence` wrapper.
/// Anything conforming to `LazySequenceProtocol` is already lazy.
extension LazySequenceProtocol {
/// Identical to `self`.
@_inlineable // FIXME(sil-serialize-all)
public var lazy: Self {
return self
}
}
|
apache-2.0
|
88cc9a2e959672bbcc3d31f33e529006
| 36.931373 | 87 | 0.622254 | 4.294118 | false | false | false | false |
carambalabs/Paparajote
|
Paparajote/Classes/Providers/GitLabProvider.swift
|
1
|
3191
|
import Foundation
import NSURL_QueryDictionary
public struct GitLabProvider: OAuth2Provider {
// MARK: - Attributes
fileprivate let clientId: String
fileprivate let clientSecret: String
fileprivate let redirectUri: String
fileprivate let state: String
fileprivate let url: URL
// MARK: - Init
public init(url: URL = URL(string: "https://gitlab.com")!,
clientId: String,
clientSecret: String,
redirectUri: String,
state: String = String.random()) {
self.url = url
self.clientId = clientId
self.clientSecret = clientSecret
self.redirectUri = redirectUri
self.state = state
}
// MARK: - Oauth2Provider
public var authorization: Authorization {
get {
return { () -> URL in
var components = URLComponents(url: self.url, resolvingAgainstBaseURL: false)!
components.path = "/oauth/authorize"
components.queryItems = [
URLQueryItem(name: "client_id", value: self.clientId),
URLQueryItem(name: "redirect_uri", value: self.redirectUri),
URLQueryItem(name: "response_type", value: "code"),
URLQueryItem(name: "state", value: self.state)
]
return components.url!
}
}
}
public var authentication: Authentication {
get {
return { url -> URLRequest? in
if !url.absoluteString.contains(self.redirectUri) { return nil }
guard let code = (url as NSURL).uq_queryDictionary()["code"] as? String,
let state = (url as NSURL).uq_queryDictionary()["state"] as? String else { return nil }
if state != self.state { return nil }
var components = URLComponents(url: self.url, resolvingAgainstBaseURL: false)!
components.path = "/oauth/token"
components.queryItems = [
URLQueryItem(name: "client_id", value: self.clientId),
URLQueryItem(name: "client_secret", value: self.clientSecret),
URLQueryItem(name: "code", value: code),
URLQueryItem(name: "redirect_uri", value: self.redirectUri),
URLQueryItem(name: "grant_type", value: "authorization_code")
]
let request = NSMutableURLRequest()
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
request.url = components.url!
return request.copy() as? URLRequest
}
}
}
public var sessionAdapter: SessionAdapter = { (data, _) -> OAuth2Session? in
let json = try? JSONSerialization.jsonObject(with: data, options: [])
guard let dictionary = json as? [String: Any] else { return nil }
let token = dictionary["access_token"] as? String
let refresh = dictionary["refresh_token"] as? String
return token.map {OAuth2Session(accessToken: $0, refreshToken: refresh)}
}
}
|
mit
|
ff2f0909a6fd319886c0ba09fb090b30
| 39.910256 | 107 | 0.570981 | 5.041074 | false | false | false | false |
AliSoftware/SwiftGen
|
Sources/SwiftGenKit/Parsers/AssetsCatalog/CatalogEntry.swift
|
1
|
4358
|
//
// SwiftGenKit
// Copyright © 2020 SwiftGen
// MIT Licence
//
import Foundation
import PathKit
protocol AssetsCatalogEntry {
var name: String { get }
// Used for converting to stencil context
var asDictionary: [String: Any] { get }
}
extension AssetsCatalog {
enum Entry {
struct Group: AssetsCatalogEntry {
let name: String
let isNamespaced: Bool
let items: [AssetsCatalogEntry]
}
struct Item: AssetsCatalogEntry {
let name: String
let value: String
let item: Constants.Item
}
}
}
// MARK: - Parser
enum Constants {
fileprivate static let path = "Contents.json"
fileprivate static let properties = "properties"
fileprivate static let providesNamespace = "provides-namespace"
///
/// This is a list of supported asset catalog item types, for now we just
/// support `color set`s, `image set`s and `data set`s. If you want to add support for
/// new types, just add it to this whitelist, and add the necessary code to
/// the `process(folder:withPrefix:)` method.
///
/// Use as reference:
/// https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_ref-Asset_Catalog_Format
///
enum Item: String, CaseIterable {
case arResourceGroup = "arresourcegroup"
case colorSet = "colorset"
case dataSet = "dataset"
case imageSet = "imageset"
case symbolSet = "symbolset"
}
}
extension AssetsCatalog.Entry {
///
/// Each node in an asset catalog is either (there are more types, but we ignore those):
/// - An AR resource group, which can contain both AR reference images and objects.
/// - A colorset, which is essentially a group containing a list of colors (the latter is ignored).
/// - A dataset, which is essentially a group containing a list of files (the latter is ignored).
/// - An imageset, which is essentially a group containing a list of files (the latter is ignored).
/// - A symbolset, which is essentially a group containing a list of files (the latter is ignored).
/// - A group, containing sub items such as imagesets or groups. A group can provide a namespaced,
/// which means that all the sub items will have to be prefixed with their parent's name.
///
/// {
/// "properties" : {
/// "provides-namespace" : true
/// }
/// }
///
/// - Parameter path: The directory path to recursively process.
/// - Parameter prefix: The prefix to prepend values with (from namespaced groups).
/// - Returns: An array of processed Entry items (a catalog).
///
static func parse(path: Path, withPrefix prefix: String) -> AssetsCatalogEntry? {
guard path.isDirectory else { return nil }
let type = path.extension ?? ""
if let item = Constants.Item(rawValue: type) {
return AssetsCatalog.Entry.Item(path: path, item: item, withPrefix: prefix)
} else if type.isEmpty {
// this is a group, they can't have any '.' in their name
let filename = path.lastComponent
let isNamespaced = AssetsCatalog.Entry.isNamespaced(path: path)
let subPrefix = isNamespaced ? "\(prefix)\(filename)/" : prefix
return AssetsCatalog.Entry.Group(
name: filename,
isNamespaced: isNamespaced,
items: AssetsCatalog.Catalog.process(folder: path, withPrefix: subPrefix)
)
} else {
// Unknown extension
return nil
}
}
}
// MARK: - Private Helpers
extension AssetsCatalog.Entry.Item {
fileprivate init(path: Path, item: Constants.Item, withPrefix prefix: String) {
self.name = path.lastComponentWithoutExtension
self.value = "\(prefix)\(name)"
self.item = item
}
}
extension AssetsCatalog.Entry {
fileprivate static func isNamespaced(path: Path) -> Bool {
let metadata = self.metadata(for: path)
if let properties = metadata[Constants.properties] as? [String: Any],
let providesNamespace = properties[Constants.providesNamespace] as? Bool {
return providesNamespace
} else {
return false
}
}
private static func metadata(for path: Path) -> [String: Any] {
let contentsFile = path + Path(Constants.path)
guard let data = try? contentsFile.read(),
let json = try? JSONSerialization.jsonObject(with: data, options: []) else {
return [:]
}
return (json as? [String: Any]) ?? [:]
}
}
|
mit
|
fb275eac560f818dec376e359351659c
| 31.514925 | 110 | 0.670186 | 4.234208 | false | false | false | false |
seeaya/Simplex
|
Simplex/Colors.swift
|
1
|
12575
|
//
// Colors.swift
// Simplex
//
// Created by Connor Barnes on 5/22/17.
// Copyright © 2017 Connor Barnes. All rights reserved.
//
/// Defines a color with alpha component. Color provides various color conversions, but stores its data in RGB, so use RGB for no loss in quality.
public struct Color {
// Where the actual values of the color are held in red, green, blue format (from 0 to 1)
var _rgb: (red: Double, green: Double, blue: Double)
/// Red, Blue, and Green values of the color from 0 to 1.
public var rgb: (red: Double, green: Double, blue: Double) {
get {
return _rgb
}
set {
// Cap and set red
switch newValue.red {
case 0...1:
_rgb.red = newValue.red
case let x where x > 1:
_rgb.red = 1
case let x where x < 0:
_rgb.red = 0
default:
break
}
// Cap and set green
switch newValue.green {
case 0...1:
_rgb.green = newValue.green
case let x where x > 1:
_rgb.green = 1
case let x where x < 0:
_rgb.green = 0
default:
break
}
// Cap and set blue
switch newValue.blue {
case 0...1:
_rgb.blue = newValue.blue
case let x where x > 1:
_rgb.blue = 1
case let x where x < 0:
_rgb.blue = 0
default:
break
}
}
}
// Where the actual value of the alpha of the color is held (from 0 to 1)
var _alpha: Double
/// Transparency of the color from 0 to 1: 0 being completely transparent and 1 being completely opaque.
public var alpha: Double {
get {
return _alpha
}
set {
// Cap and set alpha
switch newValue {
case 0...1:
_alpha = newValue
case let x where x > 1:
_alpha = 1
case let x where x < 0:
_alpha = 0
default:
break
}
}
}
/// Creates a fully opaque white color
public init() {
_rgb = (red: 1, green: 1, blue: 1)
_alpha = 1
}
/// Creates a color from red, blue, and green values
///
/// - Parameters:
/// - red: The amount of red from 0 to 1
/// - green: The amount of green from 0 to 1
/// - blue: The amount of blue from 0 to 1
public init(red: Double, green: Double, blue: Double) {
self.init()
rgb = (red: red, green: green, blue: blue)
}
/// Creates a color from red, blue, green, and alpha values
///
/// - Parameters:
/// - red: The amount of red from 0 to 1
/// - green: The amount of green from 0 to 1
/// - blue: The amount of blue from 0 to 1
/// - alpha: The opacity from 0 to 1
public init(red: Double, green: Double, blue: Double, alpha: Double) {
self.init(red: red, green: green, blue: blue)
self.alpha = alpha
}
}
// MARK: Color Conversions
extension Color {
// Conversion formula from http://www.rapidtables.com/convert/color/
/// Hue, Saturation, and Brightness (Value) values of the color from 0 to 1.
public var hsb: (hue: Double, saturation: Double, brightness: Double) {
get {
let maximum = max(_rgb.red, _rgb.green, _rgb.blue)
let delta = maximum - min(_rgb.red, _rgb.green, _rgb.blue)
// Calculate hue
var hue: Double
if delta == 0 {
hue = 0
} else {
switch maximum {
case _rgb.red:
hue = pi/3 * ((_rgb.green - _rgb.blue)/delta).truncatingRemainder(dividingBy: 6)
case _rgb.green:
hue = pi/3 * ((_rgb.blue - _rgb.red)/delta + 2)
case _rgb.blue:
hue = pi/3 * ((_rgb.red - _rgb.green)/delta + 4)
default:
hue = 0.0
}
}
// Calculate saturation
var saturation: Double
if maximum == 0 {
saturation = 0
} else {
saturation = delta/maximum
}
// Calculate brightness
let brightness = maximum
return (hue: hue, saturation: saturation, brightness: brightness)
}
set {
// Cap hue
let newHue = newValue.hue.truncatingRemainder(dividingBy: 2*pi)
// Cap saturation
var newSaturation: Double
switch newValue.saturation {
case 0...1:
newSaturation = newValue.saturation
case let x where x > 1:
newSaturation = 1
case let x where x < 0:
newSaturation = 0
default:
newSaturation = 0
}
// Cap brightness
var newBrightness: Double
switch newValue.brightness {
case 0...1:
newBrightness = newValue.brightness
case let x where x > 1:
newBrightness = 1
case let x where x < 0:
newBrightness = 0
default:
newBrightness = 0
}
// Intermediate values
let c = newBrightness * newSaturation
let x = c * (1 - abs((newHue/pi/3).truncatingRemainder(dividingBy: 2) - 1))
let m = newBrightness - c
// Calculate new values
var newRed: Double
var newGreen: Double
var newBlue: Double
switch newHue {
case 0..<pi/3:
newRed = c + m
newGreen = x + m
newBlue = m
case pi/3..<2*pi/3:
newRed = x + m
newGreen = c + m
newBlue = 0
case 2*pi/3..<pi:
newRed = m
newGreen = c + m
newBlue = x + m
case pi..<4*pi/3:
newRed = 0
newGreen = x + m
newBlue = c + m
case 4*pi/3..<5*pi/3:
newRed = x + m
newGreen = m
newBlue = c + m
case 5*pi/3..<2*pi:
newRed = c + m
newGreen = m
newBlue = x + m
default:
newRed = 0
newGreen = 0
newBlue = 0
}
// Apply new values
rgb = (red: newRed, green: newGreen, blue: newBlue)
}
}
/// Creates a color from hue, saturation, and brightness (value) values.
///
/// - Parameters:
/// - hue: The shade of the color (0 is red, 2π/3 is green, 4π/3 is blue) from 0 to 2π
/// - saturation: The intensity of the color from 0 to 1
/// - brightness: The brightness of the color from 0 to 1
public init(hue: Double, saturation: Double, brightness: Double) {
self.init()
hsb = (hue: hue, saturation: saturation, brightness: brightness)
}
/// Creates a color from hue, saturation, brightness (value) and alpha values.
///
/// - Parameters:
/// - hue: The shade of the color (0 is red, 2π/3 is green, 4π/3 is blue) from 0 to 2π
/// - saturation: The intensity of the color from 0 to 1
/// - brightness: The brightness of the color from 0 to 1
/// - alpha: The opacity of the color from 0 to 1
public init(hue: Double, saturation: Double, brightness: Double, alpha: Double) {
self.init(hue: hue, saturation: saturation, brightness: brightness)
self.alpha = alpha
}
}
extension Color {
// Conversion formula from http://www.rapidtables.com/convert/color/
/// Cyan, Magenta, Yellow and Black (Key) values of the color from 0 to 1.
public var cmyk: (cyan: Double, magenta: Double, yellow: Double, black: Double) {
get {
// Calculate black
let black = 1 - max(rgb.red, rgb.green, rgb.blue)
if black == 1 {
return (cyan: 0, magenta: 0, yellow: 0, black: 1)
}
// Calculate cyan, magenta, and yellow
let cyan = (1 - rgb.red - black) / (1 - black)
let magenta = (1 - rgb.green - black) / (1 - black)
let yellow = (1 - rgb.blue - black) / (1 - black)
return (cyan: cyan, magenta: magenta, yellow: yellow, black: black)
}
set {
var newBlack: Double
var newCyan: Double
var newMagenta: Double
var newYellow: Double
// Cap black
switch newValue.black {
case 0...1:
newBlack = newValue.black
case let x where x > 1:
newBlack = 1
case let x where x < 0:
newBlack = 0
default:
newBlack = 0
}
// Cap cyan
switch newValue.cyan {
case 0...1:
newCyan = newValue.cyan
case let x where x > 1:
newCyan = 1
case let x where x < 0:
newCyan = 0
default:
newCyan = 0
}
// Cap magenta
switch newValue.magenta {
case 0...1:
newMagenta = newValue.magenta
case let x where x > 1:
newMagenta = 1
case let x where x < 0:
newMagenta = 0
default:
newMagenta = 0
}
// Cap yellow
switch newValue.yellow {
case 0...1:
newYellow = newValue.yellow
case let x where x > 1:
newYellow = 1
case let x where x < 0:
newYellow = 0
default:
newYellow = 0
}
// Calculate new values
let newRed = (1 - newCyan) * (1 - newBlack)
let newGreen = (1 - newMagenta) * (1 - newBlack)
let newBlue = (1 - newYellow) * (1 - newBlack)
// Apply new values
rgb = (red: newRed, green: newGreen, blue: newBlue)
}
}
/// Creates a color from cyan, magenta, yellow, and black (key) values.
///
/// - Parameters:
/// - cyan: The amount of cyan from 0 to 1
/// - magenta: The amount of magenta from 0 to 1
/// - yellow: The amount of yellow from 0 to 1
/// - black: The amount of black from 0 to 1
public init(cyan: Double, magenta: Double, yellow: Double, black: Double) {
self.init()
cmyk = (cyan: cyan, magenta: magenta, yellow: yellow, black: black)
}
/// Creates a color from cyan, magenta, yellow, black (key) and alpha values.
///
/// - Parameters:
/// - cyan: The amount of cyan from 0 to 1
/// - magenta: The amount of magenta from 0 to 1
/// - yellow: The amount of yellow from 0 to 1
/// - black: The amount of black from 0 to 1
/// - alpha: The opacity from 0 to 1
public init(cyan: Double, magenta: Double, yellow: Double, black: Double, alpha: Double) {
self.init(cyan: cyan, magenta: magenta, yellow: yellow, black: black)
self.alpha = alpha
}
}
/// The method by which to calculate the grayscale value of a color.
///
/// - lightness: Averages the least and most prominent RGB values
/// - average: Averages the RGB values
/// - luminosity: Averages the RGB values, weighting for human perception (Default)
enum GrayscaleMethod {
case lightness
case average
case luminosity
}
extension Color {
/// Returns the grayscale value of the color.
///
/// - Parameter method: The method by which to calculate the grayscale value of the color (luminosity is used if no method is specified).
/// - Returns: The grayscale value of the color from 0 to 1.
func whiteness(using method: GrayscaleMethod = .luminosity) -> Double {
switch method {
case .lightness:
return (max(rgb.red, rgb.green, rgb.blue) + min(rgb.red, rgb.green, rgb.blue)) / 2
case .average:
return (rgb.red + rgb.green + rgb.blue) / 3
case .luminosity:
return 0.21*rgb.red + 0.72*rgb.green + 0.07*rgb.blue
}
}
}
// Predefined Colors
extension Color {
/// Returns a fully opaque color with RGB values 1, 0, 0.
public static var red: Color {
get {
return Color(red: 1, green: 0, blue: 0)
}
}
/// Returns a fully opaque color with RGB values 0, 1, 0.
public static var green: Color {
get {
return Color(red: 0, green: 1, blue: 0)
}
}
/// Returns a fully opaque color with RGB values 0, 0, 1.
public static var blue: Color {
get {
return Color(red: 0, green: 0, blue: 1)
}
}
/// Returns a fully opaque color with RGB values 0, 1, 1.
public static var cyan: Color {
get {
return Color(red: 0, green: 1, blue: 1)
}
}
/// Returns a fully opaque color with RGB values 1, 0, 1.
public static var magenta: Color {
get {
return Color(red: 1, green: 0, blue: 1)
}
}
/// Returns a fully opaque color with RGB values 1, 1, 0.
public static var yellow: Color {
get {
return Color(red: 1, green: 1, blue: 0)
}
}
/// Returns a fully opaque color with RGB values 1, 1, 1.
public static var white: Color {
get {
return Color(red: 1, green: 1, blue: 1)
}
}
/// Returns a fully opaque color with RGB values 0, 0 , 0.
public static var black: Color {
get {
return Color(red: 0, green: 0, blue: 0)
}
}
/// Returns a fully transparent color with RGB values 1, 1, 1.
public static var clear: Color {
get {
return Color(red: 1, green: 1, blue: 1, alpha: 0)
}
}
/// Returns a fully opaque color with RGB values 0.6, 0.4, 0.2.
public static var brown: Color {
get {
return Color(red: 0.6, green: 0.4, blue: 0.2)
}
}
/// Returns a fully opaque color with RGB values 1, 0.5, 0.
public static var orange: Color {
get {
return Color(red: 1, green: 0.5, blue: 0)
}
}
/// Returns a fully opaque color with RGB values 0.5, 0, 0.5
public static var purple: Color {
get {
return Color(red: 0.5, green: 0, blue: 0.5)
}
}
/// Returns a fully opaque color with RGB values 0.5, 0.5, 0.5
public static var gray: Color {
get {
return Color(red: 0.5, green: 0.5, blue: 0.5)
}
}
/// Returns a fully opaque color with RGB values 2/3, 2/3, 2/3.
public static var lightGray: Color {
get {
return Color(red: 2/3, green: 2/3, blue: 2/3)
}
}
/// Returns a fully opaque color with RBG values 1/3, 1/3, 1/3.
public static var darkGray: Color {
get {
return Color(red: 1/3, green: 1/3, blue: 1/3)
}
}
}
|
gpl-3.0
|
817ffe0c2f8dd5d2e99319d133288abb
| 23.936508 | 146 | 0.615452 | 3.052708 | false | false | false | false |
benlangmuir/swift
|
test/SILOptimizer/OSLogMandatoryOptTest.swift
|
2
|
36299
|
// RUN: %target-swift-frontend -enable-copy-propagation=requested-passes-only -enable-lexical-lifetimes=false -swift-version 5 -emit-sil -primary-file %s -Xllvm -sil-print-after=OSLogOptimization -o /dev/null 2>&1 | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
//
// REQUIRES: VENDOR=apple
// Tests for the OSLogOptimization pass that performs compile-time analysis
// and optimization of the new os log APIs. The tests here check whether specific
// compile-time constants such as the format string, the size of the byte buffer etc. are
// literals after the mandatory pipeline.
import OSLogTestHelper
import Foundation
// CHECK-LABEL: @${{.*}}testSimpleInterpolationyy
func testSimpleInterpolation() {
_osLogTestHelper("Minimum integer value: \(Int.min)")
// Check if there is a call to _os_log_impl with a literal format string.
// CHECK-DAG is used here as it is easier to perform the checks backwards
// from uses to the definitions.
// Match the format string first.
// CHECK: string_literal utf8 "Minimum integer value: %ld"
// Check if the size of the argument buffer is a constant.
// CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ
// CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]]
// CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 12
// CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 8
// Check whether the header bytes: premable and argument count are constants.
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 0
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 1
// Check whether argument array is folded. We need not check the contents of
// the array which is checked by a different test suite.
// CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF
// CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>>({{%.*}}, [[SB:%[0-9]+]])
// CHECK-DAG: [[SB]] = store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR:%[0-9]+]]
// We need to wade through some borrows and copy values here.
// CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[FINARR:%[0-9]+]]
// CHECK-DAG: [[FINARRFUNC:%[0-9]+]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK-DAG: [[FINARR]] = apply [[FINARRFUNC]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARGSARRAY:%[0-9]+]])
// CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]]
// CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARRAYSIZE:%[0-9]+]])
// CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 3
}
// CHECK-LABEL: @${{.*}}testInterpolationWithFormatOptionsyy
func testInterpolationWithFormatOptions() {
_osLogTestHelper("Maximum unsigned integer value: \(UInt.max, format: .hex)")
// Check if there is a call to _os_log_impl with a literal format string.
// Match the format string first.
// CHECK: string_literal utf8 "Maximum unsigned integer value: %lx"
// Check if the size of the argument buffer is a constant.
// CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ
// CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]]
// CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 12
// CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 8
// Check whether the header bytes: premable and argument count are constants.
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 0
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 1
// Check whether argument array is folded. We need not check the contents of
// the array which is checked by a different test suite.
// CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF
// CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>>({{%.*}}, [[SB:%[0-9]+]])
// CHECK-DAG: [[SB]] = store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[FINARR:%[0-9]+]]
// CHECK-DAG: [[FINARRFUNC:%[0-9]+]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK-DAG: [[FINARR]] = apply [[FINARRFUNC]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARGSARRAY:%[0-9]+]])
// CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]]
// CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARRAYSIZE:%[0-9]+]])
// CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 3
}
// CHECK-LABEL: @${{.*}}testInterpolationWithFormatOptionsAndPrivacyyy
func testInterpolationWithFormatOptionsAndPrivacy() {
let privateID: UInt = 0x79abcdef
_osLogTestHelper(
"Private Identifier: \(privateID, format: .hex, privacy: .private)")
// Check if there is a call to _os_log_impl with a literal format string.
// Match the format string first.
// CHECK: string_literal utf8 "Private Identifier: %{private}lx"
// Check if the size of the argument buffer is a constant.
// CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ
// CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]]
// CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 12
// CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 8
// Check whether the header bytes: premable and argument count are constants.
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 1
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 1
// Check whether argument array is folded. We need not check the contents of
// the array which is checked by a different test suite.
// CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF
// CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>>({{%.*}}, [[SB:%[0-9]+]])
// CHECK-DAG: [[SB]] = store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[FINARR:%[0-9]+]]
// CHECK-DAG: [[FINARRFUNC:%[0-9]+]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK-DAG: [[FINARR]] = apply [[FINARRFUNC]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARGSARRAY:%[0-9]+]])
// CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]]
// CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARRAYSIZE:%[0-9]+]])
// CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 3
}
// CHECK-LABEL: @${{.*}}testInterpolationWithMultipleArgumentsyy
func testInterpolationWithMultipleArguments() {
let privateID = 0x79abcdef
let filePermissions: UInt = 0o777
let pid = 122225
_osLogTestHelper(
"""
Access prevented: process \(pid, privacy: .public) initiated by \
user: \(privateID, privacy: .private) attempted resetting \
permissions to \(filePermissions, format: .octal)
""")
// Check if there is a call to _os_log_impl with a literal format string.
// Match the format string first.
// CHECK: string_literal utf8 "Access prevented: process %{public}ld initiated by user: %{private}ld attempted resetting permissions to %lo"
// Check if the size of the argument buffer is a constant.
// CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ
// CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]]
// CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 32
// CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 20
// Check whether the header bytes: premable and argument count are constants.
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 1
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 3
// Check whether argument array is folded. We need not check the contents of
// the array which is checked by a different test suite.
// CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF
// CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>>({{%.*}}, [[SB:%[0-9]+]])
// CHECK-DAG: [[SB]] = store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAYADDR]] = alloc_stack $Array<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>
// CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[FINARR:%[0-9]+]]
// CHECK-DAG: [[FINARRFUNC:%[0-9]+]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK-DAG: [[FINARR]] = apply [[FINARRFUNC]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARGSARRAY:%[0-9]+]])
// CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]]
// CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARRAYSIZE:%[0-9]+]])
// CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 9
}
// CHECK-LABEL: @${{.*}}testLogMessageWithoutDatayy
func testLogMessageWithoutData() {
// FIXME: here `ExpressibleByStringLiteral` conformance of OSLogMessage
// is used. In this case, the constant evaluation begins from the apply of
// the "string.makeUTF8: initializer. The constant evaluator ends up using
// the backward mode to identify the string_literal inst passed to the
// initializer. Eliminate reliance on this backward mode by starting from
// the string_literal inst, instead of initialization instruction.
_osLogTestHelper("A message with no data")
// Check if there is a call to _os_log_impl with a literal format string.
// Match the format string first.
// CHECK: string_literal utf8 "A message with no data"
// Check if the size of the argument buffer is a constant.
// CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ
// CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]]
// CHECK-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int{{[0-9]+}}, 2
// Check whether the header bytes: premable and argument count are constants.
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 0
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 0
// Check whether argument array is folded.
// CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF
// CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>>({{%.*}}, [[SB:%[0-9]+]])
// CHECK-DAG: [[SB]] = store_borrow [[ARGSARRAY2:%[0-9]+]] to {{.*}}
// CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[ARGSARRAY:%[0-9]+]]
// CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]]
// CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARRAYSIZE:%[0-9]+]])
// CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 0
}
// CHECK-LABEL: @${{.*}}testEscapingOfPercentsyy
func testEscapingOfPercents() {
_osLogTestHelper("Process failed after 99% completion")
// Match the format string first.
// CHECK: string_literal utf8 "Process failed after 99%% completion"
}
// CHECK-LABEL: @${{.*}}testDoublePercentsyy
func testDoublePercents() {
_osLogTestHelper("Double percents: %%")
// Match the format string first.
// CHECK: string_literal utf8 "Double percents: %%%%"
}
// CHECK-LABEL: @${{.*}}testSmallFormatStringsyy
func testSmallFormatStrings() {
_osLogTestHelper("a")
// Match the format string first.
// CHECK: string_literal utf8 "a"
}
/// A stress test that checks whether the optimizer handle messages with more
/// than 48 interpolated expressions. Interpolated expressions beyond this
/// limit must be ignored.
// CHECK-LABEL: @${{.*}}testMessageWithTooManyArgumentsyy
func testMessageWithTooManyArguments() {
_osLogTestHelper(
"""
\(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \
\(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \
\(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \
\(1) \(1) \(1) \(1) \(1) \(48) \(49)
""")
// Check if there is a call to _os_log_impl with a literal format string.
// Match the format string first.
// CHECK: string_literal utf8 "%ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld "
// Check if the size of the argument buffer is a constant.
// CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ
// CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]]
// CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 482
// CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 290
// Check whether the header bytes: premable and argument count are constants.
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 0
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 48
// Check whether argument array is folded.
// CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF
// CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>>({{%.*}}, [[SB:%[0-9]+]])
// CHECK-DAG: [[SB]] = store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[FINARR:%[0-9]+]]
// CHECK-DAG: [[FINARRFUNC:%[0-9]+]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK-DAG: [[FINARR]] = apply [[FINARRFUNC]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARGSARRAY:%[0-9]+]])
// CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]]
// CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARRAYSIZE:%[0-9]+]])
// CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 144
}
// CHECK-LABEL: @${{.*}}testInt32Interpolationyy
func testInt32Interpolation() {
_osLogTestHelper("32-bit integer value: \(Int32.min)")
// Check if there is a call to _os_log_impl with a literal format string.
// Match the format string first.
// CHECK: string_literal utf8 "32-bit integer value: %d"
// Check if the size of the argument buffer is a constant.
// CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ
// CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]]
// CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 8
// CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 8
// Check whether the header bytes: premable and argument count are constants.
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 0
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 1
}
// CHECK-LABEL: @${{.*}}testDynamicStringArgumentsyy
func testDynamicStringArguments() {
let concatString = "hello" + " - " + "world"
let interpolatedString = "\(31) trillion digits of pi are known so far"
_osLogTestHelper(
"""
concat: \(concatString, privacy: .public) \
interpolated: \(interpolatedString, privacy: .private)
""")
// Check if there is a call to _os_log_impl with a literal format string.
// CHECK-DAG is used here as it is easier to perform the checks backwards
// from uses to the definitions.
// Match the format string first.
// CHECK: string_literal utf8 "concat: %{public}s interpolated: %{private}s"
// Check if the size of the argument buffer is a constant.
// CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ
// CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]]
// CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 22
// CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 14
// Check whether the header bytes: premable and argument count are constants.
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 3
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 2
// Check whether argument array is folded. We need not check the contents of
// the array which is checked by a different test suite.
// CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF
// CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>>({{%.*}}, [[SB:%[0-9]+]])
// CHECK-DAG: [[SB]] = store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[FINARR:%[0-9]+]]
// CHECK-DAG: [[FINARRFUNC:%[0-9]+]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK-DAG: [[FINARR]] = apply [[FINARRFUNC]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARGSARRAY:%[0-9]+]])
// CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]]
// CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARRAYSIZE:%[0-9]+]])
// CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 6
}
// CHECK-LABEL: @${{.*}}testNSObjectInterpolationyy
func testNSObjectInterpolation() {
let nsArray: NSArray = [0, 1, 2]
let nsDictionary: NSDictionary = [1 : ""]
_osLogTestHelper(
"""
NSArray: \(nsArray, privacy: .public) \
NSDictionary: \(nsDictionary, privacy: .private)
""")
// Check if there is a call to _os_log_impl with a literal format string.
// CHECK-DAG is used here as it is easier to perform the checks backwards
// from uses to the definitions.
// Match the format string first.
// CHECK: string_literal utf8 "NSArray: %{public}@ NSDictionary: %{private}@"
// Check if the size of the argument buffer is a constant.
// CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ
// CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]]
// CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 22
// CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 14
// Check whether the header bytes: premable and argument count are constants.
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 3
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 2
// Check whether argument array is folded. We need not check the contents of
// the array which is checked by a different test suite.
// CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF
// CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>>({{%.*}}, [[SB:%[0-9]+]])
// CHECK-DAG: [[SB]] = store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[FINARR:%[0-9]+]]
// CHECK-DAG: [[FINARRFUNC:%[0-9]+]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK-DAG: [[FINARR]] = apply {{.*}}<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARGSARRAY:%[0-9]+]])
// CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]]
// CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARRAYSIZE:%[0-9]+]])
// CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 6
}
// CHECK-LABEL: @${{.*}}testDoubleInterpolationyy
func testDoubleInterpolation() {
let twoPi = 2 * 3.14
_osLogTestHelper("Tau = \(twoPi)")
// Check if there is a call to _os_log_impl with a literal format string.
// CHECK-DAG is used here as it is easier to perform the checks backwards
// from uses to the definitions.
// Match the format string first.
// CHECK: string_literal utf8 "Tau = %f"
// Check if the size of the argument buffer is a constant.
// CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ
// CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]]
// CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 12
// CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 12
// Check whether the header bytes: premable and argument count are constants.
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 0
// CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s15OSLogTestHelper9serialize_2atys5UInt8V_SpyAEGztF
// CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}})
// CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8)
// CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 1
// Check whether argument array is folded. The contents of the array is
// not checked here, but is checked by a different test suite.
// CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF
// CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>>({{%.*}}, [[SB:%[0-9]+]])
// CHECK-DAG: [[SB]] = store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]]
// CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[FINARR:%[0-9]+]]
// CHECK-DAG: [[FINARRFUNC:%[0-9]+]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF
// CHECK-DAG: [[FINARR]] = apply [[FINARRFUNC]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARGSARRAY:%[0-9]+]])
// CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]]
// CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Optional<UnsafeMutablePointer<NSObject>>, inout Optional<UnsafeMutablePointer<Any>>) -> ()>([[ARRAYSIZE:%[0-9]+]])
// CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF
// CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 3
}
// CHECK-LABEL: @${{.*}}testDeadCodeElimination6number8num32bit6stringySi_s5Int32VSStF
func testDeadCodeElimination(
number: Int,
num32bit: Int32,
string: String
) {
_osLogTestHelper("A message with no data")
_osLogTestHelper("smallstring")
_osLogTestHelper(
"""
A message with many interpolations \(number), \(num32bit), \(string), \
and a suffix
""")
_osLogTestHelper(
"""
\(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \
\(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \
\(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \
\(1) \(1) \(1) \(1) \(1) \(48) \(49)
""")
let concatString = string + ":" + String(number)
_osLogTestHelper("\(concatString)")
// CHECK-NOT: OSLogMessage
// CHECK-NOT: OSLogInterpolation
// CHECK-LABEL: end sil function '${{.*}}testDeadCodeElimination6number8num32bit6stringySi_s5Int32VSStF
}
protocol Proto {
var property: String { get set }
}
// Test capturing of address-only types in autoclosures. The following tests check that
// there are no crashes in these cases.
// CHECK-LABEL: @${{.*}}testInterpolationOfExistentials1pyAA5Proto_p_tF
func testInterpolationOfExistentials(p: Proto) {
_osLogTestHelper("A protocol's property \(p.property)")
}
// CHECK-LABEL: @${{.*}}testInterpolationOfGenerics1pyx_tAA5ProtoRzlF
func testInterpolationOfGenerics<T : Proto>(p: T) {
_osLogTestHelper("A generic argument's property \(p.property)")
}
class TestClassSelfTypeCapture {
// CHECK-LABEL: @${{.*}}TestClassSelfTypeCaptureC04testdeF0yyF
func testSelfTypeCapture() {
_osLogTestHelper("Self type of a class \(String(describing: Self.self))")
}
}
struct TestStructSelfTypeCapture {
// CHECK-LABEL: @${{.*}}TestStructSelfTypeCaptureV04testdeF0yyF
func testSelfTypeCapture() {
_osLogTestHelper("Self type of a struct \(String(describing: Self.self))")
}
}
protocol TestProtocolSelfTypeCapture {
func testSelfTypeCapture()
}
extension TestProtocolSelfTypeCapture {
// CHECK-LABEL: @${{.*}}TestProtocolSelfTypeCapturePAAE04testdeF0yyF
func testSelfTypeCapture() {
_osLogTestHelper("Self type of a protocol \(String(describing: Self.self))")
}
}
// Test that SwiftUI's preview transformations work with the logging APIs.
// A function similar to the one used by SwiftUI preview to wrap string
// literals.
@_semantics("constant_evaluable")
@_transparent
public func __designTimeStringStub(
_ key: String,
fallback: OSLogMessage
) -> OSLogMessage {
fallback
}
// CHECK-LABEL: @${{.*}}testSwiftUIPreviewWrappingyy
func testSwiftUIPreviewWrapping() {
_osLogTestHelper(__designTimeStringStub("key", fallback: "percent: %"))
// CHECK: string_literal utf8 "percent: %%"
// CHECK-NOT: OSLogMessage
// CHECK-NOT: OSLogInterpolation
// CHECK-LABEL: end sil function '${{.*}}testSwiftUIPreviewWrappingyy
}
func functionTakingClosure(_ x: () -> Void) { }
func testWrappingWithinClosures(x: Int) {
functionTakingClosure {
_osLogTestHelper(
__designTimeStringStub(
"key",
fallback: "escaping of percent: %"))
// CHECK-LABEL: @${{.*}}testWrappingWithinClosures1xySi_tFyyXEfU_
// CHECK: string_literal utf8 "escaping of percent: %%"
// CHECK-NOT: OSLogMessage
// CHECK-NOT: OSLogInterpolation
// CHECK-LABEL: end sil function '${{.*}}testWrappingWithinClosures1xySi_tFyyXEfU_
}
}
func testAnimationSignpost(cond: Bool, x: Int, y: Float) {
_osSignpostAnimationBeginTestHelper("animation begins here %d", Int.min)
_osSignpostAnimationBeginTestHelper("a message without arguments")
_osSignpostAnimationBeginTestHelper("animation begins here %ld", x)
_osSignpostAnimationBeginTestHelper("animation begins here %ld", cond ? x : y)
_osSignpostAnimationBeginTestHelper("animation begins here %ld %f", x, y)
// CHECK-LABEL: @${{.*}}testAnimationSignpost4cond1x1yySb_SiSftF
// CHECK: string_literal utf8 "animation begins here %d isAnimation=YES"
// CHECK: string_literal utf8 "a message without arguments isAnimation=YES"
// CHECK: string_literal utf8 "animation begins here %ld isAnimation=YES"
// CHECK: string_literal utf8 "animation begins here %ld isAnimation=YES"
// CHECK: string_literal utf8 "animation begins here %ld %f isAnimation=YES"
}
|
apache-2.0
|
af3838b029fb1a02bf10db8bbbd9d1d0
| 55.717188 | 287 | 0.664784 | 3.455402 | false | true | false | false |
RussVanBert/Rc4
|
Swift_Rc4/Swift_Rc4/Rc4.swift
|
1
|
1616
|
import Foundation
class Rc4 {
func byteArr(_ str: String) -> [UInt8] {
var result = [UInt8]()
for strByte in str.utf8 {
result.append(strByte)
}
return result
}
// decrypt really just calls encrypt. Amazing right?
func decrypt(_ data: [UInt8], key: [UInt8]) -> [UInt8] {
return encrypt(data, key: key)
}
func encrypt(_ data: [UInt8], key: [UInt8]) -> [UInt8] {
let swappedArray = keyScheduler(key)
return cipherArray(data, swappedArr: swappedArray)
}
func keyScheduler(_ key: [UInt8]) -> [UInt8] {
let keySwap = initialKeyArrays(key)
var iS = keySwap.iS
let iK = keySwap.iK
var j = 0
for i in 0..<256 {
let swapValue: UInt8 = iS[i]
j = (j + Int(iS[i]) + Int(iK[i])) % 256
iS[i] = iS[j]
iS[j] = swapValue
}
return iS
}
func initialKeyArrays(_ keyArr: [UInt8]) -> (iS: [UInt8], iK: [UInt8]) {
var iS = [UInt8]()
var iK = [UInt8]()
let keyLength = keyArr.count
for i in 0..<256 {
iS.append(UInt8(i))
iK.append(keyArr[i % keyLength])
}
return (iS, iK)
}
func cipherArray(_ dataArr: [UInt8], swappedArr: [UInt8]) -> [UInt8] {
var iPos = 0
var jPos = 0
var cipher = dataArr
for cipherPos in 0..<dataArr.count {
iPos = (iPos + 1) % 256
let is_i = Int(swappedArr[iPos])
jPos = (jPos + is_i) % 256
let is_j = Int(swappedArr[jPos])
let swap = swappedArr[(is_i + is_j) % 256]
let ch = dataArr[cipherPos]
cipher[cipherPos] = ch ^ swap
}
return cipher
}
}
|
mit
|
bfff42eea1f8a92c4a75c56bbf9ebd8a
| 22.42029 | 74 | 0.54703 | 3.089866 | false | false | false | false |
alessandrostone/Neon
|
Demo/Neon/Neon/ImageContainerView.swift
|
1
|
1125
|
//
// ImageContainerView.swift
// Neon
//
// Created by Mike on 9/26/15.
// Copyright © 2015 Mike Amaral. All rights reserved.
//
import UIKit
class ImageContainerView: UIView {
let imageView : UIImageView = UIImageView()
let label : UILabel = UILabel()
convenience init() {
self.init(frame: CGRectZero)
self.backgroundColor = UIColor.whiteColor()
self.layer.cornerRadius = 4.0
self.layer.borderWidth = 1.0
self.layer.borderColor = UIColor(white: 0.68, alpha: 1.0).CGColor
self.clipsToBounds = true
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
self.addSubview(imageView)
label.textAlignment = .Center
label.textColor = UIColor.blackColor()
label.font = UIFont.boldSystemFontOfSize(15.0)
self.addSubview(label)
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.anchorAndFillEdge(.Top, xPad: 0, yPad: 0, otherSize: self.height() * 0.7)
label.alignAndFill(align: .UnderCentered, relativeTo: imageView, padding: 0)
}
}
|
mit
|
58e83e1eeaefee3899361b78ed85b9a9
| 27.1 | 91 | 0.653915 | 4.306513 | false | false | false | false |
furqanmk/github
|
microapps-testapplication/Github.swift
|
1
|
8354
|
//
// Github.swift
// microapps-testapplication
//
// Created by Furqan on 22/12/2015.
// Copyright © 2015 Furqan Khan. All rights reserved.
//
import UIKit
class Github {
static let languages = [
"JavaScript",
"Java",
"Python",
"CSS",
"PHP",
"Ruby",
"C++",
"C",
"Shell",
"CSharp",
"Objective-C",
"R",
"VimL",
"Go",
"Perl",
"CoffeeScript",
"TeX",
"Swift",
"Scala",
"Emacs Lisp",
"Haskell",
"Lua",
"Clojure",
"Matlab",
"Arduino",
"Makefile",
"Groovy",
"Puppet",
"Rust",
"PowerShell"
]
static func repositories (language: String, completion: ([Repository]) -> Void) {
let request = NSURLRequest.requestForRepositories(language)
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
guard let _ = error else {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
var repositories = [Repository]()
if let array = ((json as! NSDictionary)["items"]) as? [NSDictionary] {
for item in array {
let name = item["name"] as! String
let description = item["description"] as! String
let issuesUrl = item["issues_url"] as! String
let contributorsUrl = item["contributors_url"] as! String
let stargazers = item["stargazers_count"] as! Int
let language = item["language"] as! String
if let _owner = item["owner"] as? NSDictionary {
let username = _owner["login"] as! String
let avatarUrl = _owner["avatar_url"] as! String
let image = UIImage(data: NSData(contentsOfURL: NSURL(string: avatarUrl)!)!)
let owner = Owner(username: username, image: image!)
let repository = Repository(name: name, description: description, issuesUrl: issuesUrl, contributorsUrl: contributorsUrl, owner: owner, stargazers: stargazers, language: language)
repositories.append(repository)
}
}
completion(repositories)
} else { completion(repositories) }
} catch {
}
return
}
}).resume()
}
}
class Repository {
var name: String!,
description: String!,
issues: [Issue],
contributors: [Contributor],
issuesUrl: String,
contributorsUrl: String,
owner: Owner,
stargazers: Int,
language: String
init (name: String, description: String, issuesUrl: String, contributorsUrl: String, owner: Owner, stargazers: Int, language: String) {
self.name = name
self.description = description
self.issuesUrl = issuesUrl
self.contributorsUrl = contributorsUrl
self.owner = owner
self.stargazers = stargazers
self.language = language
self.issues = []
self.contributors = []
}
func addIssue (issue: Issue) { issues.append(issue) }
func addContributor (contributor: Contributor) { contributors.append(contributor) }
func newestIssues (count: Int, completion: ([Issue]) -> Void) {
let issuesUrlRequest = NSURLRequest.requestForIssues(issuesUrl, state: .Open)
NSURLSession.sharedSession().dataTaskWithRequest(issuesUrlRequest, completionHandler: { (data, response, error) -> Void in
guard let _ = error else {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
var issues = [Issue]()
if let array = json as? NSArray {
for item in array {
let title = item["title"] as! String
let state = (item["state"] as! String == "open") ? IssueState.Open: IssueState.Closed
let body = item["body"] as? String
let number = item["number"] as! Int
issues.append(Issue(state: state, title: title, body: body, number: number))
}
if issues.count > count { completion(Array(issues[0...2])) }
else { completion(issues) }
} else { }
} catch {
}
return
}
print("Error: \(error?.localizedDescription)", true)
}).resume()
}
func topContributors (count: Int, completion: ([Contributor]) -> Void) {
let issuesUrlRequest = NSURLRequest.requestForContributors(contributorsUrl)
NSURLSession.sharedSession().dataTaskWithRequest(issuesUrlRequest, completionHandler: { (data, response, error) -> Void in
guard let _ = error else {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
var contributors = [Contributor]()
if let array = json as? NSArray {
for item in array {
let username = item["login"] as! String
let contributions = item["contributions"] as! Int
let avatarUrl = item["avatar_url"] as! String
let image = UIImage(data: NSData(contentsOfURL: NSURL(string: avatarUrl)!)!)
contributors.append(Contributor(username: username, image: image!, contributions: contributions))
}
if contributors.count > count { completion(Array(contributors[0...2])) }
else { completion(self.contributors) }
} else { }
} catch {
}
return
}
print("Error: \(error?.localizedDescription)", true)
}).resume()
}
}
struct Issue {
var state: IssueState,
title: String,
body: String?,
number: Int
}
class Contributor: Owner {
var contributions: Int
init(username: String, image: UIImage, contributions: Int) {
self.contributions = contributions
super.init(username: username, image: image)
}
}
class Owner {
var username: String, image: UIImage
init(username: String, image: UIImage) {
self.username = username
self.image = image
}
}
enum IssueState {
case Open, Closed
}
extension NSURLRequest {
static func requestForRepositories(language: String) -> NSURLRequest {
let url = "https://api.github.com/search/repositories?q=language:\(language)&sort=stars&order=desc"
return NSURLRequest(URL: NSURL(string: url)!)
}
static func requestForIssues(issuesUrl: String, state: IssueState) -> NSURLRequest {
let range = issuesUrl.rangeOfString("{/number}")
var url = issuesUrl
url.removeRange(range!)
url += "?state=\(state == .Open ? "open" : "closed")&sort=created_at&order=desc"
return NSURLRequest(URL: NSURL(string: url)!)
}
static func requestForContributors (contributorsUrl: String) -> NSURLRequest {
let url = contributorsUrl + "?q=sort=contributions&order=asc"
return NSURLRequest(URL: NSURL(string: url)!)
}
}
|
mit
|
788bc288c51de95d58d195e3c8cfe962
| 35.475983 | 211 | 0.507243 | 5.313613 | false | false | false | false |
cuappdev/podcast-ios
|
old/Podcast/ContinueListeningCollectionViewCell.swift
|
1
|
4384
|
//
// ContinueListeningCollectionViewCell.swift
// Podcast
//
// Created by Natasha Armbrust on 3/29/18.
// Copyright © 2018 Cornell App Development. All rights reserved.
//
import UIKit
protocol ContinueListeningCollectionViewCellDelegate: class {
func dismissButtonPress(on cell: ContinueListeningCollectionViewCell)
}
class ContinueListeningCollectionViewCell: UICollectionViewCell {
var artworkImageView: ImageView!
var titleLabel: UILabel!
var descriptionLabel: UILabel!
var timeLeftLabel: UILabel!
var timeLeftView: UIView!
var dismissButton: Button!
let artworkImageViewSize: CGFloat = 108
let padding: CGFloat = 18
let smallPadding: CGFloat = 12
let smallestPadding: CGFloat = 6
let timeLeftViewHeight: CGFloat = 25
weak var delegate: ContinueListeningCollectionViewCellDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .offWhite
artworkImageView = ImageView()
artworkImageView.addCornerRadius(height: artworkImageViewSize)
addSubview(artworkImageView)
artworkImageView.snp.makeConstraints { make in
make.leading.equalToSuperview()
make.size.equalTo(artworkImageViewSize)
make.top.equalToSuperview()
}
titleLabel = UILabel()
titleLabel.font = ._16SemiboldFont()
titleLabel.numberOfLines = 2
titleLabel.textColor = .offBlack
addSubview(titleLabel)
titleLabel.snp.makeConstraints { make in
make.leading.equalTo(artworkImageView.snp.trailing).offset(smallPadding)
make.trailing.equalToSuperview().inset(padding + smallPadding)
make.top.equalTo(artworkImageView.snp.top)
}
descriptionLabel = UILabel()
descriptionLabel.font = ._12RegularFont()
descriptionLabel.textColor = .charcoalGrey
descriptionLabel.numberOfLines = 2
addSubview(descriptionLabel)
descriptionLabel.snp.makeConstraints { make in
make.leading.equalTo(titleLabel.snp.leading)
make.trailing.equalTo(titleLabel.snp.trailing)
make.top.equalTo(titleLabel.snp.bottom).offset(smallestPadding)
}
timeLeftView = UIView()
timeLeftView.backgroundColor = .slateGrey
timeLeftView.clipsToBounds = true
timeLeftView.layer.cornerRadius = 3
addSubview(timeLeftView)
timeLeftLabel = UILabel()
timeLeftLabel.font = ._12SemiboldFont()
timeLeftLabel.textAlignment = .center
timeLeftLabel.textColor = .offWhite
timeLeftView.addSubview(timeLeftLabel)
timeLeftView.snp.makeConstraints { make in
make.bottom.equalTo(artworkImageView.snp.bottom)
make.leading.equalTo(titleLabel.snp.leading)
make.height.equalTo(timeLeftViewHeight)
}
timeLeftLabel.snp.makeConstraints { make in
make.centerY.equalToSuperview()
make.leading.trailing.equalToSuperview().inset(smallestPadding)
}
dismissButton = Button()
dismissButton.setImage(#imageLiteral(resourceName: "failure_icon"), for: .normal)
dismissButton.imageEdgeInsets = UIEdgeInsets.zero
dismissButton.addTarget(self, action: #selector(dismissButtonPress), for: .touchUpInside)
addSubview(dismissButton)
dismissButton.snp.makeConstraints { make in
make.top.equalToSuperview()
make.trailing.equalToSuperview().inset(smallPadding)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(for episode: Episode) {
artworkImageView.setImageAsynchronouslyWithDefaultImage(url: episode.largeArtworkImageURL)
titleLabel.text = episode.title
descriptionLabel.text = episode.getDateTimeLabelString(includeSeriesTitle: true)
if let duration = Double(episode.duration), episode.isDurationWritten {
let minsLeft = Int((duration - duration * episode.currentProgress) / 60)
timeLeftLabel.text = "\(minsLeft) min left"
timeLeftView.isHidden = false
} else {
timeLeftView.isHidden = true
}
}
@objc func dismissButtonPress() {
delegate?.dismissButtonPress(on: self)
}
}
|
mit
|
e75c95dfcd79f55f0937de93c71c4ff7
| 34.346774 | 98 | 0.682181 | 5.261705 | false | false | false | false |
cristianames92/PortalView
|
Sources/ZipList.swift
|
1
|
2171
|
//
// ZipList.swift
// PortalView
//
// Created by Guido Marucci Blas on 4/6/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import Foundation
public struct ZipList<Element>: Collection, CustomDebugStringConvertible {
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return count
}
public var count: Int {
return left.count + right.count + 1
}
public var centerIndex: Int {
return left.count
}
public var debugDescription: String {
return "ZipList(\n\tleft: \(left)\n\tcenter: \(center)\n\tright: \(right))"
}
fileprivate let left: [Element]
fileprivate let center: Element
fileprivate let right: [Element]
public init(element: Element) {
self.init(left: [], center: element, right: [])
}
public init(left: [Element], center: Element, right: [Element]) {
self.left = left
self.center = center
self.right = right
}
public subscript(index: Int) -> Element {
precondition(index >= 0 && index < count, "Index of out bounds")
if index < left.count {
return left[index]
} else if index == left.count {
return center
} else {
return right[index - left.count - 1]
}
}
public func index(after i: Int) -> Int {
return i + 1
}
public func shiftLeft() -> ZipList<Element>? {
guard let newCenter = right.first else { return .none }
return ZipList(left: left + [center], center: newCenter, right: Array(right.dropFirst()))
}
public func shiftRight() -> ZipList<Element>? {
guard let newCenter = left.last else { return .none }
return ZipList(left: Array(left.dropLast()), center: newCenter, right: [center] + right)
}
}
extension ZipList {
public func map<NewElement>(_ transform: @escaping (Element) -> NewElement) -> ZipList<NewElement> {
return ZipList<NewElement>(left: left.map(transform), center: transform(center), right: right.map(transform))
}
}
|
mit
|
32b13286c36187a8848767f9059ef3b5
| 25.790123 | 117 | 0.588018 | 4.157088 | false | false | false | false |
richardpiazza/SOSwift
|
Sources/SOSwift/AccessibilityControl.swift
|
1
|
926
|
import Foundation
/// Identifies one or more input methods that allow access to all of the application functionality.
public enum AccessibilityControl: String, CaseIterable, Codable {
case fullKeyboardControl = "fullKeyboardControl"
case fullMouseControl = "fullMouseControl"
case fullSwitchControl = "fullSwitchControl"
case fullTouchControl = "fullTouchControl"
case fullVideoControl = "fullVideoControl"
case fullVoiceControl = "fullVoiceControl"
public var displayValue: String {
switch self {
case .fullKeyboardControl: return "Full Keyboard Control"
case .fullMouseControl: return "Full Mouse Control"
case .fullSwitchControl: return "Full Switch Control"
case .fullTouchControl: return "Full Touch Control"
case .fullVideoControl: return "Full Video Control"
case .fullVoiceControl: return "Full Voice Control"
}
}
}
|
mit
|
2a63ab2b9d3d98176fc2921e09ebaef8
| 41.090909 | 99 | 0.725702 | 4.822917 | false | false | false | false |
PureSwift/DBus
|
Tests/DBusTests/SignatureTests.swift
|
1
|
3514
|
//
// SignatureTests.swift
// DBusTests
//
// Created by Alsey Coleman Miller on 10/22/18.
//
import Foundation
import XCTest
@testable import DBus
final class SignatureTests: XCTestCase {
static let allTests: [(String, (SignatureTests) -> () -> Void)] = [
("testInvalid", testInvalid),
("testValid", testValid)
]
func testInvalid() {
let strings = [
"aa",
"(ii",
"ii)",
//"()",
"a",
"test",
"(ii)(ii) (ii)",
"{si}",
"a{i}",
"v{i}",
"a{s}",
"a{(i)a}",
"a{vs}"
]
for string in strings {
XCTAssertNil(DBusSignature(rawValue: string), "\(string) should be invalid")
XCTAssertThrowsError(try DBusSignature.validate(string))
do { try DBusSignature.validate(string) }
catch let error as DBusError {
XCTAssertEqual(error.name, .invalidSignature)
print("\"\(string)\" is invalid: \(error.message)"); return
}
catch { XCTFail("Invalid error \(error)"); return }
XCTFail("Error expected for \(string)")
}
}
func testValid() {
let values: [(String, DBusSignature)] = [
("", []),
("s", [.string]),
("v", [.variant]),
("i", [.int32]),
("ii", [.int32, .int32]),
("aiai", [.array(.int32), .array(.int32)]),
("(i)", [.struct([.int32])]),
("(ii)", [.struct([.int32, .int32])]),
("(aii)", [.struct([.array(.int32), .int32])]),
("ai(i)", [.array(.int32), .struct([.int32])]),
("a(i)", [.array(.struct([.int32]))]),
("(ii)(ii)", [.struct([.int32, .int32]), .struct([.int32, .int32])]),
("(ii)(ii)(ii)", [.struct([.int32, .int32]), .struct([.int32, .int32]), .struct([.int32, .int32])]),
("a{si}", [.dictionary(DBusSignature.DictionaryType(key: .string, value: .int32)!)]),
("a{is}", [.dictionary(DBusSignature.DictionaryType(key: .int32, value: .string)!)]),
("a{s(ai)}", [.dictionary(DBusSignature.DictionaryType(key: .string, value: .struct([.array(.int32)]))!)]),
("a{sai}", [.dictionary(DBusSignature.DictionaryType(key: .string, value: .array(.int32))!)]),
("a{sv}", [.dictionary(DBusSignature.DictionaryType(key: .string, value: .variant)!)])
]
for (string, expectedSignature) in values {
XCTAssertNoThrow(try DBusSignature.validate(string))
guard let signature = DBusSignature(rawValue: string)
else { XCTFail("Could not parse string \(string)"); continue }
XCTAssertEqual(signature, expectedSignature)
XCTAssertEqual(signature.rawValue, string)
XCTAssertEqual(signature.string, string)
XCTAssertEqual(signature.elements, expectedSignature.elements)
XCTAssertEqual(Array(signature), Array(expectedSignature))
var mutable = signature
mutable.append(.double)
XCTAssertNil(mutable.string)
XCTAssertNotEqual(mutable, signature)
XCTAssertNotEqual(mutable.rawValue, signature.rawValue)
XCTAssertNotEqual(mutable.elements, signature.elements)
}
}
}
|
mit
|
17f74e83bae594d603a6ffe9913688b5
| 35.989474 | 119 | 0.507684 | 4.465057 | false | true | false | false |
dpricha89/DrApp
|
Source/TableCells/TitleCell.swift
|
1
|
1022
|
//
// TitleCell.swift
// Venga
//
// Created by David Richards on 7/22/17.
// Copyright © 2017 David Richards. All rights reserved.
//
import UIKit
open class TitleCell: UITableViewCell {
let titleLabel = UILabel()
open override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
open override func layoutSubviews() {
super.layoutSubviews()
self.backgroundColor = .clear
self.selectionStyle = .none
self.titleLabel.textColor = LibConst.sectionTitleColor
self.titleLabel.font = .systemFont(ofSize: 25)
self.contentView.addSubview(self.titleLabel)
titleLabel.snp.makeConstraints { (make) -> Void in
make.height.equalTo(LibConst.largeLabelhieght)
make.left.equalTo(self.contentView).offset(LibConst.smallLeftOffset)
make.bottom.equalTo(self.contentView)
}
}
}
|
apache-2.0
|
37df0abaf4c72606eff9fb83f44c1726
| 28.171429 | 80 | 0.65524 | 4.458515 | false | false | false | false |
samnm/material-components-ios
|
catalog/MDCDragons/MDCDragonsController.swift
|
1
|
13858
|
/*
Copyright 2015-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import CatalogByConvention
import MaterialComponents.MaterialFlexibleHeader
import MaterialComponents.MaterialLibraryInfo
import MaterialComponents.MaterialShadowElevations
import MaterialComponents.MaterialShadowLayer
import MaterialComponents.MaterialThemes
import MaterialComponents.MaterialTypography
import UIKit
class MDCDragonsController: UIViewController,
UITableViewDelegate,
UITableViewDataSource,
UISearchBarDelegate,
UIGestureRecognizerDelegate {
fileprivate struct Constants {
static let headerScrollThreshold: CGFloat = 50
static let headerViewMaxHeight: CGFloat = 113
static let headerViewMinHeight: CGFloat = 53
static let bgColor = UIColor(white: 0.97, alpha: 1)
static let headerColor = UIColor(red: 0.298, green: 0.686, blue: 0.314, alpha: 1.0)
}
fileprivate var cellsBySection: [[DragonCell]]
fileprivate var searched: [DragonCell]!
fileprivate var results: [DragonCell]!
fileprivate var tableView: UITableView!
fileprivate var isSearchActive = false
fileprivate lazy var headerViewController = MDCFlexibleHeaderViewController()
var headerView: HeaderView!
init(node: CBCNode) {
let filteredPresentable = node.children.filter { return $0.isPresentable() }
let filteredDragons = Set(node.children).subtracting(filteredPresentable)
cellsBySection = [filteredDragons.map { DragonCell(node: $0) },
filteredPresentable.map { DragonCell(node: $0) }]
cellsBySection = cellsBySection.map { $0.sorted() { $0.node.title < $1.node.title } }
super.init(nibName: nil, bundle: nil)
results = getLeafNodes(node: node)
searched = results
}
func getLeafNodes(node: CBCNode) -> [DragonCell] {
if node.children.count == 0 {
return [DragonCell(node: node)]
}
var cells = [DragonCell]()
for child in node.children {
cells += getLeafNodes(node: child)
}
return cells
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Material Dragons"
addChildViewController(headerViewController)
headerViewController.headerView.minMaxHeightIncludesSafeArea = false
headerViewController.headerView.maximumHeight = Constants.headerViewMaxHeight
headerViewController.headerView.minimumHeight = Constants.headerViewMinHeight
tableView = UITableView(frame: self.view.bounds, style: .grouped)
tableView.register(MDCDragonsTableViewCell.self,
forCellReuseIdentifier: "MDCDragonsTableViewCell")
tableView.backgroundColor = Constants.bgColor
tableView.delegate = self
tableView.dataSource = self
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
view.backgroundColor = Constants.bgColor
#if swift(>=3.2)
if #available(iOS 11, *) {
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([tableView.leftAnchor.constraint(equalTo: guide.leftAnchor),
tableView.rightAnchor.constraint(equalTo: guide.rightAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: guide.bottomAnchor)])
} else {
preiOS11Constraints()
}
#else
preiOS11Constraints()
#endif
setupHeaderView()
let tapgesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
tapgesture.delegate = self
view.addGestureRecognizer(tapgesture)
#if swift(>=3.2)
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .always
}
#endif
}
func preiOS11Constraints() {
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|",
options: [],
metrics: nil,
views: ["view": tableView]));
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|",
options: [],
metrics: nil,
views: ["view": tableView]));
}
func setupHeaderView() {
headerView = HeaderView(frame: headerViewController.headerView.bounds)
headerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
headerView.title.text = title!
headerView.searchBar.delegate = self
headerViewController.headerView.addSubview(headerView)
headerViewController.headerView.forwardTouchEvents(for: headerView)
headerViewController.headerView.backgroundColor = Constants.headerColor
headerViewController.headerView.trackingScrollView = tableView
view.addSubview(headerViewController.view)
headerViewController.didMove(toParentViewController: self)
}
func adjustLogoForScrollView(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
let inset = scrollView.contentInset.top
let relativeOffset = inset + offset
headerView.imageView.alpha = 1 - (relativeOffset / Constants.headerScrollThreshold)
headerView.title.alpha = 1 - (relativeOffset / Constants.headerScrollThreshold)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override var childViewControllerForStatusBarStyle: UIViewController? {
return headerViewController
}
override var childViewControllerForStatusBarHidden: UIViewController? {
return headerViewController
}
// MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return isSearchActive ? 1 : 2
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return isSearchActive ? "Results" : (section == 0 ? "Dragons" : "Catalog")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return isSearchActive ? searched.count : cellsBySection[section].count
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell =
tableView.dequeueReusableCell(withIdentifier: "MDCDragonsTableViewCell",
for: indexPath) as? MDCDragonsTableViewCell else {
return UITableViewCell()
}
cell.backgroundColor = .white
let nodeData = isSearchActive ? searched[indexPath.item] : cellsBySection[indexPath.section][indexPath.row]
let componentName = nodeData.node.title
cell.textLabel?.text = componentName
let node = nodeData.node
if !node.isExample() && !isSearchActive {
if nodeData.expanded {
cell.accessoryView = cell.expandedButton
} else {
cell.accessoryView = cell.defaultButton
}
} else {
cell.accessoryView = nil
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let cell = tableView.cellForRow(at: indexPath) as? MDCDragonsTableViewCell else {
return
}
let nodeData = isSearchActive ? searched[indexPath.item] : cellsBySection[indexPath.section][indexPath.row]
if nodeData.node.isExample() || isSearchActive {
setupTransition(nodeData: nodeData)
} else if !isSearchActive {
self.tableView.beginUpdates()
if nodeData.expanded {
collapseCells(at: indexPath)
cell.accessoryView = cell.defaultButton
} else {
expandCells(at: indexPath)
cell.accessoryView = cell.expandedButton
}
self.tableView.endUpdates()
nodeData.expanded = !nodeData.expanded
}
}
func setupTransition(nodeData: DragonCell) {
var vc = nodeData.node.createExampleViewController()
if !vc.responds(to: NSSelectorFromString("catalogShouldHideNavigation")) {
let container = MDCAppBarContainerViewController(contentViewController: vc)
container.appBar.headerViewController.headerView.backgroundColor = headerViewController.headerView.backgroundColor
container.appBar.navigationBar.tintColor = .white
container.appBar.navigationBar.titleTextAttributes =
[ NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont.systemFont(ofSize: 16) ]
vc.title = nodeData.node.title
let headerView = container.appBar.headerViewController.headerView
if let collectionVC = vc as? MDCCollectionViewController {
headerView.trackingScrollView = collectionVC.collectionView
} else if let scrollView = vc.view as? UIScrollView {
headerView.trackingScrollView = scrollView
} else {
var contentFrame = container.contentViewController.view.frame
let headerSize = headerView.sizeThatFits(container.contentViewController.view.frame.size)
contentFrame.origin.y = headerSize.height
contentFrame.size.height = self.view.bounds.height - headerSize.height
container.contentViewController.view.frame = contentFrame
}
vc = container
}
self.navigationController?.pushViewController(vc, animated: true)
}
}
// UIScrollViewDelegate
extension MDCDragonsController {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == headerViewController.headerView.trackingScrollView {
self.headerViewController.headerView.trackingScrollDidScroll()
self.adjustLogoForScrollView(scrollView)
}
}
func scrollViewDidEndDragging( _ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let headerView = headerViewController.headerView
if scrollView == headerView.trackingScrollView {
headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate)
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == headerViewController.headerView.trackingScrollView {
self.headerViewController.headerView.trackingScrollDidEndDecelerating()
}
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let headerView = headerViewController.headerView
if scrollView == headerView.trackingScrollView {
headerView.trackingScrollWillEndDragging(withVelocity: velocity,
targetContentOffset: targetContentOffset)
}
}
}
// UISearchBarDelegate
extension MDCDragonsController {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
isSearchActive = false
searched = results
} else {
isSearchActive = true
searched = results.filter {
return $0.node.title.range(of: searchText, options: .caseInsensitive) != nil
}
}
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searched = results
tableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.endEditing(true)
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
isSearchActive = true
tableView.reloadData()
}
@objc func dismissKeyboard() {
self.view.endEditing(true)
isSearchActive = false
tableView.reloadData()
}
@objc(gestureRecognizer:shouldReceiveTouch:)
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer is UITapGestureRecognizer {
let location = touch.location(in: tableView)
return (tableView.indexPathForRow(at: location) == nil)
}
return true
}
}
extension MDCDragonsController {
func collapseCells(at indexPath: IndexPath) {
let upperCount = cellsBySection[indexPath.section][indexPath.row].node.children.count
let indexPaths = (indexPath.row+1..<indexPath.row+1+upperCount).map {
IndexPath(row: $0, section: indexPath.section)
}
tableView.deleteRows(at: indexPaths, with: .automatic)
cellsBySection[indexPath.section].removeSubrange((indexPath.row+1..<indexPath.row+1+upperCount))
}
func expandCells(at indexPath: IndexPath) {
let nodeChildren = cellsBySection[indexPath.section][indexPath.row].node.children
let upperCount = nodeChildren.count
let indexPaths = (indexPath.row+1..<indexPath.row+1+upperCount).map {
IndexPath(row: $0, section: indexPath.section)
}
tableView.insertRows(at: indexPaths, with: .automatic)
cellsBySection[indexPath.section].insert(contentsOf: nodeChildren.map { DragonCell(node: $0) },
at: indexPath.row+1)
}
}
|
apache-2.0
|
9df3e96b6bbe852724146a79599a04c4
| 37.387812 | 120 | 0.696204 | 5.178625 | false | false | false | false |
jtaxen/FindShelter
|
Pods/FBAnnotationClusteringSwift/Pod/Classes/FBQuadTree.swift
|
1
|
2943
|
//
// FBQuadTree.swift
// FBAnnotationClusteringSwift
//
// Created by Robert Chen on 4/2/15.
// Copyright (c) 2015 Robert Chen. All rights reserved.
//
import Foundation
import MapKit
open class FBQuadTree : NSObject {
var rootNode:FBQuadTreeNode? = nil
let nodeCapacity = 8
override init (){
super.init()
rootNode = FBQuadTreeNode(boundingBox:FBQuadTreeNode.FBBoundingBoxForMapRect(MKMapRectWorld))
}
func insertAnnotation(_ annotation:MKAnnotation) -> Bool {
return insertAnnotation(annotation, toNode:rootNode!)
}
func insertAnnotation(_ annotation:MKAnnotation, toNode node:FBQuadTreeNode) -> Bool {
if !FBQuadTreeNode.FBBoundingBoxContainsCoordinate(node.boundingBox!, coordinate: annotation.coordinate) {
return false
}
if node.count < nodeCapacity {
node.annotations.append(annotation)
node.count += 1
return true
}
if node.isLeaf() {
node.subdivide()
}
if insertAnnotation(annotation, toNode:node.northEast!) {
return true
}
if insertAnnotation(annotation, toNode:node.northWest!) {
return true
}
if insertAnnotation(annotation, toNode:node.southEast!) {
return true
}
if insertAnnotation(annotation, toNode:node.southWest!) {
return true
}
return false
}
func enumerateAnnotationsInBox(_ box:FBBoundingBox, callback: (MKAnnotation) -> Void){
enumerateAnnotationsInBox(box, withNode:rootNode!, callback: callback)
}
func enumerateAnnotationsUsingBlock(_ callback: (MKAnnotation) -> Void){
enumerateAnnotationsInBox(FBQuadTreeNode.FBBoundingBoxForMapRect(MKMapRectWorld), withNode:rootNode!, callback:callback)
}
func enumerateAnnotationsInBox(_ box:FBBoundingBox, withNode node:FBQuadTreeNode, callback: (MKAnnotation) -> Void){
if (!FBQuadTreeNode.FBBoundingBoxIntersectsBoundingBox(node.boundingBox!, box2: box)) {
return;
}
let tempArray = node.annotations
for annotation in tempArray {
if (FBQuadTreeNode.FBBoundingBoxContainsCoordinate(box, coordinate: annotation.coordinate)) {
callback(annotation);
}
}
if node.isLeaf() {
return
}
enumerateAnnotationsInBox(box, withNode: node.northEast!, callback: callback)
enumerateAnnotationsInBox(box, withNode: node.northWest!, callback: callback)
enumerateAnnotationsInBox(box, withNode: node.southEast!, callback: callback)
enumerateAnnotationsInBox(box, withNode: node.southWest!, callback: callback)
}
}
|
mit
|
8b50329e61df86424b2ba9eb23d28659
| 29.030612 | 128 | 0.615019 | 4.979695 | false | false | false | false |
king129/SJWeatherServer
|
Sources/App/Utility/StringUtility.swift
|
1
|
1176
|
//
// StringUtility.swift
// SJWeatherServer
//
// Created by king on 16/10/7.
//
//
import Foundation
import Vapor
import Hash
class StringUtility {
static func isEmpty(_ param: String?) -> Bool {
if let string = param {
return string.isEmpty
} else {
return true
}
}
static func convertToString(param: Float) -> String {
return String(stringInterpolationSegment: param)
}
static func convertToString(param: Double) -> String {
return String(stringInterpolationSegment: param)
}
static func convertToString(param: Int) -> String {
return String(param)
}
static func generateSignInToken(userID: Int) -> String {
let timestamp = Date().timeIntervalSince1970
let tokenFormat = "\(userID)" + "_" + "\(timestamp)"
do {
let byes = try tokenFormat.makeBytes()
let result = try Hash.make(.sha512, byes)
print("Hash: \(result.base64String)")
return result.base64String
} catch let error {
print(error)
}
return ""
}
}
|
mit
|
564f5ced0b6e49687801b123dd2b341c
| 22.52 | 60 | 0.566327 | 4.59375 | false | false | false | false |
wistia/WistiaKit
|
Pod/Classes/Core/public/model/WistiaMediaEmbedOptions.swift
|
1
|
14969
|
//
// WistiaMediaEmbedOptions.swift
// WistiaKit
//
// Created by Daniel Spinosa on 4/13/16.
// Copyright © 2016 Wistia, Inc. All rights reserved.
//
import Foundation
/**
Most player customizations are communicated through the API in a hash called
`embed_options`. These are stored as a `WistiaMediaEmbedOptions` on the
`WistiaMedia` to which they apply.
Customizations may be visualized by using the `WistiaPlayerViewController` and
accompanying xib for display. If you are using the `WistiaPlayer`, customizations
will not have any effect.
- Note: Wistia customizations not currently supported:
- Turnstyle
- Call To Action & Annotation Links
- Social Bar (replaced with standard iOS action button)
*/
public struct WistiaMediaEmbedOptions {
/// Initialize using default values
public init(){
}
/// Tint for controls (default: #7b796a)
public var playerColor: UIColor = UIColor(red: 0.482, green: 0.475, blue: 0.4157, alpha: 1)
/// Overlay large play button on poster view before playback has started (default: true)
public var bigPlayButton: Bool = true
/// Show play/pause button on playbar (default: true)
public var smallPlayButton: Bool = true
/// Show the scrubber (default: true)
public var playbar: Bool = true
/// Show the fullscreen button on playbar (default: true)
public var fullscreenButton: Bool = true
/// Show the playbar on poster view before playback has started (default: true)
public var controlsVisibleOnLoad: Bool = true
/// Automatically play the video once it has loaded (default: false)
public var autoplay: Bool = false
/// What do do when the video ends (default: PauseOnLastFrame) as a String
public var endVideoBehaviorString: String = "pause" {
didSet {
self.endVideoBehavior = WistiaEndVideoBehavior.fromString(self.endVideoBehaviorString)
}
}
/// What do do when the video ends (default: PauseOnLastFrame) as a String
public var endVideoBehavior: WistiaEndVideoBehavior = .pauseOnLastFrame {
didSet {
self.endVideoBehaviorString = endVideoBehavior.description()
}
}
/// Image to show for poster before playback (default: nil - the first frame of video is shown)
public var stillURL: URL? = nil
/// Show the standard iOS action button (similar to Wistia Social Bar on web) (default: false)
public var actionButton: Bool = false
/// The link to use when sharing
public var actionShareURLString: String? = nil
/// The copy to use when sharing
public var actionShareTitle: String? = nil
/// Are captions available and enabled for this video (default: false)
public var captionsAvailable: Bool = false
/// Show captions by default (default: false)
public var captionsOnByDefault: Bool = false
/// A password protected video will have `lockedByPassword = true`.
/// You must provide the password as a query parameter (ie. password=XXX) to get asset info from the API.
/// A value of false indicates the video is either not password protected, or the API request included the correct password.
public var lockedByPassword: Bool = false
/// A message to use when prompting the user for the password.
public var passwordChallenge: String? = nil
/**
Enumeration of options of what should happen automatically when a video reaches the end.
- `PauseOnLastFrame` : Continue to diplay the last frame, remain paused (deafult).
- `ResetToTimeZero` : Return to the start of the video, remain paused.
- `LoopVideo` : Return to the start of the video and resume playback there.
*/
public enum WistiaEndVideoBehavior {
/// Continue to diplay the last frame, remain paused (deafult).
case pauseOnLastFrame
/// Return to the start of the video, remain paused.
case resetToTimeZero
/// Return to the start of the video and resume playback there.
case loopVideo
static func fromString(_ behavior:String) -> WistiaEndVideoBehavior {
switch behavior {
case "default":
fallthrough
case "pause":
return .pauseOnLastFrame
case "reset":
return .resetToTimeZero
case "loop":
return .loopVideo
default:
return .pauseOnLastFrame
}
}
func description() -> String {
switch self {
case .pauseOnLastFrame:
return "pause"
case .loopVideo:
return "loop"
case .resetToTimeZero:
return "reset"
}
}
}
}
// As of Swift 3.0, the default member-wise initializer for Structs is private if any properties of the struct
// private, internal if they are all public. There is no way to make this initilizer public. So we must
// explicitly create one.
// See https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html#//apple_ref/doc/uid/TP40014097-CH41-ID3
public extension WistiaMediaEmbedOptions {
/// Initializes a WistiaMediaEmbedOptions, used to customize the look and behavior of your
/// video across all platforms (web, WistiaKit, etc).
///
/// Any parameter left nil will use the default.
///
/// - Parameters:
/// - playerColor: Tint for controls (default: #7b796a)
/// - bigPlayButton: Overlay large play button on poster view before playback has started (default: true)
/// - smallPlayButton: Show play/pause button on playbar (default: true)
/// - playbar: Show the scrubber (default: true)
/// - fullscreenButton: Show the fullscreen button on playbar (default: true)
/// - controlsVisibleOnLoad: Show the playbar on poster view before playback has started (default: true)
/// - autoplay: Automatically play the video once it has loaded (default: false)
/// - endVideoBehavior: What do do when the video ends (default: PauseOnLastFrame) as a String
/// - stillURL: Image to show for poster before playback (default: nil - the first frame of video is shown)
/// - actionButton: Show the standard iOS action button (similar to Wistia Social Bar on web) (default: false)
/// - actionShareURLString: The link to use when sharing
/// - actionShareTitle: The copy to use when sharing
/// - captionsAvailable: Are captions available and enabled for this video (default: false)
/// - captionsOnByDefault: Show captions by default (default: false)
public init(playerColor: UIColor?, bigPlayButton: Bool?, smallPlayButton: Bool?, playbar: Bool?, fullscreenButton: Bool?, controlsVisibleOnLoad: Bool?, autoplay: Bool?, endVideoBehavior: WistiaMediaEmbedOptions.WistiaEndVideoBehavior?, stillURL: URL?, actionButton: Bool?, actionShareURLString: String?, actionShareTitle: String?, captionsAvailable: Bool?, captionsOnByDefault: Bool?) {
if let pc = playerColor { self.playerColor = pc }
if let bpb = bigPlayButton { self.bigPlayButton = bpb }
if let spb = smallPlayButton { self.smallPlayButton = spb }
if let pb = playbar { self.playbar = pb }
if let fsb = fullscreenButton { self.fullscreenButton = fsb }
if let cv = controlsVisibleOnLoad { self.controlsVisibleOnLoad = cv }
if let ap = autoplay { self.autoplay = ap }
if let ev = endVideoBehavior { self.endVideoBehavior = ev }
if let su = stillURL { self.stillURL = su }
if let ab = actionButton { self.actionButton = ab }
if let asu = actionShareURLString { self.actionShareURLString = asu }
if let ast = actionShareTitle { self.actionShareTitle = ast }
if let ca = captionsAvailable { self.captionsAvailable = ca }
if let co = captionsOnByDefault { self.captionsOnByDefault = co }
}
}
extension WistiaMediaEmbedOptions: WistiaJSONParsable {
/// Initialize a WistiaMediaEmbedOptions from the provided JSON hash.
///
/// - Note: Prints error message to console on parsing issue.
///
/// - parameter dictionary: JSON hash representing the WistiaMediaEmbedOptions.
///
/// - returns: Initialized WistiaMediaEmbedOptions if parsing is successful.
init?(from dictionary: [String: Any]?) {
guard dictionary != nil else { return nil }
let parser = Parser(dictionary: dictionary)
do {
playerColor = parser.fetchOptional("playerColor", default: UIColor(red: 0.482, green: 0.475, blue: 0.4157, alpha: 1)) { UIColor.wk_from(hexString: $0) }
bigPlayButton = parser.fetchOptional("playButton", default: true) { (s: NSString) -> Bool in s.boolValue }
smallPlayButton = parser.fetchOptional("smallPlayButton", default: true) { (s: NSString) -> Bool in s.boolValue }
playbar = parser.fetchOptional("playbar", default: true) { (s: NSString) -> Bool in s.boolValue }
fullscreenButton = parser.fetchOptional("fullscreenButton", default: true) { (s: NSString) -> Bool in s.boolValue }
controlsVisibleOnLoad = parser.fetchOptional("controlsVisibleOnLoad", default: true) { (s: NSString) -> Bool in s.boolValue }
autoplay = parser.fetchOptional("autoPlay", default: false) { (s: NSString) -> Bool in s.boolValue }
endVideoBehaviorString = try parser.fetchOptional("endVideoBehavior", default: "pause")
stillURL = parser.fetchOptional("stillUrl") { URL(string: $0) }
if let pluginParser = parser.fetchOptional("plugin", transformation: { (dict: [String: Any]) -> Parser? in
Parser(dictionary: dict)
}) {
// share is the new stuff, preferred over socialbar-v1
if let shareParser = pluginParser.fetchOptional("share", transformation: { (dict: [String: Any]) -> Parser? in
Parser(dictionary: dict)
}) {
// presence of this hash means sharing is on unless it's explcity set to off
actionButton = shareParser.fetchOptional("on", default: true) { (s: NSString) -> Bool in s.boolValue }
actionShareURLString = try shareParser.fetchOptional("pageUrl")
actionShareTitle = try shareParser.fetchOptional("pageTitle")
} else if let socialBarV1Parser = pluginParser.fetchOptional("share", transformation: { (dict: [String: Any]) -> Parser? in
Parser(dictionary: dict)
}) {
// presence of this hash means sharing is on unless it's explcity set to off
actionButton = socialBarV1Parser.fetchOptional("on", default: true) { (s: NSString) -> Bool in s.boolValue }
actionShareURLString = try socialBarV1Parser.fetchOptional("pageUrl")
actionShareTitle = try socialBarV1Parser.fetchOptional("pageTitle")
}
if let captionsParser = pluginParser.fetchOptional("captions-v1", transformation: { (dict: [String: Any]) -> Parser? in
Parser(dictionary: dict)
}) {
// presence of this hash means captions are available unless stated otherwise
captionsAvailable = captionsParser.fetchOptional("on", default: true) { (s: NSString) -> Bool in s.boolValue }
captionsOnByDefault = captionsAvailable && captionsParser.fetchOptional("onByDefault", default: false) { (s: NSString) -> Bool in s.boolValue }
}
// The `embedOptions` also have a `passwordProtectedVideo` key (ie. not within the `plugin` dictionary),
// but `embedOptions.passwordProtectedVideo.on` does not tell us if the request was made with the correct password or not.
// Whereas `embedOptions.plugins.passwordProtectedVideo.on` does provide this informtion.
if let passwordParser = pluginParser.fetchOptional("passwordProtectedVideo", transformation: { (dict: [String: Any]) -> Parser? in
Parser(dictionary: dict)
}) {
// when `on` is set to true, the Media is password protected and it was not requested with the correct password
// when `on` is set to false, the Media is password protected and it was requested with the correct password.
// when the passwordProtectedVideo dictionary does not exist, the video is not password protected
lockedByPassword = passwordParser.fetchOptional("on", default: false) { (s: NSString) -> Bool in s.boolValue }
passwordChallenge = try passwordParser.fetchOptional("challenge")
}
}
} catch let error {
print(error)
return nil
}
}
internal func toJson() -> [String: Any] {
var json = [String: Any]()
json["playerColor"] = playerColor.wk_toHexString()
json["playButton"] = bigPlayButton
json["smallPlayButton"] = smallPlayButton
json["playbar"] = playbar
json["fullscreenButton"] = fullscreenButton
json["controlsVisibleOnLoad"] = controlsVisibleOnLoad
json["autoPlay"] = autoplay
json["endVideoBehavior"] = endVideoBehavior.description()
json["stillUrl"] = stillURL?.description
var share = [String: Any]()
share["on"] = actionButton
share["pageUrl"] = actionShareURLString
share["pageTitle"] = actionShareTitle
json["share"] = share
var captions = [String: Any]()
captions["on"] = captionsAvailable
captions["onByDefault"] = captionsOnByDefault
json["captions-v1"] = captions
return json
}
}
//MARK: - WistiaMediaEmbedOptions Equality
extension WistiaMediaEmbedOptions: Equatable { }
/**
Compare two `WistiaMediaEmbedOptions`s for equality.
- Returns: `True` iff each customization option is equal.
*/
public func ==(lhs: WistiaMediaEmbedOptions, rhs: WistiaMediaEmbedOptions) -> Bool {
return lhs.playerColor == rhs.playerColor &&
lhs.bigPlayButton == rhs.bigPlayButton &&
lhs.smallPlayButton == rhs.smallPlayButton &&
lhs.playbar == rhs.playbar &&
lhs.fullscreenButton == rhs.fullscreenButton &&
lhs.controlsVisibleOnLoad == rhs.controlsVisibleOnLoad &&
lhs.autoplay == rhs.autoplay &&
lhs.endVideoBehavior == rhs.endVideoBehavior &&
lhs.stillURL == rhs.stillURL &&
lhs.actionButton == rhs.actionButton &&
lhs.actionShareURLString == rhs.actionShareURLString &&
lhs.actionShareTitle == rhs.actionShareTitle &&
lhs.captionsAvailable == rhs.captionsAvailable &&
lhs.captionsOnByDefault == rhs.captionsOnByDefault
}
|
mit
|
79df3d27c00a1056edf5b38ef0be9de0
| 46.821086 | 390 | 0.654997 | 4.545399 | false | false | false | false |
CPRTeam/CCIP-iOS
|
Pods/FontAwesome.swift/FontAwesome/Enum.swift
|
1
|
224349
|
// Enum.swift
//
// Copyright (c) 2014-present FontAwesome.swift contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// DO NOT EDIT! This file is auto-generated. To regenerate it, update
// Font-Awesome submodule and run `./codegen.swift`.
/// An enumaration of FontAwesome icon names.
// swiftlint:disable file_length type_body_length
public enum FontAwesome: String, CaseIterable {
case fiveHundredPixels = "fa-500px"
case accessibleIcon = "fa-accessible-icon"
case accusoft = "fa-accusoft"
case acquisitionsIncorporated = "fa-acquisitions-incorporated"
case ad = "fa-ad"
case addressBook = "fa-address-book"
case addressCard = "fa-address-card"
case adjust = "fa-adjust"
case adn = "fa-adn"
case adobe = "fa-adobe"
case adversal = "fa-adversal"
case affiliatetheme = "fa-affiliatetheme"
case airFreshener = "fa-air-freshener"
case airbnb = "fa-airbnb"
case algolia = "fa-algolia"
case alignCenter = "fa-align-center"
case alignJustify = "fa-align-justify"
case alignLeft = "fa-align-left"
case alignRight = "fa-align-right"
case alipay = "fa-alipay"
case allergies = "fa-allergies"
case amazon = "fa-amazon"
case amazonPay = "fa-amazon-pay"
case ambulance = "fa-ambulance"
case americanSignLanguageInterpreting = "fa-american-sign-language-interpreting"
case amilia = "fa-amilia"
case anchor = "fa-anchor"
case android = "fa-android"
case angellist = "fa-angellist"
case angleDoubleDown = "fa-angle-double-down"
case angleDoubleLeft = "fa-angle-double-left"
case angleDoubleRight = "fa-angle-double-right"
case angleDoubleUp = "fa-angle-double-up"
case angleDown = "fa-angle-down"
case angleLeft = "fa-angle-left"
case angleRight = "fa-angle-right"
case angleUp = "fa-angle-up"
case angry = "fa-angry"
case angrycreative = "fa-angrycreative"
case angular = "fa-angular"
case ankh = "fa-ankh"
case appStore = "fa-app-store"
case appStoreIos = "fa-app-store-ios"
case apper = "fa-apper"
case apple = "fa-apple"
case appleAlt = "fa-apple-alt"
case applePay = "fa-apple-pay"
case archive = "fa-archive"
case archway = "fa-archway"
case arrowAltCircleDown = "fa-arrow-alt-circle-down"
case arrowAltCircleLeft = "fa-arrow-alt-circle-left"
case arrowAltCircleRight = "fa-arrow-alt-circle-right"
case arrowAltCircleUp = "fa-arrow-alt-circle-up"
case arrowCircleDown = "fa-arrow-circle-down"
case arrowCircleLeft = "fa-arrow-circle-left"
case arrowCircleRight = "fa-arrow-circle-right"
case arrowCircleUp = "fa-arrow-circle-up"
case arrowDown = "fa-arrow-down"
case arrowLeft = "fa-arrow-left"
case arrowRight = "fa-arrow-right"
case arrowUp = "fa-arrow-up"
case arrowsAlt = "fa-arrows-alt"
case arrowsAltH = "fa-arrows-alt-h"
case arrowsAltV = "fa-arrows-alt-v"
case artstation = "fa-artstation"
case assistiveListeningSystems = "fa-assistive-listening-systems"
case asterisk = "fa-asterisk"
case asymmetrik = "fa-asymmetrik"
case at = "fa-at"
case atlas = "fa-atlas"
case atlassian = "fa-atlassian"
case atom = "fa-atom"
case audible = "fa-audible"
case audioDescription = "fa-audio-description"
case autoprefixer = "fa-autoprefixer"
case avianex = "fa-avianex"
case aviato = "fa-aviato"
case award = "fa-award"
case aws = "fa-aws"
case baby = "fa-baby"
case babyCarriage = "fa-baby-carriage"
case backspace = "fa-backspace"
case backward = "fa-backward"
case bacon = "fa-bacon"
case bahai = "fa-bahai"
case balanceScale = "fa-balance-scale"
case balanceScaleLeft = "fa-balance-scale-left"
case balanceScaleRight = "fa-balance-scale-right"
case ban = "fa-ban"
case bandAid = "fa-band-aid"
case bandcamp = "fa-bandcamp"
case barcode = "fa-barcode"
case bars = "fa-bars"
case baseballBall = "fa-baseball-ball"
case basketballBall = "fa-basketball-ball"
case bath = "fa-bath"
case batteryEmpty = "fa-battery-empty"
case batteryFull = "fa-battery-full"
case batteryHalf = "fa-battery-half"
case batteryQuarter = "fa-battery-quarter"
case batteryThreeQuarters = "fa-battery-three-quarters"
case battleNet = "fa-battle-net"
case bed = "fa-bed"
case beer = "fa-beer"
case behance = "fa-behance"
case behanceSquare = "fa-behance-square"
case bell = "fa-bell"
case bellSlash = "fa-bell-slash"
case bezierCurve = "fa-bezier-curve"
case bible = "fa-bible"
case bicycle = "fa-bicycle"
case biking = "fa-biking"
case bimobject = "fa-bimobject"
case binoculars = "fa-binoculars"
case biohazard = "fa-biohazard"
case birthdayCake = "fa-birthday-cake"
case bitbucket = "fa-bitbucket"
case bitcoin = "fa-bitcoin"
case bity = "fa-bity"
case blackTie = "fa-black-tie"
case blackberry = "fa-blackberry"
case blender = "fa-blender"
case blenderPhone = "fa-blender-phone"
case blind = "fa-blind"
case blog = "fa-blog"
case blogger = "fa-blogger"
case bloggerB = "fa-blogger-b"
case bluetooth = "fa-bluetooth"
case bluetoothB = "fa-bluetooth-b"
case bold = "fa-bold"
case bolt = "fa-bolt"
case bomb = "fa-bomb"
case bone = "fa-bone"
case bong = "fa-bong"
case book = "fa-book"
case bookDead = "fa-book-dead"
case bookMedical = "fa-book-medical"
case bookOpen = "fa-book-open"
case bookReader = "fa-book-reader"
case bookmark = "fa-bookmark"
case bootstrap = "fa-bootstrap"
case borderAll = "fa-border-all"
case borderNone = "fa-border-none"
case borderStyle = "fa-border-style"
case bowlingBall = "fa-bowling-ball"
case box = "fa-box"
case boxOpen = "fa-box-open"
case boxTissue = "fa-box-tissue"
case boxes = "fa-boxes"
case braille = "fa-braille"
case brain = "fa-brain"
case breadSlice = "fa-bread-slice"
case briefcase = "fa-briefcase"
case briefcaseMedical = "fa-briefcase-medical"
case broadcastTower = "fa-broadcast-tower"
case broom = "fa-broom"
case brush = "fa-brush"
case btc = "fa-btc"
case buffer = "fa-buffer"
case bug = "fa-bug"
case building = "fa-building"
case bullhorn = "fa-bullhorn"
case bullseye = "fa-bullseye"
case burn = "fa-burn"
case buromobelexperte = "fa-buromobelexperte"
case bus = "fa-bus"
case busAlt = "fa-bus-alt"
case businessTime = "fa-business-time"
case buyNLarge = "fa-buy-n-large"
case buysellads = "fa-buysellads"
case calculator = "fa-calculator"
case calendar = "fa-calendar"
case calendarAlt = "fa-calendar-alt"
case calendarCheck = "fa-calendar-check"
case calendarDay = "fa-calendar-day"
case calendarMinus = "fa-calendar-minus"
case calendarPlus = "fa-calendar-plus"
case calendarTimes = "fa-calendar-times"
case calendarWeek = "fa-calendar-week"
case camera = "fa-camera"
case cameraRetro = "fa-camera-retro"
case campground = "fa-campground"
case canadianMapleLeaf = "fa-canadian-maple-leaf"
case candyCane = "fa-candy-cane"
case cannabis = "fa-cannabis"
case capsules = "fa-capsules"
case car = "fa-car"
case carAlt = "fa-car-alt"
case carBattery = "fa-car-battery"
case carCrash = "fa-car-crash"
case carSide = "fa-car-side"
case caravan = "fa-caravan"
case caretDown = "fa-caret-down"
case caretLeft = "fa-caret-left"
case caretRight = "fa-caret-right"
case caretSquareDown = "fa-caret-square-down"
case caretSquareLeft = "fa-caret-square-left"
case caretSquareRight = "fa-caret-square-right"
case caretSquareUp = "fa-caret-square-up"
case caretUp = "fa-caret-up"
case carrot = "fa-carrot"
case cartArrowDown = "fa-cart-arrow-down"
case cartPlus = "fa-cart-plus"
case cashRegister = "fa-cash-register"
case cat = "fa-cat"
case ccAmazonPay = "fa-cc-amazon-pay"
case ccAmex = "fa-cc-amex"
case ccApplePay = "fa-cc-apple-pay"
case ccDinersClub = "fa-cc-diners-club"
case ccDiscover = "fa-cc-discover"
case ccJcb = "fa-cc-jcb"
case ccMastercard = "fa-cc-mastercard"
case ccPaypal = "fa-cc-paypal"
case ccStripe = "fa-cc-stripe"
case ccVisa = "fa-cc-visa"
case centercode = "fa-centercode"
case centos = "fa-centos"
case certificate = "fa-certificate"
case chair = "fa-chair"
case chalkboard = "fa-chalkboard"
case chalkboardTeacher = "fa-chalkboard-teacher"
case chargingStation = "fa-charging-station"
case chartArea = "fa-chart-area"
case chartBar = "fa-chart-bar"
case chartLine = "fa-chart-line"
case chartPie = "fa-chart-pie"
case check = "fa-check"
case checkCircle = "fa-check-circle"
case checkDouble = "fa-check-double"
case checkSquare = "fa-check-square"
case cheese = "fa-cheese"
case chess = "fa-chess"
case chessBishop = "fa-chess-bishop"
case chessBoard = "fa-chess-board"
case chessKing = "fa-chess-king"
case chessKnight = "fa-chess-knight"
case chessPawn = "fa-chess-pawn"
case chessQueen = "fa-chess-queen"
case chessRook = "fa-chess-rook"
case chevronCircleDown = "fa-chevron-circle-down"
case chevronCircleLeft = "fa-chevron-circle-left"
case chevronCircleRight = "fa-chevron-circle-right"
case chevronCircleUp = "fa-chevron-circle-up"
case chevronDown = "fa-chevron-down"
case chevronLeft = "fa-chevron-left"
case chevronRight = "fa-chevron-right"
case chevronUp = "fa-chevron-up"
case child = "fa-child"
case chrome = "fa-chrome"
case chromecast = "fa-chromecast"
case church = "fa-church"
case circle = "fa-circle"
case circleNotch = "fa-circle-notch"
case city = "fa-city"
case clinicMedical = "fa-clinic-medical"
case clipboard = "fa-clipboard"
case clipboardCheck = "fa-clipboard-check"
case clipboardList = "fa-clipboard-list"
case clock = "fa-clock"
case clone = "fa-clone"
case closedCaptioning = "fa-closed-captioning"
case cloud = "fa-cloud"
case cloudDownloadAlt = "fa-cloud-download-alt"
case cloudMeatball = "fa-cloud-meatball"
case cloudMoon = "fa-cloud-moon"
case cloudMoonRain = "fa-cloud-moon-rain"
case cloudRain = "fa-cloud-rain"
case cloudShowersHeavy = "fa-cloud-showers-heavy"
case cloudSun = "fa-cloud-sun"
case cloudSunRain = "fa-cloud-sun-rain"
case cloudUploadAlt = "fa-cloud-upload-alt"
case cloudscale = "fa-cloudscale"
case cloudsmith = "fa-cloudsmith"
case cloudversify = "fa-cloudversify"
case cocktail = "fa-cocktail"
case code = "fa-code"
case codeBranch = "fa-code-branch"
case codepen = "fa-codepen"
case codiepie = "fa-codiepie"
case coffee = "fa-coffee"
case cog = "fa-cog"
case cogs = "fa-cogs"
case coins = "fa-coins"
case columns = "fa-columns"
case comment = "fa-comment"
case commentAlt = "fa-comment-alt"
case commentDollar = "fa-comment-dollar"
case commentDots = "fa-comment-dots"
case commentMedical = "fa-comment-medical"
case commentSlash = "fa-comment-slash"
case comments = "fa-comments"
case commentsDollar = "fa-comments-dollar"
case compactDisc = "fa-compact-disc"
case compass = "fa-compass"
case compress = "fa-compress"
case compressAlt = "fa-compress-alt"
case compressArrowsAlt = "fa-compress-arrows-alt"
case conciergeBell = "fa-concierge-bell"
case confluence = "fa-confluence"
case connectdevelop = "fa-connectdevelop"
case contao = "fa-contao"
case cookie = "fa-cookie"
case cookieBite = "fa-cookie-bite"
case copy = "fa-copy"
case copyright = "fa-copyright"
case cottonBureau = "fa-cotton-bureau"
case couch = "fa-couch"
case cpanel = "fa-cpanel"
case creativeCommons = "fa-creative-commons"
case creativeCommonsBy = "fa-creative-commons-by"
case creativeCommonsNc = "fa-creative-commons-nc"
case creativeCommonsNcEu = "fa-creative-commons-nc-eu"
case creativeCommonsNcJp = "fa-creative-commons-nc-jp"
case creativeCommonsNd = "fa-creative-commons-nd"
case creativeCommonsPd = "fa-creative-commons-pd"
case creativeCommonsPdAlt = "fa-creative-commons-pd-alt"
case creativeCommonsRemix = "fa-creative-commons-remix"
case creativeCommonsSa = "fa-creative-commons-sa"
case creativeCommonsSampling = "fa-creative-commons-sampling"
case creativeCommonsSamplingPlus = "fa-creative-commons-sampling-plus"
case creativeCommonsShare = "fa-creative-commons-share"
case creativeCommonsZero = "fa-creative-commons-zero"
case creditCard = "fa-credit-card"
case criticalRole = "fa-critical-role"
case crop = "fa-crop"
case cropAlt = "fa-crop-alt"
case cross = "fa-cross"
case crosshairs = "fa-crosshairs"
case crow = "fa-crow"
case crown = "fa-crown"
case crutch = "fa-crutch"
case css3 = "fa-css3"
case css3Alt = "fa-css3-alt"
case cube = "fa-cube"
case cubes = "fa-cubes"
case cut = "fa-cut"
case cuttlefish = "fa-cuttlefish"
case dAndD = "fa-d-and-d"
case dAndDBeyond = "fa-d-and-d-beyond"
case dailymotion = "fa-dailymotion"
case dashcube = "fa-dashcube"
case database = "fa-database"
case deaf = "fa-deaf"
case delicious = "fa-delicious"
case democrat = "fa-democrat"
case deploydog = "fa-deploydog"
case deskpro = "fa-deskpro"
case desktop = "fa-desktop"
case dev = "fa-dev"
case deviantart = "fa-deviantart"
case dharmachakra = "fa-dharmachakra"
case dhl = "fa-dhl"
case diagnoses = "fa-diagnoses"
case diaspora = "fa-diaspora"
case dice = "fa-dice"
case diceD20 = "fa-dice-d20"
case diceD6 = "fa-dice-d6"
case diceFive = "fa-dice-five"
case diceFour = "fa-dice-four"
case diceOne = "fa-dice-one"
case diceSix = "fa-dice-six"
case diceThree = "fa-dice-three"
case diceTwo = "fa-dice-two"
case digg = "fa-digg"
case digitalOcean = "fa-digital-ocean"
case digitalTachograph = "fa-digital-tachograph"
case directions = "fa-directions"
case discord = "fa-discord"
case discourse = "fa-discourse"
case disease = "fa-disease"
case divide = "fa-divide"
case dizzy = "fa-dizzy"
case dna = "fa-dna"
case dochub = "fa-dochub"
case docker = "fa-docker"
case dog = "fa-dog"
case dollarSign = "fa-dollar-sign"
case dolly = "fa-dolly"
case dollyFlatbed = "fa-dolly-flatbed"
case donate = "fa-donate"
case doorClosed = "fa-door-closed"
case doorOpen = "fa-door-open"
case dotCircle = "fa-dot-circle"
case dove = "fa-dove"
case download = "fa-download"
case draft2digital = "fa-draft2digital"
case draftingCompass = "fa-drafting-compass"
case dragon = "fa-dragon"
case drawPolygon = "fa-draw-polygon"
case dribbble = "fa-dribbble"
case dribbbleSquare = "fa-dribbble-square"
case dropbox = "fa-dropbox"
case drum = "fa-drum"
case drumSteelpan = "fa-drum-steelpan"
case drumstickBite = "fa-drumstick-bite"
case drupal = "fa-drupal"
case dumbbell = "fa-dumbbell"
case dumpster = "fa-dumpster"
case dumpsterFire = "fa-dumpster-fire"
case dungeon = "fa-dungeon"
case dyalog = "fa-dyalog"
case earlybirds = "fa-earlybirds"
case ebay = "fa-ebay"
case edge = "fa-edge"
case edit = "fa-edit"
case egg = "fa-egg"
case eject = "fa-eject"
case elementor = "fa-elementor"
case ellipsisH = "fa-ellipsis-h"
case ellipsisV = "fa-ellipsis-v"
case ello = "fa-ello"
case ember = "fa-ember"
case empire = "fa-empire"
case envelope = "fa-envelope"
case envelopeOpen = "fa-envelope-open"
case envelopeOpenText = "fa-envelope-open-text"
case envelopeSquare = "fa-envelope-square"
case envira = "fa-envira"
case equals = "fa-equals"
case eraser = "fa-eraser"
case erlang = "fa-erlang"
case ethereum = "fa-ethereum"
case ethernet = "fa-ethernet"
case etsy = "fa-etsy"
case euroSign = "fa-euro-sign"
case evernote = "fa-evernote"
case exchangeAlt = "fa-exchange-alt"
case exclamation = "fa-exclamation"
case exclamationCircle = "fa-exclamation-circle"
case exclamationTriangle = "fa-exclamation-triangle"
case expand = "fa-expand"
case expandAlt = "fa-expand-alt"
case expandArrowsAlt = "fa-expand-arrows-alt"
case expeditedssl = "fa-expeditedssl"
case externalLinkAlt = "fa-external-link-alt"
case externalLinkSquareAlt = "fa-external-link-square-alt"
case eye = "fa-eye"
case eyeDropper = "fa-eye-dropper"
case eyeSlash = "fa-eye-slash"
case facebook = "fa-facebook"
case facebookF = "fa-facebook-f"
case facebookMessenger = "fa-facebook-messenger"
case facebookSquare = "fa-facebook-square"
case fan = "fa-fan"
case fantasyFlightGames = "fa-fantasy-flight-games"
case fastBackward = "fa-fast-backward"
case fastForward = "fa-fast-forward"
case faucet = "fa-faucet"
case fax = "fa-fax"
case feather = "fa-feather"
case featherAlt = "fa-feather-alt"
case fedex = "fa-fedex"
case fedora = "fa-fedora"
case female = "fa-female"
case fighterJet = "fa-fighter-jet"
case figma = "fa-figma"
case file = "fa-file"
case fileAlt = "fa-file-alt"
case fileArchive = "fa-file-archive"
case fileAudio = "fa-file-audio"
case fileCode = "fa-file-code"
case fileContract = "fa-file-contract"
case fileCsv = "fa-file-csv"
case fileDownload = "fa-file-download"
case fileExcel = "fa-file-excel"
case fileExport = "fa-file-export"
case fileImage = "fa-file-image"
case fileImport = "fa-file-import"
case fileInvoice = "fa-file-invoice"
case fileInvoiceDollar = "fa-file-invoice-dollar"
case fileMedical = "fa-file-medical"
case fileMedicalAlt = "fa-file-medical-alt"
case filePdf = "fa-file-pdf"
case filePowerpoint = "fa-file-powerpoint"
case filePrescription = "fa-file-prescription"
case fileSignature = "fa-file-signature"
case fileUpload = "fa-file-upload"
case fileVideo = "fa-file-video"
case fileWord = "fa-file-word"
case fill = "fa-fill"
case fillDrip = "fa-fill-drip"
case film = "fa-film"
case filter = "fa-filter"
case fingerprint = "fa-fingerprint"
case fire = "fa-fire"
case fireAlt = "fa-fire-alt"
case fireExtinguisher = "fa-fire-extinguisher"
case firefox = "fa-firefox"
case firefoxBrowser = "fa-firefox-browser"
case firstAid = "fa-first-aid"
case firstOrder = "fa-first-order"
case firstOrderAlt = "fa-first-order-alt"
case firstdraft = "fa-firstdraft"
case fish = "fa-fish"
case fistRaised = "fa-fist-raised"
case flag = "fa-flag"
case flagCheckered = "fa-flag-checkered"
case flagUsa = "fa-flag-usa"
case flask = "fa-flask"
case flickr = "fa-flickr"
case flipboard = "fa-flipboard"
case flushed = "fa-flushed"
case fly = "fa-fly"
case folder = "fa-folder"
case folderMinus = "fa-folder-minus"
case folderOpen = "fa-folder-open"
case folderPlus = "fa-folder-plus"
case font = "fa-font"
case fontAwesome = "fa-font-awesome"
case fontAwesomeAlt = "fa-font-awesome-alt"
case fontAwesomeFlag = "fa-font-awesome-flag"
case fontAwesomeLogoFull = "fa-font-awesome-logo-full"
case fonticons = "fa-fonticons"
case fonticonsFi = "fa-fonticons-fi"
case footballBall = "fa-football-ball"
case fortAwesome = "fa-fort-awesome"
case fortAwesomeAlt = "fa-fort-awesome-alt"
case forumbee = "fa-forumbee"
case forward = "fa-forward"
case foursquare = "fa-foursquare"
case freeCodeCamp = "fa-free-code-camp"
case freebsd = "fa-freebsd"
case frog = "fa-frog"
case frown = "fa-frown"
case frownOpen = "fa-frown-open"
case fulcrum = "fa-fulcrum"
case funnelDollar = "fa-funnel-dollar"
case futbol = "fa-futbol"
case galacticRepublic = "fa-galactic-republic"
case galacticSenate = "fa-galactic-senate"
case gamepad = "fa-gamepad"
case gasPump = "fa-gas-pump"
case gavel = "fa-gavel"
case gem = "fa-gem"
case genderless = "fa-genderless"
case getPocket = "fa-get-pocket"
case gg = "fa-gg"
case ggCircle = "fa-gg-circle"
case ghost = "fa-ghost"
case gift = "fa-gift"
case gifts = "fa-gifts"
case git = "fa-git"
case gitAlt = "fa-git-alt"
case gitSquare = "fa-git-square"
case github = "fa-github"
case githubAlt = "fa-github-alt"
case githubSquare = "fa-github-square"
case gitkraken = "fa-gitkraken"
case gitlab = "fa-gitlab"
case gitter = "fa-gitter"
case glassCheers = "fa-glass-cheers"
case glassMartini = "fa-glass-martini"
case glassMartiniAlt = "fa-glass-martini-alt"
case glassWhiskey = "fa-glass-whiskey"
case glasses = "fa-glasses"
case glide = "fa-glide"
case glideG = "fa-glide-g"
case globe = "fa-globe"
case globeAfrica = "fa-globe-africa"
case globeAmericas = "fa-globe-americas"
case globeAsia = "fa-globe-asia"
case globeEurope = "fa-globe-europe"
case gofore = "fa-gofore"
case golfBall = "fa-golf-ball"
case goodreads = "fa-goodreads"
case goodreadsG = "fa-goodreads-g"
case google = "fa-google"
case googleDrive = "fa-google-drive"
case googlePlay = "fa-google-play"
case googlePlus = "fa-google-plus"
case googlePlusG = "fa-google-plus-g"
case googlePlusSquare = "fa-google-plus-square"
case googleWallet = "fa-google-wallet"
case gopuram = "fa-gopuram"
case graduationCap = "fa-graduation-cap"
case gratipay = "fa-gratipay"
case grav = "fa-grav"
case greaterThan = "fa-greater-than"
case greaterThanEqual = "fa-greater-than-equal"
case grimace = "fa-grimace"
case grin = "fa-grin"
case grinAlt = "fa-grin-alt"
case grinBeam = "fa-grin-beam"
case grinBeamSweat = "fa-grin-beam-sweat"
case grinHearts = "fa-grin-hearts"
case grinSquint = "fa-grin-squint"
case grinSquintTears = "fa-grin-squint-tears"
case grinStars = "fa-grin-stars"
case grinTears = "fa-grin-tears"
case grinTongue = "fa-grin-tongue"
case grinTongueSquint = "fa-grin-tongue-squint"
case grinTongueWink = "fa-grin-tongue-wink"
case grinWink = "fa-grin-wink"
case gripHorizontal = "fa-grip-horizontal"
case gripLines = "fa-grip-lines"
case gripLinesVertical = "fa-grip-lines-vertical"
case gripVertical = "fa-grip-vertical"
case gripfire = "fa-gripfire"
case grunt = "fa-grunt"
case guitar = "fa-guitar"
case gulp = "fa-gulp"
case hSquare = "fa-h-square"
case hackerNews = "fa-hacker-news"
case hackerNewsSquare = "fa-hacker-news-square"
case hackerrank = "fa-hackerrank"
case hamburger = "fa-hamburger"
case hammer = "fa-hammer"
case hamsa = "fa-hamsa"
case handHolding = "fa-hand-holding"
case handHoldingHeart = "fa-hand-holding-heart"
case handHoldingMedical = "fa-hand-holding-medical"
case handHoldingUsd = "fa-hand-holding-usd"
case handHoldingWater = "fa-hand-holding-water"
case handLizard = "fa-hand-lizard"
case handMiddleFinger = "fa-hand-middle-finger"
case handPaper = "fa-hand-paper"
case handPeace = "fa-hand-peace"
case handPointDown = "fa-hand-point-down"
case handPointLeft = "fa-hand-point-left"
case handPointRight = "fa-hand-point-right"
case handPointUp = "fa-hand-point-up"
case handPointer = "fa-hand-pointer"
case handRock = "fa-hand-rock"
case handScissors = "fa-hand-scissors"
case handSparkles = "fa-hand-sparkles"
case handSpock = "fa-hand-spock"
case hands = "fa-hands"
case handsHelping = "fa-hands-helping"
case handsWash = "fa-hands-wash"
case handshake = "fa-handshake"
case handshakeAltSlash = "fa-handshake-alt-slash"
case handshakeSlash = "fa-handshake-slash"
case hanukiah = "fa-hanukiah"
case hardHat = "fa-hard-hat"
case hashtag = "fa-hashtag"
case hatCowboy = "fa-hat-cowboy"
case hatCowboySide = "fa-hat-cowboy-side"
case hatWizard = "fa-hat-wizard"
case hdd = "fa-hdd"
case headSideCough = "fa-head-side-cough"
case headSideCoughSlash = "fa-head-side-cough-slash"
case headSideMask = "fa-head-side-mask"
case headSideVirus = "fa-head-side-virus"
case heading = "fa-heading"
case headphones = "fa-headphones"
case headphonesAlt = "fa-headphones-alt"
case headset = "fa-headset"
case heart = "fa-heart"
case heartBroken = "fa-heart-broken"
case heartbeat = "fa-heartbeat"
case helicopter = "fa-helicopter"
case highlighter = "fa-highlighter"
case hiking = "fa-hiking"
case hippo = "fa-hippo"
case hips = "fa-hips"
case hireAHelper = "fa-hire-a-helper"
case history = "fa-history"
case hockeyPuck = "fa-hockey-puck"
case hollyBerry = "fa-holly-berry"
case home = "fa-home"
case hooli = "fa-hooli"
case hornbill = "fa-hornbill"
case horse = "fa-horse"
case horseHead = "fa-horse-head"
case hospital = "fa-hospital"
case hospitalAlt = "fa-hospital-alt"
case hospitalSymbol = "fa-hospital-symbol"
case hospitalUser = "fa-hospital-user"
case hotTub = "fa-hot-tub"
case hotdog = "fa-hotdog"
case hotel = "fa-hotel"
case hotjar = "fa-hotjar"
case hourglass = "fa-hourglass"
case hourglassEnd = "fa-hourglass-end"
case hourglassHalf = "fa-hourglass-half"
case hourglassStart = "fa-hourglass-start"
case houseDamage = "fa-house-damage"
case houseUser = "fa-house-user"
case houzz = "fa-houzz"
case hryvnia = "fa-hryvnia"
case html5 = "fa-html5"
case hubspot = "fa-hubspot"
case iCursor = "fa-i-cursor"
case iceCream = "fa-ice-cream"
case icicles = "fa-icicles"
case icons = "fa-icons"
case idBadge = "fa-id-badge"
case idCard = "fa-id-card"
case idCardAlt = "fa-id-card-alt"
case ideal = "fa-ideal"
case igloo = "fa-igloo"
case image = "fa-image"
case images = "fa-images"
case imdb = "fa-imdb"
case inbox = "fa-inbox"
case indent = "fa-indent"
case industry = "fa-industry"
case infinity = "fa-infinity"
case info = "fa-info"
case infoCircle = "fa-info-circle"
case instagram = "fa-instagram"
case instagramSquare = "fa-instagram-square"
case intercom = "fa-intercom"
case internetExplorer = "fa-internet-explorer"
case invision = "fa-invision"
case ioxhost = "fa-ioxhost"
case italic = "fa-italic"
case itchIo = "fa-itch-io"
case itunes = "fa-itunes"
case itunesNote = "fa-itunes-note"
case java = "fa-java"
case jedi = "fa-jedi"
case jediOrder = "fa-jedi-order"
case jenkins = "fa-jenkins"
case jira = "fa-jira"
case joget = "fa-joget"
case joint = "fa-joint"
case joomla = "fa-joomla"
case journalWhills = "fa-journal-whills"
case js = "fa-js"
case jsSquare = "fa-js-square"
case jsfiddle = "fa-jsfiddle"
case kaaba = "fa-kaaba"
case kaggle = "fa-kaggle"
case key = "fa-key"
case keybase = "fa-keybase"
case keyboard = "fa-keyboard"
case keycdn = "fa-keycdn"
case khanda = "fa-khanda"
case kickstarter = "fa-kickstarter"
case kickstarterK = "fa-kickstarter-k"
case kiss = "fa-kiss"
case kissBeam = "fa-kiss-beam"
case kissWinkHeart = "fa-kiss-wink-heart"
case kiwiBird = "fa-kiwi-bird"
case korvue = "fa-korvue"
case landmark = "fa-landmark"
case language = "fa-language"
case laptop = "fa-laptop"
case laptopCode = "fa-laptop-code"
case laptopHouse = "fa-laptop-house"
case laptopMedical = "fa-laptop-medical"
case laravel = "fa-laravel"
case lastfm = "fa-lastfm"
case lastfmSquare = "fa-lastfm-square"
case laugh = "fa-laugh"
case laughBeam = "fa-laugh-beam"
case laughSquint = "fa-laugh-squint"
case laughWink = "fa-laugh-wink"
case layerGroup = "fa-layer-group"
case leaf = "fa-leaf"
case leanpub = "fa-leanpub"
case lemon = "fa-lemon"
case less = "fa-less"
case lessThan = "fa-less-than"
case lessThanEqual = "fa-less-than-equal"
case levelDownAlt = "fa-level-down-alt"
case levelUpAlt = "fa-level-up-alt"
case lifeRing = "fa-life-ring"
case lightbulb = "fa-lightbulb"
case line = "fa-line"
case link = "fa-link"
case linkedin = "fa-linkedin"
case linkedinIn = "fa-linkedin-in"
case linode = "fa-linode"
case linux = "fa-linux"
case liraSign = "fa-lira-sign"
case list = "fa-list"
case listAlt = "fa-list-alt"
case listOl = "fa-list-ol"
case listUl = "fa-list-ul"
case locationArrow = "fa-location-arrow"
case lock = "fa-lock"
case lockOpen = "fa-lock-open"
case longArrowAltDown = "fa-long-arrow-alt-down"
case longArrowAltLeft = "fa-long-arrow-alt-left"
case longArrowAltRight = "fa-long-arrow-alt-right"
case longArrowAltUp = "fa-long-arrow-alt-up"
case lowVision = "fa-low-vision"
case luggageCart = "fa-luggage-cart"
case lungs = "fa-lungs"
case lungsVirus = "fa-lungs-virus"
case lyft = "fa-lyft"
case magento = "fa-magento"
case magic = "fa-magic"
case magnet = "fa-magnet"
case mailBulk = "fa-mail-bulk"
case mailchimp = "fa-mailchimp"
case male = "fa-male"
case mandalorian = "fa-mandalorian"
case map = "fa-map"
case mapMarked = "fa-map-marked"
case mapMarkedAlt = "fa-map-marked-alt"
case mapMarker = "fa-map-marker"
case mapMarkerAlt = "fa-map-marker-alt"
case mapPin = "fa-map-pin"
case mapSigns = "fa-map-signs"
case markdown = "fa-markdown"
case marker = "fa-marker"
case mars = "fa-mars"
case marsDouble = "fa-mars-double"
case marsStroke = "fa-mars-stroke"
case marsStrokeH = "fa-mars-stroke-h"
case marsStrokeV = "fa-mars-stroke-v"
case mask = "fa-mask"
case mastodon = "fa-mastodon"
case maxcdn = "fa-maxcdn"
case mdb = "fa-mdb"
case medal = "fa-medal"
case medapps = "fa-medapps"
case medium = "fa-medium"
case mediumM = "fa-medium-m"
case medkit = "fa-medkit"
case medrt = "fa-medrt"
case meetup = "fa-meetup"
case megaport = "fa-megaport"
case meh = "fa-meh"
case mehBlank = "fa-meh-blank"
case mehRollingEyes = "fa-meh-rolling-eyes"
case memory = "fa-memory"
case mendeley = "fa-mendeley"
case menorah = "fa-menorah"
case mercury = "fa-mercury"
case meteor = "fa-meteor"
case microblog = "fa-microblog"
case microchip = "fa-microchip"
case microphone = "fa-microphone"
case microphoneAlt = "fa-microphone-alt"
case microphoneAltSlash = "fa-microphone-alt-slash"
case microphoneSlash = "fa-microphone-slash"
case microscope = "fa-microscope"
case microsoft = "fa-microsoft"
case minus = "fa-minus"
case minusCircle = "fa-minus-circle"
case minusSquare = "fa-minus-square"
case mitten = "fa-mitten"
case mix = "fa-mix"
case mixcloud = "fa-mixcloud"
case mixer = "fa-mixer"
case mizuni = "fa-mizuni"
case mobile = "fa-mobile"
case mobileAlt = "fa-mobile-alt"
case modx = "fa-modx"
case monero = "fa-monero"
case moneyBill = "fa-money-bill"
case moneyBillAlt = "fa-money-bill-alt"
case moneyBillWave = "fa-money-bill-wave"
case moneyBillWaveAlt = "fa-money-bill-wave-alt"
case moneyCheck = "fa-money-check"
case moneyCheckAlt = "fa-money-check-alt"
case monument = "fa-monument"
case moon = "fa-moon"
case mortarPestle = "fa-mortar-pestle"
case mosque = "fa-mosque"
case motorcycle = "fa-motorcycle"
case mountain = "fa-mountain"
case mouse = "fa-mouse"
case mousePointer = "fa-mouse-pointer"
case mugHot = "fa-mug-hot"
case music = "fa-music"
case napster = "fa-napster"
case neos = "fa-neos"
case networkWired = "fa-network-wired"
case neuter = "fa-neuter"
case newspaper = "fa-newspaper"
case nimblr = "fa-nimblr"
case node = "fa-node"
case nodeJs = "fa-node-js"
case notEqual = "fa-not-equal"
case notesMedical = "fa-notes-medical"
case npm = "fa-npm"
case ns8 = "fa-ns8"
case nutritionix = "fa-nutritionix"
case objectGroup = "fa-object-group"
case objectUngroup = "fa-object-ungroup"
case odnoklassniki = "fa-odnoklassniki"
case odnoklassnikiSquare = "fa-odnoklassniki-square"
case oilCan = "fa-oil-can"
case oldRepublic = "fa-old-republic"
case om = "fa-om"
case opencart = "fa-opencart"
case openid = "fa-openid"
case opera = "fa-opera"
case optinMonster = "fa-optin-monster"
case orcid = "fa-orcid"
case osi = "fa-osi"
case otter = "fa-otter"
case outdent = "fa-outdent"
case page4 = "fa-page4"
case pagelines = "fa-pagelines"
case pager = "fa-pager"
case paintBrush = "fa-paint-brush"
case paintRoller = "fa-paint-roller"
case palette = "fa-palette"
case palfed = "fa-palfed"
case pallet = "fa-pallet"
case paperPlane = "fa-paper-plane"
case paperclip = "fa-paperclip"
case parachuteBox = "fa-parachute-box"
case paragraph = "fa-paragraph"
case parking = "fa-parking"
case passport = "fa-passport"
case pastafarianism = "fa-pastafarianism"
case paste = "fa-paste"
case patreon = "fa-patreon"
case pause = "fa-pause"
case pauseCircle = "fa-pause-circle"
case paw = "fa-paw"
case paypal = "fa-paypal"
case peace = "fa-peace"
case pen = "fa-pen"
case penAlt = "fa-pen-alt"
case penFancy = "fa-pen-fancy"
case penNib = "fa-pen-nib"
case penSquare = "fa-pen-square"
case pencilAlt = "fa-pencil-alt"
case pencilRuler = "fa-pencil-ruler"
case pennyArcade = "fa-penny-arcade"
case peopleArrows = "fa-people-arrows"
case peopleCarry = "fa-people-carry"
case pepperHot = "fa-pepper-hot"
case percent = "fa-percent"
case percentage = "fa-percentage"
case periscope = "fa-periscope"
case personBooth = "fa-person-booth"
case phabricator = "fa-phabricator"
case phoenixFramework = "fa-phoenix-framework"
case phoenixSquadron = "fa-phoenix-squadron"
case phone = "fa-phone"
case phoneAlt = "fa-phone-alt"
case phoneSlash = "fa-phone-slash"
case phoneSquare = "fa-phone-square"
case phoneSquareAlt = "fa-phone-square-alt"
case phoneVolume = "fa-phone-volume"
case photoVideo = "fa-photo-video"
case php = "fa-php"
case piedPiper = "fa-pied-piper"
case piedPiperAlt = "fa-pied-piper-alt"
case piedPiperHat = "fa-pied-piper-hat"
case piedPiperPp = "fa-pied-piper-pp"
case piedPiperSquare = "fa-pied-piper-square"
case piggyBank = "fa-piggy-bank"
case pills = "fa-pills"
case pinterest = "fa-pinterest"
case pinterestP = "fa-pinterest-p"
case pinterestSquare = "fa-pinterest-square"
case pizzaSlice = "fa-pizza-slice"
case placeOfWorship = "fa-place-of-worship"
case plane = "fa-plane"
case planeArrival = "fa-plane-arrival"
case planeDeparture = "fa-plane-departure"
case planeSlash = "fa-plane-slash"
case play = "fa-play"
case playCircle = "fa-play-circle"
case playstation = "fa-playstation"
case plug = "fa-plug"
case plus = "fa-plus"
case plusCircle = "fa-plus-circle"
case plusSquare = "fa-plus-square"
case podcast = "fa-podcast"
case poll = "fa-poll"
case pollH = "fa-poll-h"
case poo = "fa-poo"
case pooStorm = "fa-poo-storm"
case poop = "fa-poop"
case portrait = "fa-portrait"
case poundSign = "fa-pound-sign"
case powerOff = "fa-power-off"
case pray = "fa-pray"
case prayingHands = "fa-praying-hands"
case prescription = "fa-prescription"
case prescriptionBottle = "fa-prescription-bottle"
case prescriptionBottleAlt = "fa-prescription-bottle-alt"
case print = "fa-print"
case procedures = "fa-procedures"
case productHunt = "fa-product-hunt"
case projectDiagram = "fa-project-diagram"
case pumpMedical = "fa-pump-medical"
case pumpSoap = "fa-pump-soap"
case pushed = "fa-pushed"
case puzzlePiece = "fa-puzzle-piece"
case python = "fa-python"
case qq = "fa-qq"
case qrcode = "fa-qrcode"
case question = "fa-question"
case questionCircle = "fa-question-circle"
case quidditch = "fa-quidditch"
case quinscape = "fa-quinscape"
case quora = "fa-quora"
case quoteLeft = "fa-quote-left"
case quoteRight = "fa-quote-right"
case quran = "fa-quran"
case rProject = "fa-r-project"
case radiation = "fa-radiation"
case radiationAlt = "fa-radiation-alt"
case rainbow = "fa-rainbow"
case random = "fa-random"
case raspberryPi = "fa-raspberry-pi"
case ravelry = "fa-ravelry"
case react = "fa-react"
case reacteurope = "fa-reacteurope"
case readme = "fa-readme"
case rebel = "fa-rebel"
case receipt = "fa-receipt"
case recordVinyl = "fa-record-vinyl"
case recycle = "fa-recycle"
case redRiver = "fa-red-river"
case reddit = "fa-reddit"
case redditAlien = "fa-reddit-alien"
case redditSquare = "fa-reddit-square"
case redhat = "fa-redhat"
case redo = "fa-redo"
case redoAlt = "fa-redo-alt"
case registered = "fa-registered"
case removeFormat = "fa-remove-format"
case renren = "fa-renren"
case reply = "fa-reply"
case replyAll = "fa-reply-all"
case replyd = "fa-replyd"
case republican = "fa-republican"
case researchgate = "fa-researchgate"
case resolving = "fa-resolving"
case restroom = "fa-restroom"
case retweet = "fa-retweet"
case rev = "fa-rev"
case ribbon = "fa-ribbon"
case ring = "fa-ring"
case road = "fa-road"
case robot = "fa-robot"
case rocket = "fa-rocket"
case rocketchat = "fa-rocketchat"
case rockrms = "fa-rockrms"
case route = "fa-route"
case rss = "fa-rss"
case rssSquare = "fa-rss-square"
case rubleSign = "fa-ruble-sign"
case ruler = "fa-ruler"
case rulerCombined = "fa-ruler-combined"
case rulerHorizontal = "fa-ruler-horizontal"
case rulerVertical = "fa-ruler-vertical"
case running = "fa-running"
case rupeeSign = "fa-rupee-sign"
case sadCry = "fa-sad-cry"
case sadTear = "fa-sad-tear"
case safari = "fa-safari"
case salesforce = "fa-salesforce"
case sass = "fa-sass"
case satellite = "fa-satellite"
case satelliteDish = "fa-satellite-dish"
case save = "fa-save"
case schlix = "fa-schlix"
case school = "fa-school"
case screwdriver = "fa-screwdriver"
case scribd = "fa-scribd"
case scroll = "fa-scroll"
case sdCard = "fa-sd-card"
case search = "fa-search"
case searchDollar = "fa-search-dollar"
case searchLocation = "fa-search-location"
case searchMinus = "fa-search-minus"
case searchPlus = "fa-search-plus"
case searchengin = "fa-searchengin"
case seedling = "fa-seedling"
case sellcast = "fa-sellcast"
case sellsy = "fa-sellsy"
case server = "fa-server"
case servicestack = "fa-servicestack"
case shapes = "fa-shapes"
case share = "fa-share"
case shareAlt = "fa-share-alt"
case shareAltSquare = "fa-share-alt-square"
case shareSquare = "fa-share-square"
case shekelSign = "fa-shekel-sign"
case shieldAlt = "fa-shield-alt"
case shieldVirus = "fa-shield-virus"
case ship = "fa-ship"
case shippingFast = "fa-shipping-fast"
case shirtsinbulk = "fa-shirtsinbulk"
case shoePrints = "fa-shoe-prints"
case shopify = "fa-shopify"
case shoppingBag = "fa-shopping-bag"
case shoppingBasket = "fa-shopping-basket"
case shoppingCart = "fa-shopping-cart"
case shopware = "fa-shopware"
case shower = "fa-shower"
case shuttleVan = "fa-shuttle-van"
case sign = "fa-sign"
case signInAlt = "fa-sign-in-alt"
case signLanguage = "fa-sign-language"
case signOutAlt = "fa-sign-out-alt"
case signal = "fa-signal"
case signature = "fa-signature"
case simCard = "fa-sim-card"
case simplybuilt = "fa-simplybuilt"
case sistrix = "fa-sistrix"
case sitemap = "fa-sitemap"
case sith = "fa-sith"
case skating = "fa-skating"
case sketch = "fa-sketch"
case skiing = "fa-skiing"
case skiingNordic = "fa-skiing-nordic"
case skull = "fa-skull"
case skullCrossbones = "fa-skull-crossbones"
case skyatlas = "fa-skyatlas"
case skype = "fa-skype"
case slack = "fa-slack"
case slackHash = "fa-slack-hash"
case slash = "fa-slash"
case sleigh = "fa-sleigh"
case slidersH = "fa-sliders-h"
case slideshare = "fa-slideshare"
case smile = "fa-smile"
case smileBeam = "fa-smile-beam"
case smileWink = "fa-smile-wink"
case smog = "fa-smog"
case smoking = "fa-smoking"
case smokingBan = "fa-smoking-ban"
case sms = "fa-sms"
case snapchat = "fa-snapchat"
case snapchatGhost = "fa-snapchat-ghost"
case snapchatSquare = "fa-snapchat-square"
case snowboarding = "fa-snowboarding"
case snowflake = "fa-snowflake"
case snowman = "fa-snowman"
case snowplow = "fa-snowplow"
case soap = "fa-soap"
case socks = "fa-socks"
case solarPanel = "fa-solar-panel"
case sort = "fa-sort"
case sortAlphaDown = "fa-sort-alpha-down"
case sortAlphaDownAlt = "fa-sort-alpha-down-alt"
case sortAlphaUp = "fa-sort-alpha-up"
case sortAlphaUpAlt = "fa-sort-alpha-up-alt"
case sortAmountDown = "fa-sort-amount-down"
case sortAmountDownAlt = "fa-sort-amount-down-alt"
case sortAmountUp = "fa-sort-amount-up"
case sortAmountUpAlt = "fa-sort-amount-up-alt"
case sortDown = "fa-sort-down"
case sortNumericDown = "fa-sort-numeric-down"
case sortNumericDownAlt = "fa-sort-numeric-down-alt"
case sortNumericUp = "fa-sort-numeric-up"
case sortNumericUpAlt = "fa-sort-numeric-up-alt"
case sortUp = "fa-sort-up"
case soundcloud = "fa-soundcloud"
case sourcetree = "fa-sourcetree"
case spa = "fa-spa"
case spaceShuttle = "fa-space-shuttle"
case speakap = "fa-speakap"
case speakerDeck = "fa-speaker-deck"
case spellCheck = "fa-spell-check"
case spider = "fa-spider"
case spinner = "fa-spinner"
case splotch = "fa-splotch"
case spotify = "fa-spotify"
case sprayCan = "fa-spray-can"
case square = "fa-square"
case squareFull = "fa-square-full"
case squareRootAlt = "fa-square-root-alt"
case squarespace = "fa-squarespace"
case stackExchange = "fa-stack-exchange"
case stackOverflow = "fa-stack-overflow"
case stackpath = "fa-stackpath"
case stamp = "fa-stamp"
case star = "fa-star"
case starAndCrescent = "fa-star-and-crescent"
case starHalf = "fa-star-half"
case starHalfAlt = "fa-star-half-alt"
case starOfDavid = "fa-star-of-david"
case starOfLife = "fa-star-of-life"
case staylinked = "fa-staylinked"
case steam = "fa-steam"
case steamSquare = "fa-steam-square"
case steamSymbol = "fa-steam-symbol"
case stepBackward = "fa-step-backward"
case stepForward = "fa-step-forward"
case stethoscope = "fa-stethoscope"
case stickerMule = "fa-sticker-mule"
case stickyNote = "fa-sticky-note"
case stop = "fa-stop"
case stopCircle = "fa-stop-circle"
case stopwatch = "fa-stopwatch"
case stopwatch20 = "fa-stopwatch-20"
case store = "fa-store"
case storeAlt = "fa-store-alt"
case storeAltSlash = "fa-store-alt-slash"
case storeSlash = "fa-store-slash"
case strava = "fa-strava"
case stream = "fa-stream"
case streetView = "fa-street-view"
case strikethrough = "fa-strikethrough"
case stripe = "fa-stripe"
case stripeS = "fa-stripe-s"
case stroopwafel = "fa-stroopwafel"
case studiovinari = "fa-studiovinari"
case stumbleupon = "fa-stumbleupon"
case stumbleuponCircle = "fa-stumbleupon-circle"
case `subscript` = "fa-subscript"
case subway = "fa-subway"
case suitcase = "fa-suitcase"
case suitcaseRolling = "fa-suitcase-rolling"
case sun = "fa-sun"
case superpowers = "fa-superpowers"
case superscript = "fa-superscript"
case supple = "fa-supple"
case surprise = "fa-surprise"
case suse = "fa-suse"
case swatchbook = "fa-swatchbook"
case swift = "fa-swift"
case swimmer = "fa-swimmer"
case swimmingPool = "fa-swimming-pool"
case symfony = "fa-symfony"
case synagogue = "fa-synagogue"
case sync = "fa-sync"
case syncAlt = "fa-sync-alt"
case syringe = "fa-syringe"
case table = "fa-table"
case tableTennis = "fa-table-tennis"
case tablet = "fa-tablet"
case tabletAlt = "fa-tablet-alt"
case tablets = "fa-tablets"
case tachometerAlt = "fa-tachometer-alt"
case tag = "fa-tag"
case tags = "fa-tags"
case tape = "fa-tape"
case tasks = "fa-tasks"
case taxi = "fa-taxi"
case teamspeak = "fa-teamspeak"
case teeth = "fa-teeth"
case teethOpen = "fa-teeth-open"
case telegram = "fa-telegram"
case telegramPlane = "fa-telegram-plane"
case temperatureHigh = "fa-temperature-high"
case temperatureLow = "fa-temperature-low"
case tencentWeibo = "fa-tencent-weibo"
case tenge = "fa-tenge"
case terminal = "fa-terminal"
case textHeight = "fa-text-height"
case textWidth = "fa-text-width"
case th = "fa-th"
case thLarge = "fa-th-large"
case thList = "fa-th-list"
case theRedYeti = "fa-the-red-yeti"
case theaterMasks = "fa-theater-masks"
case themeco = "fa-themeco"
case themeisle = "fa-themeisle"
case thermometer = "fa-thermometer"
case thermometerEmpty = "fa-thermometer-empty"
case thermometerFull = "fa-thermometer-full"
case thermometerHalf = "fa-thermometer-half"
case thermometerQuarter = "fa-thermometer-quarter"
case thermometerThreeQuarters = "fa-thermometer-three-quarters"
case thinkPeaks = "fa-think-peaks"
case thumbsDown = "fa-thumbs-down"
case thumbsUp = "fa-thumbs-up"
case thumbtack = "fa-thumbtack"
case ticketAlt = "fa-ticket-alt"
case times = "fa-times"
case timesCircle = "fa-times-circle"
case tint = "fa-tint"
case tintSlash = "fa-tint-slash"
case tired = "fa-tired"
case toggleOff = "fa-toggle-off"
case toggleOn = "fa-toggle-on"
case toilet = "fa-toilet"
case toiletPaper = "fa-toilet-paper"
case toiletPaperSlash = "fa-toilet-paper-slash"
case toolbox = "fa-toolbox"
case tools = "fa-tools"
case tooth = "fa-tooth"
case torah = "fa-torah"
case toriiGate = "fa-torii-gate"
case tractor = "fa-tractor"
case tradeFederation = "fa-trade-federation"
case trademark = "fa-trademark"
case trafficLight = "fa-traffic-light"
case trailer = "fa-trailer"
case train = "fa-train"
case tram = "fa-tram"
case transgender = "fa-transgender"
case transgenderAlt = "fa-transgender-alt"
case trash = "fa-trash"
case trashAlt = "fa-trash-alt"
case trashRestore = "fa-trash-restore"
case trashRestoreAlt = "fa-trash-restore-alt"
case tree = "fa-tree"
case trello = "fa-trello"
case tripadvisor = "fa-tripadvisor"
case trophy = "fa-trophy"
case truck = "fa-truck"
case truckLoading = "fa-truck-loading"
case truckMonster = "fa-truck-monster"
case truckMoving = "fa-truck-moving"
case truckPickup = "fa-truck-pickup"
case tshirt = "fa-tshirt"
case tty = "fa-tty"
case tumblr = "fa-tumblr"
case tumblrSquare = "fa-tumblr-square"
case tv = "fa-tv"
case twitch = "fa-twitch"
case twitter = "fa-twitter"
case twitterSquare = "fa-twitter-square"
case typo3 = "fa-typo3"
case uber = "fa-uber"
case ubuntu = "fa-ubuntu"
case uikit = "fa-uikit"
case umbraco = "fa-umbraco"
case umbrella = "fa-umbrella"
case umbrellaBeach = "fa-umbrella-beach"
case underline = "fa-underline"
case undo = "fa-undo"
case undoAlt = "fa-undo-alt"
case uniregistry = "fa-uniregistry"
case unity = "fa-unity"
case universalAccess = "fa-universal-access"
case university = "fa-university"
case unlink = "fa-unlink"
case unlock = "fa-unlock"
case unlockAlt = "fa-unlock-alt"
case untappd = "fa-untappd"
case upload = "fa-upload"
case ups = "fa-ups"
case usb = "fa-usb"
case user = "fa-user"
case userAlt = "fa-user-alt"
case userAltSlash = "fa-user-alt-slash"
case userAstronaut = "fa-user-astronaut"
case userCheck = "fa-user-check"
case userCircle = "fa-user-circle"
case userClock = "fa-user-clock"
case userCog = "fa-user-cog"
case userEdit = "fa-user-edit"
case userFriends = "fa-user-friends"
case userGraduate = "fa-user-graduate"
case userInjured = "fa-user-injured"
case userLock = "fa-user-lock"
case userMd = "fa-user-md"
case userMinus = "fa-user-minus"
case userNinja = "fa-user-ninja"
case userNurse = "fa-user-nurse"
case userPlus = "fa-user-plus"
case userSecret = "fa-user-secret"
case userShield = "fa-user-shield"
case userSlash = "fa-user-slash"
case userTag = "fa-user-tag"
case userTie = "fa-user-tie"
case userTimes = "fa-user-times"
case users = "fa-users"
case usersCog = "fa-users-cog"
case usps = "fa-usps"
case ussunnah = "fa-ussunnah"
case utensilSpoon = "fa-utensil-spoon"
case utensils = "fa-utensils"
case vaadin = "fa-vaadin"
case vectorSquare = "fa-vector-square"
case venus = "fa-venus"
case venusDouble = "fa-venus-double"
case venusMars = "fa-venus-mars"
case viacoin = "fa-viacoin"
case viadeo = "fa-viadeo"
case viadeoSquare = "fa-viadeo-square"
case vial = "fa-vial"
case vials = "fa-vials"
case viber = "fa-viber"
case video = "fa-video"
case videoSlash = "fa-video-slash"
case vihara = "fa-vihara"
case vimeo = "fa-vimeo"
case vimeoSquare = "fa-vimeo-square"
case vimeoV = "fa-vimeo-v"
case vine = "fa-vine"
case virus = "fa-virus"
case virusSlash = "fa-virus-slash"
case viruses = "fa-viruses"
case vk = "fa-vk"
case vnv = "fa-vnv"
case voicemail = "fa-voicemail"
case volleyballBall = "fa-volleyball-ball"
case volumeDown = "fa-volume-down"
case volumeMute = "fa-volume-mute"
case volumeOff = "fa-volume-off"
case volumeUp = "fa-volume-up"
case voteYea = "fa-vote-yea"
case vrCardboard = "fa-vr-cardboard"
case vuejs = "fa-vuejs"
case walking = "fa-walking"
case wallet = "fa-wallet"
case warehouse = "fa-warehouse"
case water = "fa-water"
case waveSquare = "fa-wave-square"
case waze = "fa-waze"
case weebly = "fa-weebly"
case weibo = "fa-weibo"
case weight = "fa-weight"
case weightHanging = "fa-weight-hanging"
case weixin = "fa-weixin"
case whatsapp = "fa-whatsapp"
case whatsappSquare = "fa-whatsapp-square"
case wheelchair = "fa-wheelchair"
case whmcs = "fa-whmcs"
case wifi = "fa-wifi"
case wikipediaW = "fa-wikipedia-w"
case wind = "fa-wind"
case windowClose = "fa-window-close"
case windowMaximize = "fa-window-maximize"
case windowMinimize = "fa-window-minimize"
case windowRestore = "fa-window-restore"
case windows = "fa-windows"
case wineBottle = "fa-wine-bottle"
case wineGlass = "fa-wine-glass"
case wineGlassAlt = "fa-wine-glass-alt"
case wix = "fa-wix"
case wizardsOfTheCoast = "fa-wizards-of-the-coast"
case wolfPackBattalion = "fa-wolf-pack-battalion"
case wonSign = "fa-won-sign"
case wordpress = "fa-wordpress"
case wordpressSimple = "fa-wordpress-simple"
case wpbeginner = "fa-wpbeginner"
case wpexplorer = "fa-wpexplorer"
case wpforms = "fa-wpforms"
case wpressr = "fa-wpressr"
case wrench = "fa-wrench"
case xRay = "fa-x-ray"
case xbox = "fa-xbox"
case xing = "fa-xing"
case xingSquare = "fa-xing-square"
case yCombinator = "fa-y-combinator"
case yahoo = "fa-yahoo"
case yammer = "fa-yammer"
case yandex = "fa-yandex"
case yandexInternational = "fa-yandex-international"
case yarn = "fa-yarn"
case yelp = "fa-yelp"
case yenSign = "fa-yen-sign"
case yinYang = "fa-yin-yang"
case yoast = "fa-yoast"
case youtube = "fa-youtube"
case youtubeSquare = "fa-youtube-square"
case zhihu = "fa-zhihu"
/// An unicode code of FontAwesome icon
public var unicode: String {
switch self {
case .fiveHundredPixels: return "\u{f26e}"
case .accessibleIcon: return "\u{f368}"
case .accusoft: return "\u{f369}"
case .acquisitionsIncorporated: return "\u{f6af}"
case .ad: return "\u{f641}"
case .addressBook: return "\u{f2b9}"
case .addressCard: return "\u{f2bb}"
case .adjust: return "\u{f042}"
case .adn: return "\u{f170}"
case .adobe: return "\u{f778}"
case .adversal: return "\u{f36a}"
case .affiliatetheme: return "\u{f36b}"
case .airFreshener: return "\u{f5d0}"
case .airbnb: return "\u{f834}"
case .algolia: return "\u{f36c}"
case .alignCenter: return "\u{f037}"
case .alignJustify: return "\u{f039}"
case .alignLeft: return "\u{f036}"
case .alignRight: return "\u{f038}"
case .alipay: return "\u{f642}"
case .allergies: return "\u{f461}"
case .amazon: return "\u{f270}"
case .amazonPay: return "\u{f42c}"
case .ambulance: return "\u{f0f9}"
case .americanSignLanguageInterpreting: return "\u{f2a3}"
case .amilia: return "\u{f36d}"
case .anchor: return "\u{f13d}"
case .android: return "\u{f17b}"
case .angellist: return "\u{f209}"
case .angleDoubleDown: return "\u{f103}"
case .angleDoubleLeft: return "\u{f100}"
case .angleDoubleRight: return "\u{f101}"
case .angleDoubleUp: return "\u{f102}"
case .angleDown: return "\u{f107}"
case .angleLeft: return "\u{f104}"
case .angleRight: return "\u{f105}"
case .angleUp: return "\u{f106}"
case .angry: return "\u{f556}"
case .angrycreative: return "\u{f36e}"
case .angular: return "\u{f420}"
case .ankh: return "\u{f644}"
case .appStore: return "\u{f36f}"
case .appStoreIos: return "\u{f370}"
case .apper: return "\u{f371}"
case .apple: return "\u{f179}"
case .appleAlt: return "\u{f5d1}"
case .applePay: return "\u{f415}"
case .archive: return "\u{f187}"
case .archway: return "\u{f557}"
case .arrowAltCircleDown: return "\u{f358}"
case .arrowAltCircleLeft: return "\u{f359}"
case .arrowAltCircleRight: return "\u{f35a}"
case .arrowAltCircleUp: return "\u{f35b}"
case .arrowCircleDown: return "\u{f0ab}"
case .arrowCircleLeft: return "\u{f0a8}"
case .arrowCircleRight: return "\u{f0a9}"
case .arrowCircleUp: return "\u{f0aa}"
case .arrowDown: return "\u{f063}"
case .arrowLeft: return "\u{f060}"
case .arrowRight: return "\u{f061}"
case .arrowUp: return "\u{f062}"
case .arrowsAlt: return "\u{f0b2}"
case .arrowsAltH: return "\u{f337}"
case .arrowsAltV: return "\u{f338}"
case .artstation: return "\u{f77a}"
case .assistiveListeningSystems: return "\u{f2a2}"
case .asterisk: return "\u{f069}"
case .asymmetrik: return "\u{f372}"
case .at: return "\u{f1fa}"
case .atlas: return "\u{f558}"
case .atlassian: return "\u{f77b}"
case .atom: return "\u{f5d2}"
case .audible: return "\u{f373}"
case .audioDescription: return "\u{f29e}"
case .autoprefixer: return "\u{f41c}"
case .avianex: return "\u{f374}"
case .aviato: return "\u{f421}"
case .award: return "\u{f559}"
case .aws: return "\u{f375}"
case .baby: return "\u{f77c}"
case .babyCarriage: return "\u{f77d}"
case .backspace: return "\u{f55a}"
case .backward: return "\u{f04a}"
case .bacon: return "\u{f7e5}"
case .bahai: return "\u{f666}"
case .balanceScale: return "\u{f24e}"
case .balanceScaleLeft: return "\u{f515}"
case .balanceScaleRight: return "\u{f516}"
case .ban: return "\u{f05e}"
case .bandAid: return "\u{f462}"
case .bandcamp: return "\u{f2d5}"
case .barcode: return "\u{f02a}"
case .bars: return "\u{f0c9}"
case .baseballBall: return "\u{f433}"
case .basketballBall: return "\u{f434}"
case .bath: return "\u{f2cd}"
case .batteryEmpty: return "\u{f244}"
case .batteryFull: return "\u{f240}"
case .batteryHalf: return "\u{f242}"
case .batteryQuarter: return "\u{f243}"
case .batteryThreeQuarters: return "\u{f241}"
case .battleNet: return "\u{f835}"
case .bed: return "\u{f236}"
case .beer: return "\u{f0fc}"
case .behance: return "\u{f1b4}"
case .behanceSquare: return "\u{f1b5}"
case .bell: return "\u{f0f3}"
case .bellSlash: return "\u{f1f6}"
case .bezierCurve: return "\u{f55b}"
case .bible: return "\u{f647}"
case .bicycle: return "\u{f206}"
case .biking: return "\u{f84a}"
case .bimobject: return "\u{f378}"
case .binoculars: return "\u{f1e5}"
case .biohazard: return "\u{f780}"
case .birthdayCake: return "\u{f1fd}"
case .bitbucket: return "\u{f171}"
case .bitcoin: return "\u{f379}"
case .bity: return "\u{f37a}"
case .blackTie: return "\u{f27e}"
case .blackberry: return "\u{f37b}"
case .blender: return "\u{f517}"
case .blenderPhone: return "\u{f6b6}"
case .blind: return "\u{f29d}"
case .blog: return "\u{f781}"
case .blogger: return "\u{f37c}"
case .bloggerB: return "\u{f37d}"
case .bluetooth: return "\u{f293}"
case .bluetoothB: return "\u{f294}"
case .bold: return "\u{f032}"
case .bolt: return "\u{f0e7}"
case .bomb: return "\u{f1e2}"
case .bone: return "\u{f5d7}"
case .bong: return "\u{f55c}"
case .book: return "\u{f02d}"
case .bookDead: return "\u{f6b7}"
case .bookMedical: return "\u{f7e6}"
case .bookOpen: return "\u{f518}"
case .bookReader: return "\u{f5da}"
case .bookmark: return "\u{f02e}"
case .bootstrap: return "\u{f836}"
case .borderAll: return "\u{f84c}"
case .borderNone: return "\u{f850}"
case .borderStyle: return "\u{f853}"
case .bowlingBall: return "\u{f436}"
case .box: return "\u{f466}"
case .boxOpen: return "\u{f49e}"
case .boxTissue: return "\u{f95b}"
case .boxes: return "\u{f468}"
case .braille: return "\u{f2a1}"
case .brain: return "\u{f5dc}"
case .breadSlice: return "\u{f7ec}"
case .briefcase: return "\u{f0b1}"
case .briefcaseMedical: return "\u{f469}"
case .broadcastTower: return "\u{f519}"
case .broom: return "\u{f51a}"
case .brush: return "\u{f55d}"
case .btc: return "\u{f15a}"
case .buffer: return "\u{f837}"
case .bug: return "\u{f188}"
case .building: return "\u{f1ad}"
case .bullhorn: return "\u{f0a1}"
case .bullseye: return "\u{f140}"
case .burn: return "\u{f46a}"
case .buromobelexperte: return "\u{f37f}"
case .bus: return "\u{f207}"
case .busAlt: return "\u{f55e}"
case .businessTime: return "\u{f64a}"
case .buyNLarge: return "\u{f8a6}"
case .buysellads: return "\u{f20d}"
case .calculator: return "\u{f1ec}"
case .calendar: return "\u{f133}"
case .calendarAlt: return "\u{f073}"
case .calendarCheck: return "\u{f274}"
case .calendarDay: return "\u{f783}"
case .calendarMinus: return "\u{f272}"
case .calendarPlus: return "\u{f271}"
case .calendarTimes: return "\u{f273}"
case .calendarWeek: return "\u{f784}"
case .camera: return "\u{f030}"
case .cameraRetro: return "\u{f083}"
case .campground: return "\u{f6bb}"
case .canadianMapleLeaf: return "\u{f785}"
case .candyCane: return "\u{f786}"
case .cannabis: return "\u{f55f}"
case .capsules: return "\u{f46b}"
case .car: return "\u{f1b9}"
case .carAlt: return "\u{f5de}"
case .carBattery: return "\u{f5df}"
case .carCrash: return "\u{f5e1}"
case .carSide: return "\u{f5e4}"
case .caravan: return "\u{f8ff}"
case .caretDown: return "\u{f0d7}"
case .caretLeft: return "\u{f0d9}"
case .caretRight: return "\u{f0da}"
case .caretSquareDown: return "\u{f150}"
case .caretSquareLeft: return "\u{f191}"
case .caretSquareRight: return "\u{f152}"
case .caretSquareUp: return "\u{f151}"
case .caretUp: return "\u{f0d8}"
case .carrot: return "\u{f787}"
case .cartArrowDown: return "\u{f218}"
case .cartPlus: return "\u{f217}"
case .cashRegister: return "\u{f788}"
case .cat: return "\u{f6be}"
case .ccAmazonPay: return "\u{f42d}"
case .ccAmex: return "\u{f1f3}"
case .ccApplePay: return "\u{f416}"
case .ccDinersClub: return "\u{f24c}"
case .ccDiscover: return "\u{f1f2}"
case .ccJcb: return "\u{f24b}"
case .ccMastercard: return "\u{f1f1}"
case .ccPaypal: return "\u{f1f4}"
case .ccStripe: return "\u{f1f5}"
case .ccVisa: return "\u{f1f0}"
case .centercode: return "\u{f380}"
case .centos: return "\u{f789}"
case .certificate: return "\u{f0a3}"
case .chair: return "\u{f6c0}"
case .chalkboard: return "\u{f51b}"
case .chalkboardTeacher: return "\u{f51c}"
case .chargingStation: return "\u{f5e7}"
case .chartArea: return "\u{f1fe}"
case .chartBar: return "\u{f080}"
case .chartLine: return "\u{f201}"
case .chartPie: return "\u{f200}"
case .check: return "\u{f00c}"
case .checkCircle: return "\u{f058}"
case .checkDouble: return "\u{f560}"
case .checkSquare: return "\u{f14a}"
case .cheese: return "\u{f7ef}"
case .chess: return "\u{f439}"
case .chessBishop: return "\u{f43a}"
case .chessBoard: return "\u{f43c}"
case .chessKing: return "\u{f43f}"
case .chessKnight: return "\u{f441}"
case .chessPawn: return "\u{f443}"
case .chessQueen: return "\u{f445}"
case .chessRook: return "\u{f447}"
case .chevronCircleDown: return "\u{f13a}"
case .chevronCircleLeft: return "\u{f137}"
case .chevronCircleRight: return "\u{f138}"
case .chevronCircleUp: return "\u{f139}"
case .chevronDown: return "\u{f078}"
case .chevronLeft: return "\u{f053}"
case .chevronRight: return "\u{f054}"
case .chevronUp: return "\u{f077}"
case .child: return "\u{f1ae}"
case .chrome: return "\u{f268}"
case .chromecast: return "\u{f838}"
case .church: return "\u{f51d}"
case .circle: return "\u{f111}"
case .circleNotch: return "\u{f1ce}"
case .city: return "\u{f64f}"
case .clinicMedical: return "\u{f7f2}"
case .clipboard: return "\u{f328}"
case .clipboardCheck: return "\u{f46c}"
case .clipboardList: return "\u{f46d}"
case .clock: return "\u{f017}"
case .clone: return "\u{f24d}"
case .closedCaptioning: return "\u{f20a}"
case .cloud: return "\u{f0c2}"
case .cloudDownloadAlt: return "\u{f381}"
case .cloudMeatball: return "\u{f73b}"
case .cloudMoon: return "\u{f6c3}"
case .cloudMoonRain: return "\u{f73c}"
case .cloudRain: return "\u{f73d}"
case .cloudShowersHeavy: return "\u{f740}"
case .cloudSun: return "\u{f6c4}"
case .cloudSunRain: return "\u{f743}"
case .cloudUploadAlt: return "\u{f382}"
case .cloudscale: return "\u{f383}"
case .cloudsmith: return "\u{f384}"
case .cloudversify: return "\u{f385}"
case .cocktail: return "\u{f561}"
case .code: return "\u{f121}"
case .codeBranch: return "\u{f126}"
case .codepen: return "\u{f1cb}"
case .codiepie: return "\u{f284}"
case .coffee: return "\u{f0f4}"
case .cog: return "\u{f013}"
case .cogs: return "\u{f085}"
case .coins: return "\u{f51e}"
case .columns: return "\u{f0db}"
case .comment: return "\u{f075}"
case .commentAlt: return "\u{f27a}"
case .commentDollar: return "\u{f651}"
case .commentDots: return "\u{f4ad}"
case .commentMedical: return "\u{f7f5}"
case .commentSlash: return "\u{f4b3}"
case .comments: return "\u{f086}"
case .commentsDollar: return "\u{f653}"
case .compactDisc: return "\u{f51f}"
case .compass: return "\u{f14e}"
case .compress: return "\u{f066}"
case .compressAlt: return "\u{f422}"
case .compressArrowsAlt: return "\u{f78c}"
case .conciergeBell: return "\u{f562}"
case .confluence: return "\u{f78d}"
case .connectdevelop: return "\u{f20e}"
case .contao: return "\u{f26d}"
case .cookie: return "\u{f563}"
case .cookieBite: return "\u{f564}"
case .copy: return "\u{f0c5}"
case .copyright: return "\u{f1f9}"
case .cottonBureau: return "\u{f89e}"
case .couch: return "\u{f4b8}"
case .cpanel: return "\u{f388}"
case .creativeCommons: return "\u{f25e}"
case .creativeCommonsBy: return "\u{f4e7}"
case .creativeCommonsNc: return "\u{f4e8}"
case .creativeCommonsNcEu: return "\u{f4e9}"
case .creativeCommonsNcJp: return "\u{f4ea}"
case .creativeCommonsNd: return "\u{f4eb}"
case .creativeCommonsPd: return "\u{f4ec}"
case .creativeCommonsPdAlt: return "\u{f4ed}"
case .creativeCommonsRemix: return "\u{f4ee}"
case .creativeCommonsSa: return "\u{f4ef}"
case .creativeCommonsSampling: return "\u{f4f0}"
case .creativeCommonsSamplingPlus: return "\u{f4f1}"
case .creativeCommonsShare: return "\u{f4f2}"
case .creativeCommonsZero: return "\u{f4f3}"
case .creditCard: return "\u{f09d}"
case .criticalRole: return "\u{f6c9}"
case .crop: return "\u{f125}"
case .cropAlt: return "\u{f565}"
case .cross: return "\u{f654}"
case .crosshairs: return "\u{f05b}"
case .crow: return "\u{f520}"
case .crown: return "\u{f521}"
case .crutch: return "\u{f7f7}"
case .css3: return "\u{f13c}"
case .css3Alt: return "\u{f38b}"
case .cube: return "\u{f1b2}"
case .cubes: return "\u{f1b3}"
case .cut: return "\u{f0c4}"
case .cuttlefish: return "\u{f38c}"
case .dAndD: return "\u{f38d}"
case .dAndDBeyond: return "\u{f6ca}"
case .dailymotion: return "\u{f952}"
case .dashcube: return "\u{f210}"
case .database: return "\u{f1c0}"
case .deaf: return "\u{f2a4}"
case .delicious: return "\u{f1a5}"
case .democrat: return "\u{f747}"
case .deploydog: return "\u{f38e}"
case .deskpro: return "\u{f38f}"
case .desktop: return "\u{f108}"
case .dev: return "\u{f6cc}"
case .deviantart: return "\u{f1bd}"
case .dharmachakra: return "\u{f655}"
case .dhl: return "\u{f790}"
case .diagnoses: return "\u{f470}"
case .diaspora: return "\u{f791}"
case .dice: return "\u{f522}"
case .diceD20: return "\u{f6cf}"
case .diceD6: return "\u{f6d1}"
case .diceFive: return "\u{f523}"
case .diceFour: return "\u{f524}"
case .diceOne: return "\u{f525}"
case .diceSix: return "\u{f526}"
case .diceThree: return "\u{f527}"
case .diceTwo: return "\u{f528}"
case .digg: return "\u{f1a6}"
case .digitalOcean: return "\u{f391}"
case .digitalTachograph: return "\u{f566}"
case .directions: return "\u{f5eb}"
case .discord: return "\u{f392}"
case .discourse: return "\u{f393}"
case .disease: return "\u{f7fa}"
case .divide: return "\u{f529}"
case .dizzy: return "\u{f567}"
case .dna: return "\u{f471}"
case .dochub: return "\u{f394}"
case .docker: return "\u{f395}"
case .dog: return "\u{f6d3}"
case .dollarSign: return "\u{f155}"
case .dolly: return "\u{f472}"
case .dollyFlatbed: return "\u{f474}"
case .donate: return "\u{f4b9}"
case .doorClosed: return "\u{f52a}"
case .doorOpen: return "\u{f52b}"
case .dotCircle: return "\u{f192}"
case .dove: return "\u{f4ba}"
case .download: return "\u{f019}"
case .draft2digital: return "\u{f396}"
case .draftingCompass: return "\u{f568}"
case .dragon: return "\u{f6d5}"
case .drawPolygon: return "\u{f5ee}"
case .dribbble: return "\u{f17d}"
case .dribbbleSquare: return "\u{f397}"
case .dropbox: return "\u{f16b}"
case .drum: return "\u{f569}"
case .drumSteelpan: return "\u{f56a}"
case .drumstickBite: return "\u{f6d7}"
case .drupal: return "\u{f1a9}"
case .dumbbell: return "\u{f44b}"
case .dumpster: return "\u{f793}"
case .dumpsterFire: return "\u{f794}"
case .dungeon: return "\u{f6d9}"
case .dyalog: return "\u{f399}"
case .earlybirds: return "\u{f39a}"
case .ebay: return "\u{f4f4}"
case .edge: return "\u{f282}"
case .edit: return "\u{f044}"
case .egg: return "\u{f7fb}"
case .eject: return "\u{f052}"
case .elementor: return "\u{f430}"
case .ellipsisH: return "\u{f141}"
case .ellipsisV: return "\u{f142}"
case .ello: return "\u{f5f1}"
case .ember: return "\u{f423}"
case .empire: return "\u{f1d1}"
case .envelope: return "\u{f0e0}"
case .envelopeOpen: return "\u{f2b6}"
case .envelopeOpenText: return "\u{f658}"
case .envelopeSquare: return "\u{f199}"
case .envira: return "\u{f299}"
case .equals: return "\u{f52c}"
case .eraser: return "\u{f12d}"
case .erlang: return "\u{f39d}"
case .ethereum: return "\u{f42e}"
case .ethernet: return "\u{f796}"
case .etsy: return "\u{f2d7}"
case .euroSign: return "\u{f153}"
case .evernote: return "\u{f839}"
case .exchangeAlt: return "\u{f362}"
case .exclamation: return "\u{f12a}"
case .exclamationCircle: return "\u{f06a}"
case .exclamationTriangle: return "\u{f071}"
case .expand: return "\u{f065}"
case .expandAlt: return "\u{f424}"
case .expandArrowsAlt: return "\u{f31e}"
case .expeditedssl: return "\u{f23e}"
case .externalLinkAlt: return "\u{f35d}"
case .externalLinkSquareAlt: return "\u{f360}"
case .eye: return "\u{f06e}"
case .eyeDropper: return "\u{f1fb}"
case .eyeSlash: return "\u{f070}"
case .facebook: return "\u{f09a}"
case .facebookF: return "\u{f39e}"
case .facebookMessenger: return "\u{f39f}"
case .facebookSquare: return "\u{f082}"
case .fan: return "\u{f863}"
case .fantasyFlightGames: return "\u{f6dc}"
case .fastBackward: return "\u{f049}"
case .fastForward: return "\u{f050}"
case .faucet: return "\u{f905}"
case .fax: return "\u{f1ac}"
case .feather: return "\u{f52d}"
case .featherAlt: return "\u{f56b}"
case .fedex: return "\u{f797}"
case .fedora: return "\u{f798}"
case .female: return "\u{f182}"
case .fighterJet: return "\u{f0fb}"
case .figma: return "\u{f799}"
case .file: return "\u{f15b}"
case .fileAlt: return "\u{f15c}"
case .fileArchive: return "\u{f1c6}"
case .fileAudio: return "\u{f1c7}"
case .fileCode: return "\u{f1c9}"
case .fileContract: return "\u{f56c}"
case .fileCsv: return "\u{f6dd}"
case .fileDownload: return "\u{f56d}"
case .fileExcel: return "\u{f1c3}"
case .fileExport: return "\u{f56e}"
case .fileImage: return "\u{f1c5}"
case .fileImport: return "\u{f56f}"
case .fileInvoice: return "\u{f570}"
case .fileInvoiceDollar: return "\u{f571}"
case .fileMedical: return "\u{f477}"
case .fileMedicalAlt: return "\u{f478}"
case .filePdf: return "\u{f1c1}"
case .filePowerpoint: return "\u{f1c4}"
case .filePrescription: return "\u{f572}"
case .fileSignature: return "\u{f573}"
case .fileUpload: return "\u{f574}"
case .fileVideo: return "\u{f1c8}"
case .fileWord: return "\u{f1c2}"
case .fill: return "\u{f575}"
case .fillDrip: return "\u{f576}"
case .film: return "\u{f008}"
case .filter: return "\u{f0b0}"
case .fingerprint: return "\u{f577}"
case .fire: return "\u{f06d}"
case .fireAlt: return "\u{f7e4}"
case .fireExtinguisher: return "\u{f134}"
case .firefox: return "\u{f269}"
case .firefoxBrowser: return "\u{f907}"
case .firstAid: return "\u{f479}"
case .firstOrder: return "\u{f2b0}"
case .firstOrderAlt: return "\u{f50a}"
case .firstdraft: return "\u{f3a1}"
case .fish: return "\u{f578}"
case .fistRaised: return "\u{f6de}"
case .flag: return "\u{f024}"
case .flagCheckered: return "\u{f11e}"
case .flagUsa: return "\u{f74d}"
case .flask: return "\u{f0c3}"
case .flickr: return "\u{f16e}"
case .flipboard: return "\u{f44d}"
case .flushed: return "\u{f579}"
case .fly: return "\u{f417}"
case .folder: return "\u{f07b}"
case .folderMinus: return "\u{f65d}"
case .folderOpen: return "\u{f07c}"
case .folderPlus: return "\u{f65e}"
case .font: return "\u{f031}"
case .fontAwesome: return "\u{f2b4}"
case .fontAwesomeAlt: return "\u{f35c}"
case .fontAwesomeFlag: return "\u{f425}"
case .fontAwesomeLogoFull: return "\u{f4e6}"
case .fonticons: return "\u{f280}"
case .fonticonsFi: return "\u{f3a2}"
case .footballBall: return "\u{f44e}"
case .fortAwesome: return "\u{f286}"
case .fortAwesomeAlt: return "\u{f3a3}"
case .forumbee: return "\u{f211}"
case .forward: return "\u{f04e}"
case .foursquare: return "\u{f180}"
case .freeCodeCamp: return "\u{f2c5}"
case .freebsd: return "\u{f3a4}"
case .frog: return "\u{f52e}"
case .frown: return "\u{f119}"
case .frownOpen: return "\u{f57a}"
case .fulcrum: return "\u{f50b}"
case .funnelDollar: return "\u{f662}"
case .futbol: return "\u{f1e3}"
case .galacticRepublic: return "\u{f50c}"
case .galacticSenate: return "\u{f50d}"
case .gamepad: return "\u{f11b}"
case .gasPump: return "\u{f52f}"
case .gavel: return "\u{f0e3}"
case .gem: return "\u{f3a5}"
case .genderless: return "\u{f22d}"
case .getPocket: return "\u{f265}"
case .gg: return "\u{f260}"
case .ggCircle: return "\u{f261}"
case .ghost: return "\u{f6e2}"
case .gift: return "\u{f06b}"
case .gifts: return "\u{f79c}"
case .git: return "\u{f1d3}"
case .gitAlt: return "\u{f841}"
case .gitSquare: return "\u{f1d2}"
case .github: return "\u{f09b}"
case .githubAlt: return "\u{f113}"
case .githubSquare: return "\u{f092}"
case .gitkraken: return "\u{f3a6}"
case .gitlab: return "\u{f296}"
case .gitter: return "\u{f426}"
case .glassCheers: return "\u{f79f}"
case .glassMartini: return "\u{f000}"
case .glassMartiniAlt: return "\u{f57b}"
case .glassWhiskey: return "\u{f7a0}"
case .glasses: return "\u{f530}"
case .glide: return "\u{f2a5}"
case .glideG: return "\u{f2a6}"
case .globe: return "\u{f0ac}"
case .globeAfrica: return "\u{f57c}"
case .globeAmericas: return "\u{f57d}"
case .globeAsia: return "\u{f57e}"
case .globeEurope: return "\u{f7a2}"
case .gofore: return "\u{f3a7}"
case .golfBall: return "\u{f450}"
case .goodreads: return "\u{f3a8}"
case .goodreadsG: return "\u{f3a9}"
case .google: return "\u{f1a0}"
case .googleDrive: return "\u{f3aa}"
case .googlePlay: return "\u{f3ab}"
case .googlePlus: return "\u{f2b3}"
case .googlePlusG: return "\u{f0d5}"
case .googlePlusSquare: return "\u{f0d4}"
case .googleWallet: return "\u{f1ee}"
case .gopuram: return "\u{f664}"
case .graduationCap: return "\u{f19d}"
case .gratipay: return "\u{f184}"
case .grav: return "\u{f2d6}"
case .greaterThan: return "\u{f531}"
case .greaterThanEqual: return "\u{f532}"
case .grimace: return "\u{f57f}"
case .grin: return "\u{f580}"
case .grinAlt: return "\u{f581}"
case .grinBeam: return "\u{f582}"
case .grinBeamSweat: return "\u{f583}"
case .grinHearts: return "\u{f584}"
case .grinSquint: return "\u{f585}"
case .grinSquintTears: return "\u{f586}"
case .grinStars: return "\u{f587}"
case .grinTears: return "\u{f588}"
case .grinTongue: return "\u{f589}"
case .grinTongueSquint: return "\u{f58a}"
case .grinTongueWink: return "\u{f58b}"
case .grinWink: return "\u{f58c}"
case .gripHorizontal: return "\u{f58d}"
case .gripLines: return "\u{f7a4}"
case .gripLinesVertical: return "\u{f7a5}"
case .gripVertical: return "\u{f58e}"
case .gripfire: return "\u{f3ac}"
case .grunt: return "\u{f3ad}"
case .guitar: return "\u{f7a6}"
case .gulp: return "\u{f3ae}"
case .hSquare: return "\u{f0fd}"
case .hackerNews: return "\u{f1d4}"
case .hackerNewsSquare: return "\u{f3af}"
case .hackerrank: return "\u{f5f7}"
case .hamburger: return "\u{f805}"
case .hammer: return "\u{f6e3}"
case .hamsa: return "\u{f665}"
case .handHolding: return "\u{f4bd}"
case .handHoldingHeart: return "\u{f4be}"
case .handHoldingMedical: return "\u{f95c}"
case .handHoldingUsd: return "\u{f4c0}"
case .handHoldingWater: return "\u{f4c1}"
case .handLizard: return "\u{f258}"
case .handMiddleFinger: return "\u{f806}"
case .handPaper: return "\u{f256}"
case .handPeace: return "\u{f25b}"
case .handPointDown: return "\u{f0a7}"
case .handPointLeft: return "\u{f0a5}"
case .handPointRight: return "\u{f0a4}"
case .handPointUp: return "\u{f0a6}"
case .handPointer: return "\u{f25a}"
case .handRock: return "\u{f255}"
case .handScissors: return "\u{f257}"
case .handSparkles: return "\u{f95d}"
case .handSpock: return "\u{f259}"
case .hands: return "\u{f4c2}"
case .handsHelping: return "\u{f4c4}"
case .handsWash: return "\u{f95e}"
case .handshake: return "\u{f2b5}"
case .handshakeAltSlash: return "\u{f95f}"
case .handshakeSlash: return "\u{f960}"
case .hanukiah: return "\u{f6e6}"
case .hardHat: return "\u{f807}"
case .hashtag: return "\u{f292}"
case .hatCowboy: return "\u{f8c0}"
case .hatCowboySide: return "\u{f8c1}"
case .hatWizard: return "\u{f6e8}"
case .hdd: return "\u{f0a0}"
case .headSideCough: return "\u{f961}"
case .headSideCoughSlash: return "\u{f962}"
case .headSideMask: return "\u{f963}"
case .headSideVirus: return "\u{f964}"
case .heading: return "\u{f1dc}"
case .headphones: return "\u{f025}"
case .headphonesAlt: return "\u{f58f}"
case .headset: return "\u{f590}"
case .heart: return "\u{f004}"
case .heartBroken: return "\u{f7a9}"
case .heartbeat: return "\u{f21e}"
case .helicopter: return "\u{f533}"
case .highlighter: return "\u{f591}"
case .hiking: return "\u{f6ec}"
case .hippo: return "\u{f6ed}"
case .hips: return "\u{f452}"
case .hireAHelper: return "\u{f3b0}"
case .history: return "\u{f1da}"
case .hockeyPuck: return "\u{f453}"
case .hollyBerry: return "\u{f7aa}"
case .home: return "\u{f015}"
case .hooli: return "\u{f427}"
case .hornbill: return "\u{f592}"
case .horse: return "\u{f6f0}"
case .horseHead: return "\u{f7ab}"
case .hospital: return "\u{f0f8}"
case .hospitalAlt: return "\u{f47d}"
case .hospitalSymbol: return "\u{f47e}"
case .hospitalUser: return "\u{f80d}"
case .hotTub: return "\u{f593}"
case .hotdog: return "\u{f80f}"
case .hotel: return "\u{f594}"
case .hotjar: return "\u{f3b1}"
case .hourglass: return "\u{f254}"
case .hourglassEnd: return "\u{f253}"
case .hourglassHalf: return "\u{f252}"
case .hourglassStart: return "\u{f251}"
case .houseDamage: return "\u{f6f1}"
case .houseUser: return "\u{f965}"
case .houzz: return "\u{f27c}"
case .hryvnia: return "\u{f6f2}"
case .html5: return "\u{f13b}"
case .hubspot: return "\u{f3b2}"
case .iCursor: return "\u{f246}"
case .iceCream: return "\u{f810}"
case .icicles: return "\u{f7ad}"
case .icons: return "\u{f86d}"
case .idBadge: return "\u{f2c1}"
case .idCard: return "\u{f2c2}"
case .idCardAlt: return "\u{f47f}"
case .ideal: return "\u{f913}"
case .igloo: return "\u{f7ae}"
case .image: return "\u{f03e}"
case .images: return "\u{f302}"
case .imdb: return "\u{f2d8}"
case .inbox: return "\u{f01c}"
case .indent: return "\u{f03c}"
case .industry: return "\u{f275}"
case .infinity: return "\u{f534}"
case .info: return "\u{f129}"
case .infoCircle: return "\u{f05a}"
case .instagram: return "\u{f16d}"
case .instagramSquare: return "\u{f955}"
case .intercom: return "\u{f7af}"
case .internetExplorer: return "\u{f26b}"
case .invision: return "\u{f7b0}"
case .ioxhost: return "\u{f208}"
case .italic: return "\u{f033}"
case .itchIo: return "\u{f83a}"
case .itunes: return "\u{f3b4}"
case .itunesNote: return "\u{f3b5}"
case .java: return "\u{f4e4}"
case .jedi: return "\u{f669}"
case .jediOrder: return "\u{f50e}"
case .jenkins: return "\u{f3b6}"
case .jira: return "\u{f7b1}"
case .joget: return "\u{f3b7}"
case .joint: return "\u{f595}"
case .joomla: return "\u{f1aa}"
case .journalWhills: return "\u{f66a}"
case .js: return "\u{f3b8}"
case .jsSquare: return "\u{f3b9}"
case .jsfiddle: return "\u{f1cc}"
case .kaaba: return "\u{f66b}"
case .kaggle: return "\u{f5fa}"
case .key: return "\u{f084}"
case .keybase: return "\u{f4f5}"
case .keyboard: return "\u{f11c}"
case .keycdn: return "\u{f3ba}"
case .khanda: return "\u{f66d}"
case .kickstarter: return "\u{f3bb}"
case .kickstarterK: return "\u{f3bc}"
case .kiss: return "\u{f596}"
case .kissBeam: return "\u{f597}"
case .kissWinkHeart: return "\u{f598}"
case .kiwiBird: return "\u{f535}"
case .korvue: return "\u{f42f}"
case .landmark: return "\u{f66f}"
case .language: return "\u{f1ab}"
case .laptop: return "\u{f109}"
case .laptopCode: return "\u{f5fc}"
case .laptopHouse: return "\u{f966}"
case .laptopMedical: return "\u{f812}"
case .laravel: return "\u{f3bd}"
case .lastfm: return "\u{f202}"
case .lastfmSquare: return "\u{f203}"
case .laugh: return "\u{f599}"
case .laughBeam: return "\u{f59a}"
case .laughSquint: return "\u{f59b}"
case .laughWink: return "\u{f59c}"
case .layerGroup: return "\u{f5fd}"
case .leaf: return "\u{f06c}"
case .leanpub: return "\u{f212}"
case .lemon: return "\u{f094}"
case .less: return "\u{f41d}"
case .lessThan: return "\u{f536}"
case .lessThanEqual: return "\u{f537}"
case .levelDownAlt: return "\u{f3be}"
case .levelUpAlt: return "\u{f3bf}"
case .lifeRing: return "\u{f1cd}"
case .lightbulb: return "\u{f0eb}"
case .line: return "\u{f3c0}"
case .link: return "\u{f0c1}"
case .linkedin: return "\u{f08c}"
case .linkedinIn: return "\u{f0e1}"
case .linode: return "\u{f2b8}"
case .linux: return "\u{f17c}"
case .liraSign: return "\u{f195}"
case .list: return "\u{f03a}"
case .listAlt: return "\u{f022}"
case .listOl: return "\u{f0cb}"
case .listUl: return "\u{f0ca}"
case .locationArrow: return "\u{f124}"
case .lock: return "\u{f023}"
case .lockOpen: return "\u{f3c1}"
case .longArrowAltDown: return "\u{f309}"
case .longArrowAltLeft: return "\u{f30a}"
case .longArrowAltRight: return "\u{f30b}"
case .longArrowAltUp: return "\u{f30c}"
case .lowVision: return "\u{f2a8}"
case .luggageCart: return "\u{f59d}"
case .lungs: return "\u{f604}"
case .lungsVirus: return "\u{f967}"
case .lyft: return "\u{f3c3}"
case .magento: return "\u{f3c4}"
case .magic: return "\u{f0d0}"
case .magnet: return "\u{f076}"
case .mailBulk: return "\u{f674}"
case .mailchimp: return "\u{f59e}"
case .male: return "\u{f183}"
case .mandalorian: return "\u{f50f}"
case .map: return "\u{f279}"
case .mapMarked: return "\u{f59f}"
case .mapMarkedAlt: return "\u{f5a0}"
case .mapMarker: return "\u{f041}"
case .mapMarkerAlt: return "\u{f3c5}"
case .mapPin: return "\u{f276}"
case .mapSigns: return "\u{f277}"
case .markdown: return "\u{f60f}"
case .marker: return "\u{f5a1}"
case .mars: return "\u{f222}"
case .marsDouble: return "\u{f227}"
case .marsStroke: return "\u{f229}"
case .marsStrokeH: return "\u{f22b}"
case .marsStrokeV: return "\u{f22a}"
case .mask: return "\u{f6fa}"
case .mastodon: return "\u{f4f6}"
case .maxcdn: return "\u{f136}"
case .mdb: return "\u{f8ca}"
case .medal: return "\u{f5a2}"
case .medapps: return "\u{f3c6}"
case .medium: return "\u{f23a}"
case .mediumM: return "\u{f3c7}"
case .medkit: return "\u{f0fa}"
case .medrt: return "\u{f3c8}"
case .meetup: return "\u{f2e0}"
case .megaport: return "\u{f5a3}"
case .meh: return "\u{f11a}"
case .mehBlank: return "\u{f5a4}"
case .mehRollingEyes: return "\u{f5a5}"
case .memory: return "\u{f538}"
case .mendeley: return "\u{f7b3}"
case .menorah: return "\u{f676}"
case .mercury: return "\u{f223}"
case .meteor: return "\u{f753}"
case .microblog: return "\u{f91a}"
case .microchip: return "\u{f2db}"
case .microphone: return "\u{f130}"
case .microphoneAlt: return "\u{f3c9}"
case .microphoneAltSlash: return "\u{f539}"
case .microphoneSlash: return "\u{f131}"
case .microscope: return "\u{f610}"
case .microsoft: return "\u{f3ca}"
case .minus: return "\u{f068}"
case .minusCircle: return "\u{f056}"
case .minusSquare: return "\u{f146}"
case .mitten: return "\u{f7b5}"
case .mix: return "\u{f3cb}"
case .mixcloud: return "\u{f289}"
case .mixer: return "\u{f956}"
case .mizuni: return "\u{f3cc}"
case .mobile: return "\u{f10b}"
case .mobileAlt: return "\u{f3cd}"
case .modx: return "\u{f285}"
case .monero: return "\u{f3d0}"
case .moneyBill: return "\u{f0d6}"
case .moneyBillAlt: return "\u{f3d1}"
case .moneyBillWave: return "\u{f53a}"
case .moneyBillWaveAlt: return "\u{f53b}"
case .moneyCheck: return "\u{f53c}"
case .moneyCheckAlt: return "\u{f53d}"
case .monument: return "\u{f5a6}"
case .moon: return "\u{f186}"
case .mortarPestle: return "\u{f5a7}"
case .mosque: return "\u{f678}"
case .motorcycle: return "\u{f21c}"
case .mountain: return "\u{f6fc}"
case .mouse: return "\u{f8cc}"
case .mousePointer: return "\u{f245}"
case .mugHot: return "\u{f7b6}"
case .music: return "\u{f001}"
case .napster: return "\u{f3d2}"
case .neos: return "\u{f612}"
case .networkWired: return "\u{f6ff}"
case .neuter: return "\u{f22c}"
case .newspaper: return "\u{f1ea}"
case .nimblr: return "\u{f5a8}"
case .node: return "\u{f419}"
case .nodeJs: return "\u{f3d3}"
case .notEqual: return "\u{f53e}"
case .notesMedical: return "\u{f481}"
case .npm: return "\u{f3d4}"
case .ns8: return "\u{f3d5}"
case .nutritionix: return "\u{f3d6}"
case .objectGroup: return "\u{f247}"
case .objectUngroup: return "\u{f248}"
case .odnoklassniki: return "\u{f263}"
case .odnoklassnikiSquare: return "\u{f264}"
case .oilCan: return "\u{f613}"
case .oldRepublic: return "\u{f510}"
case .om: return "\u{f679}"
case .opencart: return "\u{f23d}"
case .openid: return "\u{f19b}"
case .opera: return "\u{f26a}"
case .optinMonster: return "\u{f23c}"
case .orcid: return "\u{f8d2}"
case .osi: return "\u{f41a}"
case .otter: return "\u{f700}"
case .outdent: return "\u{f03b}"
case .page4: return "\u{f3d7}"
case .pagelines: return "\u{f18c}"
case .pager: return "\u{f815}"
case .paintBrush: return "\u{f1fc}"
case .paintRoller: return "\u{f5aa}"
case .palette: return "\u{f53f}"
case .palfed: return "\u{f3d8}"
case .pallet: return "\u{f482}"
case .paperPlane: return "\u{f1d8}"
case .paperclip: return "\u{f0c6}"
case .parachuteBox: return "\u{f4cd}"
case .paragraph: return "\u{f1dd}"
case .parking: return "\u{f540}"
case .passport: return "\u{f5ab}"
case .pastafarianism: return "\u{f67b}"
case .paste: return "\u{f0ea}"
case .patreon: return "\u{f3d9}"
case .pause: return "\u{f04c}"
case .pauseCircle: return "\u{f28b}"
case .paw: return "\u{f1b0}"
case .paypal: return "\u{f1ed}"
case .peace: return "\u{f67c}"
case .pen: return "\u{f304}"
case .penAlt: return "\u{f305}"
case .penFancy: return "\u{f5ac}"
case .penNib: return "\u{f5ad}"
case .penSquare: return "\u{f14b}"
case .pencilAlt: return "\u{f303}"
case .pencilRuler: return "\u{f5ae}"
case .pennyArcade: return "\u{f704}"
case .peopleArrows: return "\u{f968}"
case .peopleCarry: return "\u{f4ce}"
case .pepperHot: return "\u{f816}"
case .percent: return "\u{f295}"
case .percentage: return "\u{f541}"
case .periscope: return "\u{f3da}"
case .personBooth: return "\u{f756}"
case .phabricator: return "\u{f3db}"
case .phoenixFramework: return "\u{f3dc}"
case .phoenixSquadron: return "\u{f511}"
case .phone: return "\u{f095}"
case .phoneAlt: return "\u{f879}"
case .phoneSlash: return "\u{f3dd}"
case .phoneSquare: return "\u{f098}"
case .phoneSquareAlt: return "\u{f87b}"
case .phoneVolume: return "\u{f2a0}"
case .photoVideo: return "\u{f87c}"
case .php: return "\u{f457}"
case .piedPiper: return "\u{f2ae}"
case .piedPiperAlt: return "\u{f1a8}"
case .piedPiperHat: return "\u{f4e5}"
case .piedPiperPp: return "\u{f1a7}"
case .piedPiperSquare: return "\u{f91e}"
case .piggyBank: return "\u{f4d3}"
case .pills: return "\u{f484}"
case .pinterest: return "\u{f0d2}"
case .pinterestP: return "\u{f231}"
case .pinterestSquare: return "\u{f0d3}"
case .pizzaSlice: return "\u{f818}"
case .placeOfWorship: return "\u{f67f}"
case .plane: return "\u{f072}"
case .planeArrival: return "\u{f5af}"
case .planeDeparture: return "\u{f5b0}"
case .planeSlash: return "\u{f969}"
case .play: return "\u{f04b}"
case .playCircle: return "\u{f144}"
case .playstation: return "\u{f3df}"
case .plug: return "\u{f1e6}"
case .plus: return "\u{f067}"
case .plusCircle: return "\u{f055}"
case .plusSquare: return "\u{f0fe}"
case .podcast: return "\u{f2ce}"
case .poll: return "\u{f681}"
case .pollH: return "\u{f682}"
case .poo: return "\u{f2fe}"
case .pooStorm: return "\u{f75a}"
case .poop: return "\u{f619}"
case .portrait: return "\u{f3e0}"
case .poundSign: return "\u{f154}"
case .powerOff: return "\u{f011}"
case .pray: return "\u{f683}"
case .prayingHands: return "\u{f684}"
case .prescription: return "\u{f5b1}"
case .prescriptionBottle: return "\u{f485}"
case .prescriptionBottleAlt: return "\u{f486}"
case .print: return "\u{f02f}"
case .procedures: return "\u{f487}"
case .productHunt: return "\u{f288}"
case .projectDiagram: return "\u{f542}"
case .pumpMedical: return "\u{f96a}"
case .pumpSoap: return "\u{f96b}"
case .pushed: return "\u{f3e1}"
case .puzzlePiece: return "\u{f12e}"
case .python: return "\u{f3e2}"
case .qq: return "\u{f1d6}"
case .qrcode: return "\u{f029}"
case .question: return "\u{f128}"
case .questionCircle: return "\u{f059}"
case .quidditch: return "\u{f458}"
case .quinscape: return "\u{f459}"
case .quora: return "\u{f2c4}"
case .quoteLeft: return "\u{f10d}"
case .quoteRight: return "\u{f10e}"
case .quran: return "\u{f687}"
case .rProject: return "\u{f4f7}"
case .radiation: return "\u{f7b9}"
case .radiationAlt: return "\u{f7ba}"
case .rainbow: return "\u{f75b}"
case .random: return "\u{f074}"
case .raspberryPi: return "\u{f7bb}"
case .ravelry: return "\u{f2d9}"
case .react: return "\u{f41b}"
case .reacteurope: return "\u{f75d}"
case .readme: return "\u{f4d5}"
case .rebel: return "\u{f1d0}"
case .receipt: return "\u{f543}"
case .recordVinyl: return "\u{f8d9}"
case .recycle: return "\u{f1b8}"
case .redRiver: return "\u{f3e3}"
case .reddit: return "\u{f1a1}"
case .redditAlien: return "\u{f281}"
case .redditSquare: return "\u{f1a2}"
case .redhat: return "\u{f7bc}"
case .redo: return "\u{f01e}"
case .redoAlt: return "\u{f2f9}"
case .registered: return "\u{f25d}"
case .removeFormat: return "\u{f87d}"
case .renren: return "\u{f18b}"
case .reply: return "\u{f3e5}"
case .replyAll: return "\u{f122}"
case .replyd: return "\u{f3e6}"
case .republican: return "\u{f75e}"
case .researchgate: return "\u{f4f8}"
case .resolving: return "\u{f3e7}"
case .restroom: return "\u{f7bd}"
case .retweet: return "\u{f079}"
case .rev: return "\u{f5b2}"
case .ribbon: return "\u{f4d6}"
case .ring: return "\u{f70b}"
case .road: return "\u{f018}"
case .robot: return "\u{f544}"
case .rocket: return "\u{f135}"
case .rocketchat: return "\u{f3e8}"
case .rockrms: return "\u{f3e9}"
case .route: return "\u{f4d7}"
case .rss: return "\u{f09e}"
case .rssSquare: return "\u{f143}"
case .rubleSign: return "\u{f158}"
case .ruler: return "\u{f545}"
case .rulerCombined: return "\u{f546}"
case .rulerHorizontal: return "\u{f547}"
case .rulerVertical: return "\u{f548}"
case .running: return "\u{f70c}"
case .rupeeSign: return "\u{f156}"
case .sadCry: return "\u{f5b3}"
case .sadTear: return "\u{f5b4}"
case .safari: return "\u{f267}"
case .salesforce: return "\u{f83b}"
case .sass: return "\u{f41e}"
case .satellite: return "\u{f7bf}"
case .satelliteDish: return "\u{f7c0}"
case .save: return "\u{f0c7}"
case .schlix: return "\u{f3ea}"
case .school: return "\u{f549}"
case .screwdriver: return "\u{f54a}"
case .scribd: return "\u{f28a}"
case .scroll: return "\u{f70e}"
case .sdCard: return "\u{f7c2}"
case .search: return "\u{f002}"
case .searchDollar: return "\u{f688}"
case .searchLocation: return "\u{f689}"
case .searchMinus: return "\u{f010}"
case .searchPlus: return "\u{f00e}"
case .searchengin: return "\u{f3eb}"
case .seedling: return "\u{f4d8}"
case .sellcast: return "\u{f2da}"
case .sellsy: return "\u{f213}"
case .server: return "\u{f233}"
case .servicestack: return "\u{f3ec}"
case .shapes: return "\u{f61f}"
case .share: return "\u{f064}"
case .shareAlt: return "\u{f1e0}"
case .shareAltSquare: return "\u{f1e1}"
case .shareSquare: return "\u{f14d}"
case .shekelSign: return "\u{f20b}"
case .shieldAlt: return "\u{f3ed}"
case .shieldVirus: return "\u{f96c}"
case .ship: return "\u{f21a}"
case .shippingFast: return "\u{f48b}"
case .shirtsinbulk: return "\u{f214}"
case .shoePrints: return "\u{f54b}"
case .shopify: return "\u{f957}"
case .shoppingBag: return "\u{f290}"
case .shoppingBasket: return "\u{f291}"
case .shoppingCart: return "\u{f07a}"
case .shopware: return "\u{f5b5}"
case .shower: return "\u{f2cc}"
case .shuttleVan: return "\u{f5b6}"
case .sign: return "\u{f4d9}"
case .signInAlt: return "\u{f2f6}"
case .signLanguage: return "\u{f2a7}"
case .signOutAlt: return "\u{f2f5}"
case .signal: return "\u{f012}"
case .signature: return "\u{f5b7}"
case .simCard: return "\u{f7c4}"
case .simplybuilt: return "\u{f215}"
case .sistrix: return "\u{f3ee}"
case .sitemap: return "\u{f0e8}"
case .sith: return "\u{f512}"
case .skating: return "\u{f7c5}"
case .sketch: return "\u{f7c6}"
case .skiing: return "\u{f7c9}"
case .skiingNordic: return "\u{f7ca}"
case .skull: return "\u{f54c}"
case .skullCrossbones: return "\u{f714}"
case .skyatlas: return "\u{f216}"
case .skype: return "\u{f17e}"
case .slack: return "\u{f198}"
case .slackHash: return "\u{f3ef}"
case .slash: return "\u{f715}"
case .sleigh: return "\u{f7cc}"
case .slidersH: return "\u{f1de}"
case .slideshare: return "\u{f1e7}"
case .smile: return "\u{f118}"
case .smileBeam: return "\u{f5b8}"
case .smileWink: return "\u{f4da}"
case .smog: return "\u{f75f}"
case .smoking: return "\u{f48d}"
case .smokingBan: return "\u{f54d}"
case .sms: return "\u{f7cd}"
case .snapchat: return "\u{f2ab}"
case .snapchatGhost: return "\u{f2ac}"
case .snapchatSquare: return "\u{f2ad}"
case .snowboarding: return "\u{f7ce}"
case .snowflake: return "\u{f2dc}"
case .snowman: return "\u{f7d0}"
case .snowplow: return "\u{f7d2}"
case .soap: return "\u{f96e}"
case .socks: return "\u{f696}"
case .solarPanel: return "\u{f5ba}"
case .sort: return "\u{f0dc}"
case .sortAlphaDown: return "\u{f15d}"
case .sortAlphaDownAlt: return "\u{f881}"
case .sortAlphaUp: return "\u{f15e}"
case .sortAlphaUpAlt: return "\u{f882}"
case .sortAmountDown: return "\u{f160}"
case .sortAmountDownAlt: return "\u{f884}"
case .sortAmountUp: return "\u{f161}"
case .sortAmountUpAlt: return "\u{f885}"
case .sortDown: return "\u{f0dd}"
case .sortNumericDown: return "\u{f162}"
case .sortNumericDownAlt: return "\u{f886}"
case .sortNumericUp: return "\u{f163}"
case .sortNumericUpAlt: return "\u{f887}"
case .sortUp: return "\u{f0de}"
case .soundcloud: return "\u{f1be}"
case .sourcetree: return "\u{f7d3}"
case .spa: return "\u{f5bb}"
case .spaceShuttle: return "\u{f197}"
case .speakap: return "\u{f3f3}"
case .speakerDeck: return "\u{f83c}"
case .spellCheck: return "\u{f891}"
case .spider: return "\u{f717}"
case .spinner: return "\u{f110}"
case .splotch: return "\u{f5bc}"
case .spotify: return "\u{f1bc}"
case .sprayCan: return "\u{f5bd}"
case .square: return "\u{f0c8}"
case .squareFull: return "\u{f45c}"
case .squareRootAlt: return "\u{f698}"
case .squarespace: return "\u{f5be}"
case .stackExchange: return "\u{f18d}"
case .stackOverflow: return "\u{f16c}"
case .stackpath: return "\u{f842}"
case .stamp: return "\u{f5bf}"
case .star: return "\u{f005}"
case .starAndCrescent: return "\u{f699}"
case .starHalf: return "\u{f089}"
case .starHalfAlt: return "\u{f5c0}"
case .starOfDavid: return "\u{f69a}"
case .starOfLife: return "\u{f621}"
case .staylinked: return "\u{f3f5}"
case .steam: return "\u{f1b6}"
case .steamSquare: return "\u{f1b7}"
case .steamSymbol: return "\u{f3f6}"
case .stepBackward: return "\u{f048}"
case .stepForward: return "\u{f051}"
case .stethoscope: return "\u{f0f1}"
case .stickerMule: return "\u{f3f7}"
case .stickyNote: return "\u{f249}"
case .stop: return "\u{f04d}"
case .stopCircle: return "\u{f28d}"
case .stopwatch: return "\u{f2f2}"
case .stopwatch20: return "\u{f96f}"
case .store: return "\u{f54e}"
case .storeAlt: return "\u{f54f}"
case .storeAltSlash: return "\u{f970}"
case .storeSlash: return "\u{f971}"
case .strava: return "\u{f428}"
case .stream: return "\u{f550}"
case .streetView: return "\u{f21d}"
case .strikethrough: return "\u{f0cc}"
case .stripe: return "\u{f429}"
case .stripeS: return "\u{f42a}"
case .stroopwafel: return "\u{f551}"
case .studiovinari: return "\u{f3f8}"
case .stumbleupon: return "\u{f1a4}"
case .stumbleuponCircle: return "\u{f1a3}"
case .`subscript`: return "\u{f12c}"
case .subway: return "\u{f239}"
case .suitcase: return "\u{f0f2}"
case .suitcaseRolling: return "\u{f5c1}"
case .sun: return "\u{f185}"
case .superpowers: return "\u{f2dd}"
case .superscript: return "\u{f12b}"
case .supple: return "\u{f3f9}"
case .surprise: return "\u{f5c2}"
case .suse: return "\u{f7d6}"
case .swatchbook: return "\u{f5c3}"
case .swift: return "\u{f8e1}"
case .swimmer: return "\u{f5c4}"
case .swimmingPool: return "\u{f5c5}"
case .symfony: return "\u{f83d}"
case .synagogue: return "\u{f69b}"
case .sync: return "\u{f021}"
case .syncAlt: return "\u{f2f1}"
case .syringe: return "\u{f48e}"
case .table: return "\u{f0ce}"
case .tableTennis: return "\u{f45d}"
case .tablet: return "\u{f10a}"
case .tabletAlt: return "\u{f3fa}"
case .tablets: return "\u{f490}"
case .tachometerAlt: return "\u{f3fd}"
case .tag: return "\u{f02b}"
case .tags: return "\u{f02c}"
case .tape: return "\u{f4db}"
case .tasks: return "\u{f0ae}"
case .taxi: return "\u{f1ba}"
case .teamspeak: return "\u{f4f9}"
case .teeth: return "\u{f62e}"
case .teethOpen: return "\u{f62f}"
case .telegram: return "\u{f2c6}"
case .telegramPlane: return "\u{f3fe}"
case .temperatureHigh: return "\u{f769}"
case .temperatureLow: return "\u{f76b}"
case .tencentWeibo: return "\u{f1d5}"
case .tenge: return "\u{f7d7}"
case .terminal: return "\u{f120}"
case .textHeight: return "\u{f034}"
case .textWidth: return "\u{f035}"
case .th: return "\u{f00a}"
case .thLarge: return "\u{f009}"
case .thList: return "\u{f00b}"
case .theRedYeti: return "\u{f69d}"
case .theaterMasks: return "\u{f630}"
case .themeco: return "\u{f5c6}"
case .themeisle: return "\u{f2b2}"
case .thermometer: return "\u{f491}"
case .thermometerEmpty: return "\u{f2cb}"
case .thermometerFull: return "\u{f2c7}"
case .thermometerHalf: return "\u{f2c9}"
case .thermometerQuarter: return "\u{f2ca}"
case .thermometerThreeQuarters: return "\u{f2c8}"
case .thinkPeaks: return "\u{f731}"
case .thumbsDown: return "\u{f165}"
case .thumbsUp: return "\u{f164}"
case .thumbtack: return "\u{f08d}"
case .ticketAlt: return "\u{f3ff}"
case .times: return "\u{f00d}"
case .timesCircle: return "\u{f057}"
case .tint: return "\u{f043}"
case .tintSlash: return "\u{f5c7}"
case .tired: return "\u{f5c8}"
case .toggleOff: return "\u{f204}"
case .toggleOn: return "\u{f205}"
case .toilet: return "\u{f7d8}"
case .toiletPaper: return "\u{f71e}"
case .toiletPaperSlash: return "\u{f972}"
case .toolbox: return "\u{f552}"
case .tools: return "\u{f7d9}"
case .tooth: return "\u{f5c9}"
case .torah: return "\u{f6a0}"
case .toriiGate: return "\u{f6a1}"
case .tractor: return "\u{f722}"
case .tradeFederation: return "\u{f513}"
case .trademark: return "\u{f25c}"
case .trafficLight: return "\u{f637}"
case .trailer: return "\u{f941}"
case .train: return "\u{f238}"
case .tram: return "\u{f7da}"
case .transgender: return "\u{f224}"
case .transgenderAlt: return "\u{f225}"
case .trash: return "\u{f1f8}"
case .trashAlt: return "\u{f2ed}"
case .trashRestore: return "\u{f829}"
case .trashRestoreAlt: return "\u{f82a}"
case .tree: return "\u{f1bb}"
case .trello: return "\u{f181}"
case .tripadvisor: return "\u{f262}"
case .trophy: return "\u{f091}"
case .truck: return "\u{f0d1}"
case .truckLoading: return "\u{f4de}"
case .truckMonster: return "\u{f63b}"
case .truckMoving: return "\u{f4df}"
case .truckPickup: return "\u{f63c}"
case .tshirt: return "\u{f553}"
case .tty: return "\u{f1e4}"
case .tumblr: return "\u{f173}"
case .tumblrSquare: return "\u{f174}"
case .tv: return "\u{f26c}"
case .twitch: return "\u{f1e8}"
case .twitter: return "\u{f099}"
case .twitterSquare: return "\u{f081}"
case .typo3: return "\u{f42b}"
case .uber: return "\u{f402}"
case .ubuntu: return "\u{f7df}"
case .uikit: return "\u{f403}"
case .umbraco: return "\u{f8e8}"
case .umbrella: return "\u{f0e9}"
case .umbrellaBeach: return "\u{f5ca}"
case .underline: return "\u{f0cd}"
case .undo: return "\u{f0e2}"
case .undoAlt: return "\u{f2ea}"
case .uniregistry: return "\u{f404}"
case .unity: return "\u{f949}"
case .universalAccess: return "\u{f29a}"
case .university: return "\u{f19c}"
case .unlink: return "\u{f127}"
case .unlock: return "\u{f09c}"
case .unlockAlt: return "\u{f13e}"
case .untappd: return "\u{f405}"
case .upload: return "\u{f093}"
case .ups: return "\u{f7e0}"
case .usb: return "\u{f287}"
case .user: return "\u{f007}"
case .userAlt: return "\u{f406}"
case .userAltSlash: return "\u{f4fa}"
case .userAstronaut: return "\u{f4fb}"
case .userCheck: return "\u{f4fc}"
case .userCircle: return "\u{f2bd}"
case .userClock: return "\u{f4fd}"
case .userCog: return "\u{f4fe}"
case .userEdit: return "\u{f4ff}"
case .userFriends: return "\u{f500}"
case .userGraduate: return "\u{f501}"
case .userInjured: return "\u{f728}"
case .userLock: return "\u{f502}"
case .userMd: return "\u{f0f0}"
case .userMinus: return "\u{f503}"
case .userNinja: return "\u{f504}"
case .userNurse: return "\u{f82f}"
case .userPlus: return "\u{f234}"
case .userSecret: return "\u{f21b}"
case .userShield: return "\u{f505}"
case .userSlash: return "\u{f506}"
case .userTag: return "\u{f507}"
case .userTie: return "\u{f508}"
case .userTimes: return "\u{f235}"
case .users: return "\u{f0c0}"
case .usersCog: return "\u{f509}"
case .usps: return "\u{f7e1}"
case .ussunnah: return "\u{f407}"
case .utensilSpoon: return "\u{f2e5}"
case .utensils: return "\u{f2e7}"
case .vaadin: return "\u{f408}"
case .vectorSquare: return "\u{f5cb}"
case .venus: return "\u{f221}"
case .venusDouble: return "\u{f226}"
case .venusMars: return "\u{f228}"
case .viacoin: return "\u{f237}"
case .viadeo: return "\u{f2a9}"
case .viadeoSquare: return "\u{f2aa}"
case .vial: return "\u{f492}"
case .vials: return "\u{f493}"
case .viber: return "\u{f409}"
case .video: return "\u{f03d}"
case .videoSlash: return "\u{f4e2}"
case .vihara: return "\u{f6a7}"
case .vimeo: return "\u{f40a}"
case .vimeoSquare: return "\u{f194}"
case .vimeoV: return "\u{f27d}"
case .vine: return "\u{f1ca}"
case .virus: return "\u{f974}"
case .virusSlash: return "\u{f975}"
case .viruses: return "\u{f976}"
case .vk: return "\u{f189}"
case .vnv: return "\u{f40b}"
case .voicemail: return "\u{f897}"
case .volleyballBall: return "\u{f45f}"
case .volumeDown: return "\u{f027}"
case .volumeMute: return "\u{f6a9}"
case .volumeOff: return "\u{f026}"
case .volumeUp: return "\u{f028}"
case .voteYea: return "\u{f772}"
case .vrCardboard: return "\u{f729}"
case .vuejs: return "\u{f41f}"
case .walking: return "\u{f554}"
case .wallet: return "\u{f555}"
case .warehouse: return "\u{f494}"
case .water: return "\u{f773}"
case .waveSquare: return "\u{f83e}"
case .waze: return "\u{f83f}"
case .weebly: return "\u{f5cc}"
case .weibo: return "\u{f18a}"
case .weight: return "\u{f496}"
case .weightHanging: return "\u{f5cd}"
case .weixin: return "\u{f1d7}"
case .whatsapp: return "\u{f232}"
case .whatsappSquare: return "\u{f40c}"
case .wheelchair: return "\u{f193}"
case .whmcs: return "\u{f40d}"
case .wifi: return "\u{f1eb}"
case .wikipediaW: return "\u{f266}"
case .wind: return "\u{f72e}"
case .windowClose: return "\u{f410}"
case .windowMaximize: return "\u{f2d0}"
case .windowMinimize: return "\u{f2d1}"
case .windowRestore: return "\u{f2d2}"
case .windows: return "\u{f17a}"
case .wineBottle: return "\u{f72f}"
case .wineGlass: return "\u{f4e3}"
case .wineGlassAlt: return "\u{f5ce}"
case .wix: return "\u{f5cf}"
case .wizardsOfTheCoast: return "\u{f730}"
case .wolfPackBattalion: return "\u{f514}"
case .wonSign: return "\u{f159}"
case .wordpress: return "\u{f19a}"
case .wordpressSimple: return "\u{f411}"
case .wpbeginner: return "\u{f297}"
case .wpexplorer: return "\u{f2de}"
case .wpforms: return "\u{f298}"
case .wpressr: return "\u{f3e4}"
case .wrench: return "\u{f0ad}"
case .xRay: return "\u{f497}"
case .xbox: return "\u{f412}"
case .xing: return "\u{f168}"
case .xingSquare: return "\u{f169}"
case .yCombinator: return "\u{f23b}"
case .yahoo: return "\u{f19e}"
case .yammer: return "\u{f840}"
case .yandex: return "\u{f413}"
case .yandexInternational: return "\u{f414}"
case .yarn: return "\u{f7e3}"
case .yelp: return "\u{f1e9}"
case .yenSign: return "\u{f157}"
case .yinYang: return "\u{f6ad}"
case .yoast: return "\u{f2b1}"
case .youtube: return "\u{f167}"
case .youtubeSquare: return "\u{f431}"
case .zhihu: return "\u{f63f}"
default: return ""
}
}
/// Supported styles of each FontAwesome font
public var supportedStyles: [FontAwesomeStyle] {
switch self {
case .fiveHundredPixels: return [.brands]
case .accessibleIcon: return [.brands]
case .accusoft: return [.brands]
case .acquisitionsIncorporated: return [.brands]
case .ad: return [.solid]
case .addressBook: return [.solid, .regular]
case .addressCard: return [.solid, .regular]
case .adjust: return [.solid]
case .adn: return [.brands]
case .adobe: return [.brands]
case .adversal: return [.brands]
case .affiliatetheme: return [.brands]
case .airFreshener: return [.solid]
case .airbnb: return [.brands]
case .algolia: return [.brands]
case .alignCenter: return [.solid]
case .alignJustify: return [.solid]
case .alignLeft: return [.solid]
case .alignRight: return [.solid]
case .alipay: return [.brands]
case .allergies: return [.solid]
case .amazon: return [.brands]
case .amazonPay: return [.brands]
case .ambulance: return [.solid]
case .americanSignLanguageInterpreting: return [.solid]
case .amilia: return [.brands]
case .anchor: return [.solid]
case .android: return [.brands]
case .angellist: return [.brands]
case .angleDoubleDown: return [.solid]
case .angleDoubleLeft: return [.solid]
case .angleDoubleRight: return [.solid]
case .angleDoubleUp: return [.solid]
case .angleDown: return [.solid]
case .angleLeft: return [.solid]
case .angleRight: return [.solid]
case .angleUp: return [.solid]
case .angry: return [.solid, .regular]
case .angrycreative: return [.brands]
case .angular: return [.brands]
case .ankh: return [.solid]
case .appStore: return [.brands]
case .appStoreIos: return [.brands]
case .apper: return [.brands]
case .apple: return [.brands]
case .appleAlt: return [.solid]
case .applePay: return [.brands]
case .archive: return [.solid]
case .archway: return [.solid]
case .arrowAltCircleDown: return [.solid, .regular]
case .arrowAltCircleLeft: return [.solid, .regular]
case .arrowAltCircleRight: return [.solid, .regular]
case .arrowAltCircleUp: return [.solid, .regular]
case .arrowCircleDown: return [.solid]
case .arrowCircleLeft: return [.solid]
case .arrowCircleRight: return [.solid]
case .arrowCircleUp: return [.solid]
case .arrowDown: return [.solid]
case .arrowLeft: return [.solid]
case .arrowRight: return [.solid]
case .arrowUp: return [.solid]
case .arrowsAlt: return [.solid]
case .arrowsAltH: return [.solid]
case .arrowsAltV: return [.solid]
case .artstation: return [.brands]
case .assistiveListeningSystems: return [.solid]
case .asterisk: return [.solid]
case .asymmetrik: return [.brands]
case .at: return [.solid]
case .atlas: return [.solid]
case .atlassian: return [.brands]
case .atom: return [.solid]
case .audible: return [.brands]
case .audioDescription: return [.solid]
case .autoprefixer: return [.brands]
case .avianex: return [.brands]
case .aviato: return [.brands]
case .award: return [.solid]
case .aws: return [.brands]
case .baby: return [.solid]
case .babyCarriage: return [.solid]
case .backspace: return [.solid]
case .backward: return [.solid]
case .bacon: return [.solid]
case .bahai: return [.solid]
case .balanceScale: return [.solid]
case .balanceScaleLeft: return [.solid]
case .balanceScaleRight: return [.solid]
case .ban: return [.solid]
case .bandAid: return [.solid]
case .bandcamp: return [.brands]
case .barcode: return [.solid]
case .bars: return [.solid]
case .baseballBall: return [.solid]
case .basketballBall: return [.solid]
case .bath: return [.solid]
case .batteryEmpty: return [.solid]
case .batteryFull: return [.solid]
case .batteryHalf: return [.solid]
case .batteryQuarter: return [.solid]
case .batteryThreeQuarters: return [.solid]
case .battleNet: return [.brands]
case .bed: return [.solid]
case .beer: return [.solid]
case .behance: return [.brands]
case .behanceSquare: return [.brands]
case .bell: return [.solid, .regular]
case .bellSlash: return [.solid, .regular]
case .bezierCurve: return [.solid]
case .bible: return [.solid]
case .bicycle: return [.solid]
case .biking: return [.solid]
case .bimobject: return [.brands]
case .binoculars: return [.solid]
case .biohazard: return [.solid]
case .birthdayCake: return [.solid]
case .bitbucket: return [.brands]
case .bitcoin: return [.brands]
case .bity: return [.brands]
case .blackTie: return [.brands]
case .blackberry: return [.brands]
case .blender: return [.solid]
case .blenderPhone: return [.solid]
case .blind: return [.solid]
case .blog: return [.solid]
case .blogger: return [.brands]
case .bloggerB: return [.brands]
case .bluetooth: return [.brands]
case .bluetoothB: return [.brands]
case .bold: return [.solid]
case .bolt: return [.solid]
case .bomb: return [.solid]
case .bone: return [.solid]
case .bong: return [.solid]
case .book: return [.solid]
case .bookDead: return [.solid]
case .bookMedical: return [.solid]
case .bookOpen: return [.solid]
case .bookReader: return [.solid]
case .bookmark: return [.solid, .regular]
case .bootstrap: return [.brands]
case .borderAll: return [.solid]
case .borderNone: return [.solid]
case .borderStyle: return [.solid]
case .bowlingBall: return [.solid]
case .box: return [.solid]
case .boxOpen: return [.solid]
case .boxTissue: return [.solid]
case .boxes: return [.solid]
case .braille: return [.solid]
case .brain: return [.solid]
case .breadSlice: return [.solid]
case .briefcase: return [.solid]
case .briefcaseMedical: return [.solid]
case .broadcastTower: return [.solid]
case .broom: return [.solid]
case .brush: return [.solid]
case .btc: return [.brands]
case .buffer: return [.brands]
case .bug: return [.solid]
case .building: return [.solid, .regular]
case .bullhorn: return [.solid]
case .bullseye: return [.solid]
case .burn: return [.solid]
case .buromobelexperte: return [.brands]
case .bus: return [.solid]
case .busAlt: return [.solid]
case .businessTime: return [.solid]
case .buyNLarge: return [.brands]
case .buysellads: return [.brands]
case .calculator: return [.solid]
case .calendar: return [.solid, .regular]
case .calendarAlt: return [.solid, .regular]
case .calendarCheck: return [.solid, .regular]
case .calendarDay: return [.solid]
case .calendarMinus: return [.solid, .regular]
case .calendarPlus: return [.solid, .regular]
case .calendarTimes: return [.solid, .regular]
case .calendarWeek: return [.solid]
case .camera: return [.solid]
case .cameraRetro: return [.solid]
case .campground: return [.solid]
case .canadianMapleLeaf: return [.brands]
case .candyCane: return [.solid]
case .cannabis: return [.solid]
case .capsules: return [.solid]
case .car: return [.solid]
case .carAlt: return [.solid]
case .carBattery: return [.solid]
case .carCrash: return [.solid]
case .carSide: return [.solid]
case .caravan: return [.solid]
case .caretDown: return [.solid]
case .caretLeft: return [.solid]
case .caretRight: return [.solid]
case .caretSquareDown: return [.solid, .regular]
case .caretSquareLeft: return [.solid, .regular]
case .caretSquareRight: return [.solid, .regular]
case .caretSquareUp: return [.solid, .regular]
case .caretUp: return [.solid]
case .carrot: return [.solid]
case .cartArrowDown: return [.solid]
case .cartPlus: return [.solid]
case .cashRegister: return [.solid]
case .cat: return [.solid]
case .ccAmazonPay: return [.brands]
case .ccAmex: return [.brands]
case .ccApplePay: return [.brands]
case .ccDinersClub: return [.brands]
case .ccDiscover: return [.brands]
case .ccJcb: return [.brands]
case .ccMastercard: return [.brands]
case .ccPaypal: return [.brands]
case .ccStripe: return [.brands]
case .ccVisa: return [.brands]
case .centercode: return [.brands]
case .centos: return [.brands]
case .certificate: return [.solid]
case .chair: return [.solid]
case .chalkboard: return [.solid]
case .chalkboardTeacher: return [.solid]
case .chargingStation: return [.solid]
case .chartArea: return [.solid]
case .chartBar: return [.solid, .regular]
case .chartLine: return [.solid]
case .chartPie: return [.solid]
case .check: return [.solid]
case .checkCircle: return [.solid, .regular]
case .checkDouble: return [.solid]
case .checkSquare: return [.solid, .regular]
case .cheese: return [.solid]
case .chess: return [.solid]
case .chessBishop: return [.solid]
case .chessBoard: return [.solid]
case .chessKing: return [.solid]
case .chessKnight: return [.solid]
case .chessPawn: return [.solid]
case .chessQueen: return [.solid]
case .chessRook: return [.solid]
case .chevronCircleDown: return [.solid]
case .chevronCircleLeft: return [.solid]
case .chevronCircleRight: return [.solid]
case .chevronCircleUp: return [.solid]
case .chevronDown: return [.solid]
case .chevronLeft: return [.solid]
case .chevronRight: return [.solid]
case .chevronUp: return [.solid]
case .child: return [.solid]
case .chrome: return [.brands]
case .chromecast: return [.brands]
case .church: return [.solid]
case .circle: return [.solid, .regular]
case .circleNotch: return [.solid]
case .city: return [.solid]
case .clinicMedical: return [.solid]
case .clipboard: return [.solid, .regular]
case .clipboardCheck: return [.solid]
case .clipboardList: return [.solid]
case .clock: return [.solid, .regular]
case .clone: return [.solid, .regular]
case .closedCaptioning: return [.solid, .regular]
case .cloud: return [.solid]
case .cloudDownloadAlt: return [.solid]
case .cloudMeatball: return [.solid]
case .cloudMoon: return [.solid]
case .cloudMoonRain: return [.solid]
case .cloudRain: return [.solid]
case .cloudShowersHeavy: return [.solid]
case .cloudSun: return [.solid]
case .cloudSunRain: return [.solid]
case .cloudUploadAlt: return [.solid]
case .cloudscale: return [.brands]
case .cloudsmith: return [.brands]
case .cloudversify: return [.brands]
case .cocktail: return [.solid]
case .code: return [.solid]
case .codeBranch: return [.solid]
case .codepen: return [.brands]
case .codiepie: return [.brands]
case .coffee: return [.solid]
case .cog: return [.solid]
case .cogs: return [.solid]
case .coins: return [.solid]
case .columns: return [.solid]
case .comment: return [.solid, .regular]
case .commentAlt: return [.solid, .regular]
case .commentDollar: return [.solid]
case .commentDots: return [.solid, .regular]
case .commentMedical: return [.solid]
case .commentSlash: return [.solid]
case .comments: return [.solid, .regular]
case .commentsDollar: return [.solid]
case .compactDisc: return [.solid]
case .compass: return [.solid, .regular]
case .compress: return [.solid]
case .compressAlt: return [.solid]
case .compressArrowsAlt: return [.solid]
case .conciergeBell: return [.solid]
case .confluence: return [.brands]
case .connectdevelop: return [.brands]
case .contao: return [.brands]
case .cookie: return [.solid]
case .cookieBite: return [.solid]
case .copy: return [.solid, .regular]
case .copyright: return [.solid, .regular]
case .cottonBureau: return [.brands]
case .couch: return [.solid]
case .cpanel: return [.brands]
case .creativeCommons: return [.brands]
case .creativeCommonsBy: return [.brands]
case .creativeCommonsNc: return [.brands]
case .creativeCommonsNcEu: return [.brands]
case .creativeCommonsNcJp: return [.brands]
case .creativeCommonsNd: return [.brands]
case .creativeCommonsPd: return [.brands]
case .creativeCommonsPdAlt: return [.brands]
case .creativeCommonsRemix: return [.brands]
case .creativeCommonsSa: return [.brands]
case .creativeCommonsSampling: return [.brands]
case .creativeCommonsSamplingPlus: return [.brands]
case .creativeCommonsShare: return [.brands]
case .creativeCommonsZero: return [.brands]
case .creditCard: return [.solid, .regular]
case .criticalRole: return [.brands]
case .crop: return [.solid]
case .cropAlt: return [.solid]
case .cross: return [.solid]
case .crosshairs: return [.solid]
case .crow: return [.solid]
case .crown: return [.solid]
case .crutch: return [.solid]
case .css3: return [.brands]
case .css3Alt: return [.brands]
case .cube: return [.solid]
case .cubes: return [.solid]
case .cut: return [.solid]
case .cuttlefish: return [.brands]
case .dAndD: return [.brands]
case .dAndDBeyond: return [.brands]
case .dailymotion: return [.brands]
case .dashcube: return [.brands]
case .database: return [.solid]
case .deaf: return [.solid]
case .delicious: return [.brands]
case .democrat: return [.solid]
case .deploydog: return [.brands]
case .deskpro: return [.brands]
case .desktop: return [.solid]
case .dev: return [.brands]
case .deviantart: return [.brands]
case .dharmachakra: return [.solid]
case .dhl: return [.brands]
case .diagnoses: return [.solid]
case .diaspora: return [.brands]
case .dice: return [.solid]
case .diceD20: return [.solid]
case .diceD6: return [.solid]
case .diceFive: return [.solid]
case .diceFour: return [.solid]
case .diceOne: return [.solid]
case .diceSix: return [.solid]
case .diceThree: return [.solid]
case .diceTwo: return [.solid]
case .digg: return [.brands]
case .digitalOcean: return [.brands]
case .digitalTachograph: return [.solid]
case .directions: return [.solid]
case .discord: return [.brands]
case .discourse: return [.brands]
case .disease: return [.solid]
case .divide: return [.solid]
case .dizzy: return [.solid, .regular]
case .dna: return [.solid]
case .dochub: return [.brands]
case .docker: return [.brands]
case .dog: return [.solid]
case .dollarSign: return [.solid]
case .dolly: return [.solid]
case .dollyFlatbed: return [.solid]
case .donate: return [.solid]
case .doorClosed: return [.solid]
case .doorOpen: return [.solid]
case .dotCircle: return [.solid, .regular]
case .dove: return [.solid]
case .download: return [.solid]
case .draft2digital: return [.brands]
case .draftingCompass: return [.solid]
case .dragon: return [.solid]
case .drawPolygon: return [.solid]
case .dribbble: return [.brands]
case .dribbbleSquare: return [.brands]
case .dropbox: return [.brands]
case .drum: return [.solid]
case .drumSteelpan: return [.solid]
case .drumstickBite: return [.solid]
case .drupal: return [.brands]
case .dumbbell: return [.solid]
case .dumpster: return [.solid]
case .dumpsterFire: return [.solid]
case .dungeon: return [.solid]
case .dyalog: return [.brands]
case .earlybirds: return [.brands]
case .ebay: return [.brands]
case .edge: return [.brands]
case .edit: return [.solid, .regular]
case .egg: return [.solid]
case .eject: return [.solid]
case .elementor: return [.brands]
case .ellipsisH: return [.solid]
case .ellipsisV: return [.solid]
case .ello: return [.brands]
case .ember: return [.brands]
case .empire: return [.brands]
case .envelope: return [.solid, .regular]
case .envelopeOpen: return [.solid, .regular]
case .envelopeOpenText: return [.solid]
case .envelopeSquare: return [.solid]
case .envira: return [.brands]
case .equals: return [.solid]
case .eraser: return [.solid]
case .erlang: return [.brands]
case .ethereum: return [.brands]
case .ethernet: return [.solid]
case .etsy: return [.brands]
case .euroSign: return [.solid]
case .evernote: return [.brands]
case .exchangeAlt: return [.solid]
case .exclamation: return [.solid]
case .exclamationCircle: return [.solid]
case .exclamationTriangle: return [.solid]
case .expand: return [.solid]
case .expandAlt: return [.solid]
case .expandArrowsAlt: return [.solid]
case .expeditedssl: return [.brands]
case .externalLinkAlt: return [.solid]
case .externalLinkSquareAlt: return [.solid]
case .eye: return [.solid, .regular]
case .eyeDropper: return [.solid]
case .eyeSlash: return [.solid, .regular]
case .facebook: return [.brands]
case .facebookF: return [.brands]
case .facebookMessenger: return [.brands]
case .facebookSquare: return [.brands]
case .fan: return [.solid]
case .fantasyFlightGames: return [.brands]
case .fastBackward: return [.solid]
case .fastForward: return [.solid]
case .faucet: return [.solid]
case .fax: return [.solid]
case .feather: return [.solid]
case .featherAlt: return [.solid]
case .fedex: return [.brands]
case .fedora: return [.brands]
case .female: return [.solid]
case .fighterJet: return [.solid]
case .figma: return [.brands]
case .file: return [.solid, .regular]
case .fileAlt: return [.solid, .regular]
case .fileArchive: return [.solid, .regular]
case .fileAudio: return [.solid, .regular]
case .fileCode: return [.solid, .regular]
case .fileContract: return [.solid]
case .fileCsv: return [.solid]
case .fileDownload: return [.solid]
case .fileExcel: return [.solid, .regular]
case .fileExport: return [.solid]
case .fileImage: return [.solid, .regular]
case .fileImport: return [.solid]
case .fileInvoice: return [.solid]
case .fileInvoiceDollar: return [.solid]
case .fileMedical: return [.solid]
case .fileMedicalAlt: return [.solid]
case .filePdf: return [.solid, .regular]
case .filePowerpoint: return [.solid, .regular]
case .filePrescription: return [.solid]
case .fileSignature: return [.solid]
case .fileUpload: return [.solid]
case .fileVideo: return [.solid, .regular]
case .fileWord: return [.solid, .regular]
case .fill: return [.solid]
case .fillDrip: return [.solid]
case .film: return [.solid]
case .filter: return [.solid]
case .fingerprint: return [.solid]
case .fire: return [.solid]
case .fireAlt: return [.solid]
case .fireExtinguisher: return [.solid]
case .firefox: return [.brands]
case .firefoxBrowser: return [.brands]
case .firstAid: return [.solid]
case .firstOrder: return [.brands]
case .firstOrderAlt: return [.brands]
case .firstdraft: return [.brands]
case .fish: return [.solid]
case .fistRaised: return [.solid]
case .flag: return [.solid, .regular]
case .flagCheckered: return [.solid]
case .flagUsa: return [.solid]
case .flask: return [.solid]
case .flickr: return [.brands]
case .flipboard: return [.brands]
case .flushed: return [.solid, .regular]
case .fly: return [.brands]
case .folder: return [.solid, .regular]
case .folderMinus: return [.solid]
case .folderOpen: return [.solid, .regular]
case .folderPlus: return [.solid]
case .font: return [.solid]
case .fontAwesome: return [.brands]
case .fontAwesomeAlt: return [.brands]
case .fontAwesomeFlag: return [.brands]
case .fontAwesomeLogoFull: return [.regular, .solid, .brands]
case .fonticons: return [.brands]
case .fonticonsFi: return [.brands]
case .footballBall: return [.solid]
case .fortAwesome: return [.brands]
case .fortAwesomeAlt: return [.brands]
case .forumbee: return [.brands]
case .forward: return [.solid]
case .foursquare: return [.brands]
case .freeCodeCamp: return [.brands]
case .freebsd: return [.brands]
case .frog: return [.solid]
case .frown: return [.solid, .regular]
case .frownOpen: return [.solid, .regular]
case .fulcrum: return [.brands]
case .funnelDollar: return [.solid]
case .futbol: return [.solid, .regular]
case .galacticRepublic: return [.brands]
case .galacticSenate: return [.brands]
case .gamepad: return [.solid]
case .gasPump: return [.solid]
case .gavel: return [.solid]
case .gem: return [.solid, .regular]
case .genderless: return [.solid]
case .getPocket: return [.brands]
case .gg: return [.brands]
case .ggCircle: return [.brands]
case .ghost: return [.solid]
case .gift: return [.solid]
case .gifts: return [.solid]
case .git: return [.brands]
case .gitAlt: return [.brands]
case .gitSquare: return [.brands]
case .github: return [.brands]
case .githubAlt: return [.brands]
case .githubSquare: return [.brands]
case .gitkraken: return [.brands]
case .gitlab: return [.brands]
case .gitter: return [.brands]
case .glassCheers: return [.solid]
case .glassMartini: return [.solid]
case .glassMartiniAlt: return [.solid]
case .glassWhiskey: return [.solid]
case .glasses: return [.solid]
case .glide: return [.brands]
case .glideG: return [.brands]
case .globe: return [.solid]
case .globeAfrica: return [.solid]
case .globeAmericas: return [.solid]
case .globeAsia: return [.solid]
case .globeEurope: return [.solid]
case .gofore: return [.brands]
case .golfBall: return [.solid]
case .goodreads: return [.brands]
case .goodreadsG: return [.brands]
case .google: return [.brands]
case .googleDrive: return [.brands]
case .googlePlay: return [.brands]
case .googlePlus: return [.brands]
case .googlePlusG: return [.brands]
case .googlePlusSquare: return [.brands]
case .googleWallet: return [.brands]
case .gopuram: return [.solid]
case .graduationCap: return [.solid]
case .gratipay: return [.brands]
case .grav: return [.brands]
case .greaterThan: return [.solid]
case .greaterThanEqual: return [.solid]
case .grimace: return [.solid, .regular]
case .grin: return [.solid, .regular]
case .grinAlt: return [.solid, .regular]
case .grinBeam: return [.solid, .regular]
case .grinBeamSweat: return [.solid, .regular]
case .grinHearts: return [.solid, .regular]
case .grinSquint: return [.solid, .regular]
case .grinSquintTears: return [.solid, .regular]
case .grinStars: return [.solid, .regular]
case .grinTears: return [.solid, .regular]
case .grinTongue: return [.solid, .regular]
case .grinTongueSquint: return [.solid, .regular]
case .grinTongueWink: return [.solid, .regular]
case .grinWink: return [.solid, .regular]
case .gripHorizontal: return [.solid]
case .gripLines: return [.solid]
case .gripLinesVertical: return [.solid]
case .gripVertical: return [.solid]
case .gripfire: return [.brands]
case .grunt: return [.brands]
case .guitar: return [.solid]
case .gulp: return [.brands]
case .hSquare: return [.solid]
case .hackerNews: return [.brands]
case .hackerNewsSquare: return [.brands]
case .hackerrank: return [.brands]
case .hamburger: return [.solid]
case .hammer: return [.solid]
case .hamsa: return [.solid]
case .handHolding: return [.solid]
case .handHoldingHeart: return [.solid]
case .handHoldingMedical: return [.solid]
case .handHoldingUsd: return [.solid]
case .handHoldingWater: return [.solid]
case .handLizard: return [.solid, .regular]
case .handMiddleFinger: return [.solid]
case .handPaper: return [.solid, .regular]
case .handPeace: return [.solid, .regular]
case .handPointDown: return [.solid, .regular]
case .handPointLeft: return [.solid, .regular]
case .handPointRight: return [.solid, .regular]
case .handPointUp: return [.solid, .regular]
case .handPointer: return [.solid, .regular]
case .handRock: return [.solid, .regular]
case .handScissors: return [.solid, .regular]
case .handSparkles: return [.solid]
case .handSpock: return [.solid, .regular]
case .hands: return [.solid]
case .handsHelping: return [.solid]
case .handsWash: return [.solid]
case .handshake: return [.solid, .regular]
case .handshakeAltSlash: return [.solid]
case .handshakeSlash: return [.solid]
case .hanukiah: return [.solid]
case .hardHat: return [.solid]
case .hashtag: return [.solid]
case .hatCowboy: return [.solid]
case .hatCowboySide: return [.solid]
case .hatWizard: return [.solid]
case .hdd: return [.solid, .regular]
case .headSideCough: return [.solid]
case .headSideCoughSlash: return [.solid]
case .headSideMask: return [.solid]
case .headSideVirus: return [.solid]
case .heading: return [.solid]
case .headphones: return [.solid]
case .headphonesAlt: return [.solid]
case .headset: return [.solid]
case .heart: return [.solid, .regular]
case .heartBroken: return [.solid]
case .heartbeat: return [.solid]
case .helicopter: return [.solid]
case .highlighter: return [.solid]
case .hiking: return [.solid]
case .hippo: return [.solid]
case .hips: return [.brands]
case .hireAHelper: return [.brands]
case .history: return [.solid]
case .hockeyPuck: return [.solid]
case .hollyBerry: return [.solid]
case .home: return [.solid]
case .hooli: return [.brands]
case .hornbill: return [.brands]
case .horse: return [.solid]
case .horseHead: return [.solid]
case .hospital: return [.solid, .regular]
case .hospitalAlt: return [.solid]
case .hospitalSymbol: return [.solid]
case .hospitalUser: return [.solid]
case .hotTub: return [.solid]
case .hotdog: return [.solid]
case .hotel: return [.solid]
case .hotjar: return [.brands]
case .hourglass: return [.solid, .regular]
case .hourglassEnd: return [.solid]
case .hourglassHalf: return [.solid]
case .hourglassStart: return [.solid]
case .houseDamage: return [.solid]
case .houseUser: return [.solid]
case .houzz: return [.brands]
case .hryvnia: return [.solid]
case .html5: return [.brands]
case .hubspot: return [.brands]
case .iCursor: return [.solid]
case .iceCream: return [.solid]
case .icicles: return [.solid]
case .icons: return [.solid]
case .idBadge: return [.solid, .regular]
case .idCard: return [.solid, .regular]
case .idCardAlt: return [.solid]
case .ideal: return [.brands]
case .igloo: return [.solid]
case .image: return [.solid, .regular]
case .images: return [.solid, .regular]
case .imdb: return [.brands]
case .inbox: return [.solid]
case .indent: return [.solid]
case .industry: return [.solid]
case .infinity: return [.solid]
case .info: return [.solid]
case .infoCircle: return [.solid]
case .instagram: return [.brands]
case .instagramSquare: return [.brands]
case .intercom: return [.brands]
case .internetExplorer: return [.brands]
case .invision: return [.brands]
case .ioxhost: return [.brands]
case .italic: return [.solid]
case .itchIo: return [.brands]
case .itunes: return [.brands]
case .itunesNote: return [.brands]
case .java: return [.brands]
case .jedi: return [.solid]
case .jediOrder: return [.brands]
case .jenkins: return [.brands]
case .jira: return [.brands]
case .joget: return [.brands]
case .joint: return [.solid]
case .joomla: return [.brands]
case .journalWhills: return [.solid]
case .js: return [.brands]
case .jsSquare: return [.brands]
case .jsfiddle: return [.brands]
case .kaaba: return [.solid]
case .kaggle: return [.brands]
case .key: return [.solid]
case .keybase: return [.brands]
case .keyboard: return [.solid, .regular]
case .keycdn: return [.brands]
case .khanda: return [.solid]
case .kickstarter: return [.brands]
case .kickstarterK: return [.brands]
case .kiss: return [.solid, .regular]
case .kissBeam: return [.solid, .regular]
case .kissWinkHeart: return [.solid, .regular]
case .kiwiBird: return [.solid]
case .korvue: return [.brands]
case .landmark: return [.solid]
case .language: return [.solid]
case .laptop: return [.solid]
case .laptopCode: return [.solid]
case .laptopHouse: return [.solid]
case .laptopMedical: return [.solid]
case .laravel: return [.brands]
case .lastfm: return [.brands]
case .lastfmSquare: return [.brands]
case .laugh: return [.solid, .regular]
case .laughBeam: return [.solid, .regular]
case .laughSquint: return [.solid, .regular]
case .laughWink: return [.solid, .regular]
case .layerGroup: return [.solid]
case .leaf: return [.solid]
case .leanpub: return [.brands]
case .lemon: return [.solid, .regular]
case .less: return [.brands]
case .lessThan: return [.solid]
case .lessThanEqual: return [.solid]
case .levelDownAlt: return [.solid]
case .levelUpAlt: return [.solid]
case .lifeRing: return [.solid, .regular]
case .lightbulb: return [.solid, .regular]
case .line: return [.brands]
case .link: return [.solid]
case .linkedin: return [.brands]
case .linkedinIn: return [.brands]
case .linode: return [.brands]
case .linux: return [.brands]
case .liraSign: return [.solid]
case .list: return [.solid]
case .listAlt: return [.solid, .regular]
case .listOl: return [.solid]
case .listUl: return [.solid]
case .locationArrow: return [.solid]
case .lock: return [.solid]
case .lockOpen: return [.solid]
case .longArrowAltDown: return [.solid]
case .longArrowAltLeft: return [.solid]
case .longArrowAltRight: return [.solid]
case .longArrowAltUp: return [.solid]
case .lowVision: return [.solid]
case .luggageCart: return [.solid]
case .lungs: return [.solid]
case .lungsVirus: return [.solid]
case .lyft: return [.brands]
case .magento: return [.brands]
case .magic: return [.solid]
case .magnet: return [.solid]
case .mailBulk: return [.solid]
case .mailchimp: return [.brands]
case .male: return [.solid]
case .mandalorian: return [.brands]
case .map: return [.solid, .regular]
case .mapMarked: return [.solid]
case .mapMarkedAlt: return [.solid]
case .mapMarker: return [.solid]
case .mapMarkerAlt: return [.solid]
case .mapPin: return [.solid]
case .mapSigns: return [.solid]
case .markdown: return [.brands]
case .marker: return [.solid]
case .mars: return [.solid]
case .marsDouble: return [.solid]
case .marsStroke: return [.solid]
case .marsStrokeH: return [.solid]
case .marsStrokeV: return [.solid]
case .mask: return [.solid]
case .mastodon: return [.brands]
case .maxcdn: return [.brands]
case .mdb: return [.brands]
case .medal: return [.solid]
case .medapps: return [.brands]
case .medium: return [.brands]
case .mediumM: return [.brands]
case .medkit: return [.solid]
case .medrt: return [.brands]
case .meetup: return [.brands]
case .megaport: return [.brands]
case .meh: return [.solid, .regular]
case .mehBlank: return [.solid, .regular]
case .mehRollingEyes: return [.solid, .regular]
case .memory: return [.solid]
case .mendeley: return [.brands]
case .menorah: return [.solid]
case .mercury: return [.solid]
case .meteor: return [.solid]
case .microblog: return [.brands]
case .microchip: return [.solid]
case .microphone: return [.solid]
case .microphoneAlt: return [.solid]
case .microphoneAltSlash: return [.solid]
case .microphoneSlash: return [.solid]
case .microscope: return [.solid]
case .microsoft: return [.brands]
case .minus: return [.solid]
case .minusCircle: return [.solid]
case .minusSquare: return [.solid, .regular]
case .mitten: return [.solid]
case .mix: return [.brands]
case .mixcloud: return [.brands]
case .mixer: return [.brands]
case .mizuni: return [.brands]
case .mobile: return [.solid]
case .mobileAlt: return [.solid]
case .modx: return [.brands]
case .monero: return [.brands]
case .moneyBill: return [.solid]
case .moneyBillAlt: return [.solid, .regular]
case .moneyBillWave: return [.solid]
case .moneyBillWaveAlt: return [.solid]
case .moneyCheck: return [.solid]
case .moneyCheckAlt: return [.solid]
case .monument: return [.solid]
case .moon: return [.solid, .regular]
case .mortarPestle: return [.solid]
case .mosque: return [.solid]
case .motorcycle: return [.solid]
case .mountain: return [.solid]
case .mouse: return [.solid]
case .mousePointer: return [.solid]
case .mugHot: return [.solid]
case .music: return [.solid]
case .napster: return [.brands]
case .neos: return [.brands]
case .networkWired: return [.solid]
case .neuter: return [.solid]
case .newspaper: return [.solid, .regular]
case .nimblr: return [.brands]
case .node: return [.brands]
case .nodeJs: return [.brands]
case .notEqual: return [.solid]
case .notesMedical: return [.solid]
case .npm: return [.brands]
case .ns8: return [.brands]
case .nutritionix: return [.brands]
case .objectGroup: return [.solid, .regular]
case .objectUngroup: return [.solid, .regular]
case .odnoklassniki: return [.brands]
case .odnoklassnikiSquare: return [.brands]
case .oilCan: return [.solid]
case .oldRepublic: return [.brands]
case .om: return [.solid]
case .opencart: return [.brands]
case .openid: return [.brands]
case .opera: return [.brands]
case .optinMonster: return [.brands]
case .orcid: return [.brands]
case .osi: return [.brands]
case .otter: return [.solid]
case .outdent: return [.solid]
case .page4: return [.brands]
case .pagelines: return [.brands]
case .pager: return [.solid]
case .paintBrush: return [.solid]
case .paintRoller: return [.solid]
case .palette: return [.solid]
case .palfed: return [.brands]
case .pallet: return [.solid]
case .paperPlane: return [.solid, .regular]
case .paperclip: return [.solid]
case .parachuteBox: return [.solid]
case .paragraph: return [.solid]
case .parking: return [.solid]
case .passport: return [.solid]
case .pastafarianism: return [.solid]
case .paste: return [.solid]
case .patreon: return [.brands]
case .pause: return [.solid]
case .pauseCircle: return [.solid, .regular]
case .paw: return [.solid]
case .paypal: return [.brands]
case .peace: return [.solid]
case .pen: return [.solid]
case .penAlt: return [.solid]
case .penFancy: return [.solid]
case .penNib: return [.solid]
case .penSquare: return [.solid]
case .pencilAlt: return [.solid]
case .pencilRuler: return [.solid]
case .pennyArcade: return [.brands]
case .peopleArrows: return [.solid]
case .peopleCarry: return [.solid]
case .pepperHot: return [.solid]
case .percent: return [.solid]
case .percentage: return [.solid]
case .periscope: return [.brands]
case .personBooth: return [.solid]
case .phabricator: return [.brands]
case .phoenixFramework: return [.brands]
case .phoenixSquadron: return [.brands]
case .phone: return [.solid]
case .phoneAlt: return [.solid]
case .phoneSlash: return [.solid]
case .phoneSquare: return [.solid]
case .phoneSquareAlt: return [.solid]
case .phoneVolume: return [.solid]
case .photoVideo: return [.solid]
case .php: return [.brands]
case .piedPiper: return [.brands]
case .piedPiperAlt: return [.brands]
case .piedPiperHat: return [.brands]
case .piedPiperPp: return [.brands]
case .piedPiperSquare: return [.brands]
case .piggyBank: return [.solid]
case .pills: return [.solid]
case .pinterest: return [.brands]
case .pinterestP: return [.brands]
case .pinterestSquare: return [.brands]
case .pizzaSlice: return [.solid]
case .placeOfWorship: return [.solid]
case .plane: return [.solid]
case .planeArrival: return [.solid]
case .planeDeparture: return [.solid]
case .planeSlash: return [.solid]
case .play: return [.solid]
case .playCircle: return [.solid, .regular]
case .playstation: return [.brands]
case .plug: return [.solid]
case .plus: return [.solid]
case .plusCircle: return [.solid]
case .plusSquare: return [.solid, .regular]
case .podcast: return [.solid]
case .poll: return [.solid]
case .pollH: return [.solid]
case .poo: return [.solid]
case .pooStorm: return [.solid]
case .poop: return [.solid]
case .portrait: return [.solid]
case .poundSign: return [.solid]
case .powerOff: return [.solid]
case .pray: return [.solid]
case .prayingHands: return [.solid]
case .prescription: return [.solid]
case .prescriptionBottle: return [.solid]
case .prescriptionBottleAlt: return [.solid]
case .print: return [.solid]
case .procedures: return [.solid]
case .productHunt: return [.brands]
case .projectDiagram: return [.solid]
case .pumpMedical: return [.solid]
case .pumpSoap: return [.solid]
case .pushed: return [.brands]
case .puzzlePiece: return [.solid]
case .python: return [.brands]
case .qq: return [.brands]
case .qrcode: return [.solid]
case .question: return [.solid]
case .questionCircle: return [.solid, .regular]
case .quidditch: return [.solid]
case .quinscape: return [.brands]
case .quora: return [.brands]
case .quoteLeft: return [.solid]
case .quoteRight: return [.solid]
case .quran: return [.solid]
case .rProject: return [.brands]
case .radiation: return [.solid]
case .radiationAlt: return [.solid]
case .rainbow: return [.solid]
case .random: return [.solid]
case .raspberryPi: return [.brands]
case .ravelry: return [.brands]
case .react: return [.brands]
case .reacteurope: return [.brands]
case .readme: return [.brands]
case .rebel: return [.brands]
case .receipt: return [.solid]
case .recordVinyl: return [.solid]
case .recycle: return [.solid]
case .redRiver: return [.brands]
case .reddit: return [.brands]
case .redditAlien: return [.brands]
case .redditSquare: return [.brands]
case .redhat: return [.brands]
case .redo: return [.solid]
case .redoAlt: return [.solid]
case .registered: return [.solid, .regular]
case .removeFormat: return [.solid]
case .renren: return [.brands]
case .reply: return [.solid]
case .replyAll: return [.solid]
case .replyd: return [.brands]
case .republican: return [.solid]
case .researchgate: return [.brands]
case .resolving: return [.brands]
case .restroom: return [.solid]
case .retweet: return [.solid]
case .rev: return [.brands]
case .ribbon: return [.solid]
case .ring: return [.solid]
case .road: return [.solid]
case .robot: return [.solid]
case .rocket: return [.solid]
case .rocketchat: return [.brands]
case .rockrms: return [.brands]
case .route: return [.solid]
case .rss: return [.solid]
case .rssSquare: return [.solid]
case .rubleSign: return [.solid]
case .ruler: return [.solid]
case .rulerCombined: return [.solid]
case .rulerHorizontal: return [.solid]
case .rulerVertical: return [.solid]
case .running: return [.solid]
case .rupeeSign: return [.solid]
case .sadCry: return [.solid, .regular]
case .sadTear: return [.solid, .regular]
case .safari: return [.brands]
case .salesforce: return [.brands]
case .sass: return [.brands]
case .satellite: return [.solid]
case .satelliteDish: return [.solid]
case .save: return [.solid, .regular]
case .schlix: return [.brands]
case .school: return [.solid]
case .screwdriver: return [.solid]
case .scribd: return [.brands]
case .scroll: return [.solid]
case .sdCard: return [.solid]
case .search: return [.solid]
case .searchDollar: return [.solid]
case .searchLocation: return [.solid]
case .searchMinus: return [.solid]
case .searchPlus: return [.solid]
case .searchengin: return [.brands]
case .seedling: return [.solid]
case .sellcast: return [.brands]
case .sellsy: return [.brands]
case .server: return [.solid]
case .servicestack: return [.brands]
case .shapes: return [.solid]
case .share: return [.solid]
case .shareAlt: return [.solid]
case .shareAltSquare: return [.solid]
case .shareSquare: return [.solid, .regular]
case .shekelSign: return [.solid]
case .shieldAlt: return [.solid]
case .shieldVirus: return [.solid]
case .ship: return [.solid]
case .shippingFast: return [.solid]
case .shirtsinbulk: return [.brands]
case .shoePrints: return [.solid]
case .shopify: return [.brands]
case .shoppingBag: return [.solid]
case .shoppingBasket: return [.solid]
case .shoppingCart: return [.solid]
case .shopware: return [.brands]
case .shower: return [.solid]
case .shuttleVan: return [.solid]
case .sign: return [.solid]
case .signInAlt: return [.solid]
case .signLanguage: return [.solid]
case .signOutAlt: return [.solid]
case .signal: return [.solid]
case .signature: return [.solid]
case .simCard: return [.solid]
case .simplybuilt: return [.brands]
case .sistrix: return [.brands]
case .sitemap: return [.solid]
case .sith: return [.brands]
case .skating: return [.solid]
case .sketch: return [.brands]
case .skiing: return [.solid]
case .skiingNordic: return [.solid]
case .skull: return [.solid]
case .skullCrossbones: return [.solid]
case .skyatlas: return [.brands]
case .skype: return [.brands]
case .slack: return [.brands]
case .slackHash: return [.brands]
case .slash: return [.solid]
case .sleigh: return [.solid]
case .slidersH: return [.solid]
case .slideshare: return [.brands]
case .smile: return [.solid, .regular]
case .smileBeam: return [.solid, .regular]
case .smileWink: return [.solid, .regular]
case .smog: return [.solid]
case .smoking: return [.solid]
case .smokingBan: return [.solid]
case .sms: return [.solid]
case .snapchat: return [.brands]
case .snapchatGhost: return [.brands]
case .snapchatSquare: return [.brands]
case .snowboarding: return [.solid]
case .snowflake: return [.solid, .regular]
case .snowman: return [.solid]
case .snowplow: return [.solid]
case .soap: return [.solid]
case .socks: return [.solid]
case .solarPanel: return [.solid]
case .sort: return [.solid]
case .sortAlphaDown: return [.solid]
case .sortAlphaDownAlt: return [.solid]
case .sortAlphaUp: return [.solid]
case .sortAlphaUpAlt: return [.solid]
case .sortAmountDown: return [.solid]
case .sortAmountDownAlt: return [.solid]
case .sortAmountUp: return [.solid]
case .sortAmountUpAlt: return [.solid]
case .sortDown: return [.solid]
case .sortNumericDown: return [.solid]
case .sortNumericDownAlt: return [.solid]
case .sortNumericUp: return [.solid]
case .sortNumericUpAlt: return [.solid]
case .sortUp: return [.solid]
case .soundcloud: return [.brands]
case .sourcetree: return [.brands]
case .spa: return [.solid]
case .spaceShuttle: return [.solid]
case .speakap: return [.brands]
case .speakerDeck: return [.brands]
case .spellCheck: return [.solid]
case .spider: return [.solid]
case .spinner: return [.solid]
case .splotch: return [.solid]
case .spotify: return [.brands]
case .sprayCan: return [.solid]
case .square: return [.solid, .regular]
case .squareFull: return [.solid]
case .squareRootAlt: return [.solid]
case .squarespace: return [.brands]
case .stackExchange: return [.brands]
case .stackOverflow: return [.brands]
case .stackpath: return [.brands]
case .stamp: return [.solid]
case .star: return [.solid, .regular]
case .starAndCrescent: return [.solid]
case .starHalf: return [.solid, .regular]
case .starHalfAlt: return [.solid]
case .starOfDavid: return [.solid]
case .starOfLife: return [.solid]
case .staylinked: return [.brands]
case .steam: return [.brands]
case .steamSquare: return [.brands]
case .steamSymbol: return [.brands]
case .stepBackward: return [.solid]
case .stepForward: return [.solid]
case .stethoscope: return [.solid]
case .stickerMule: return [.brands]
case .stickyNote: return [.solid, .regular]
case .stop: return [.solid]
case .stopCircle: return [.solid, .regular]
case .stopwatch: return [.solid]
case .stopwatch20: return [.solid]
case .store: return [.solid]
case .storeAlt: return [.solid]
case .storeAltSlash: return [.solid]
case .storeSlash: return [.solid]
case .strava: return [.brands]
case .stream: return [.solid]
case .streetView: return [.solid]
case .strikethrough: return [.solid]
case .stripe: return [.brands]
case .stripeS: return [.brands]
case .stroopwafel: return [.solid]
case .studiovinari: return [.brands]
case .stumbleupon: return [.brands]
case .stumbleuponCircle: return [.brands]
case .`subscript`: return [.solid]
case .subway: return [.solid]
case .suitcase: return [.solid]
case .suitcaseRolling: return [.solid]
case .sun: return [.solid, .regular]
case .superpowers: return [.brands]
case .superscript: return [.solid]
case .supple: return [.brands]
case .surprise: return [.solid, .regular]
case .suse: return [.brands]
case .swatchbook: return [.solid]
case .swift: return [.brands]
case .swimmer: return [.solid]
case .swimmingPool: return [.solid]
case .symfony: return [.brands]
case .synagogue: return [.solid]
case .sync: return [.solid]
case .syncAlt: return [.solid]
case .syringe: return [.solid]
case .table: return [.solid]
case .tableTennis: return [.solid]
case .tablet: return [.solid]
case .tabletAlt: return [.solid]
case .tablets: return [.solid]
case .tachometerAlt: return [.solid]
case .tag: return [.solid]
case .tags: return [.solid]
case .tape: return [.solid]
case .tasks: return [.solid]
case .taxi: return [.solid]
case .teamspeak: return [.brands]
case .teeth: return [.solid]
case .teethOpen: return [.solid]
case .telegram: return [.brands]
case .telegramPlane: return [.brands]
case .temperatureHigh: return [.solid]
case .temperatureLow: return [.solid]
case .tencentWeibo: return [.brands]
case .tenge: return [.solid]
case .terminal: return [.solid]
case .textHeight: return [.solid]
case .textWidth: return [.solid]
case .th: return [.solid]
case .thLarge: return [.solid]
case .thList: return [.solid]
case .theRedYeti: return [.brands]
case .theaterMasks: return [.solid]
case .themeco: return [.brands]
case .themeisle: return [.brands]
case .thermometer: return [.solid]
case .thermometerEmpty: return [.solid]
case .thermometerFull: return [.solid]
case .thermometerHalf: return [.solid]
case .thermometerQuarter: return [.solid]
case .thermometerThreeQuarters: return [.solid]
case .thinkPeaks: return [.brands]
case .thumbsDown: return [.solid, .regular]
case .thumbsUp: return [.solid, .regular]
case .thumbtack: return [.solid]
case .ticketAlt: return [.solid]
case .times: return [.solid]
case .timesCircle: return [.solid, .regular]
case .tint: return [.solid]
case .tintSlash: return [.solid]
case .tired: return [.solid, .regular]
case .toggleOff: return [.solid]
case .toggleOn: return [.solid]
case .toilet: return [.solid]
case .toiletPaper: return [.solid]
case .toiletPaperSlash: return [.solid]
case .toolbox: return [.solid]
case .tools: return [.solid]
case .tooth: return [.solid]
case .torah: return [.solid]
case .toriiGate: return [.solid]
case .tractor: return [.solid]
case .tradeFederation: return [.brands]
case .trademark: return [.solid]
case .trafficLight: return [.solid]
case .trailer: return [.solid]
case .train: return [.solid]
case .tram: return [.solid]
case .transgender: return [.solid]
case .transgenderAlt: return [.solid]
case .trash: return [.solid]
case .trashAlt: return [.solid, .regular]
case .trashRestore: return [.solid]
case .trashRestoreAlt: return [.solid]
case .tree: return [.solid]
case .trello: return [.brands]
case .tripadvisor: return [.brands]
case .trophy: return [.solid]
case .truck: return [.solid]
case .truckLoading: return [.solid]
case .truckMonster: return [.solid]
case .truckMoving: return [.solid]
case .truckPickup: return [.solid]
case .tshirt: return [.solid]
case .tty: return [.solid]
case .tumblr: return [.brands]
case .tumblrSquare: return [.brands]
case .tv: return [.solid]
case .twitch: return [.brands]
case .twitter: return [.brands]
case .twitterSquare: return [.brands]
case .typo3: return [.brands]
case .uber: return [.brands]
case .ubuntu: return [.brands]
case .uikit: return [.brands]
case .umbraco: return [.brands]
case .umbrella: return [.solid]
case .umbrellaBeach: return [.solid]
case .underline: return [.solid]
case .undo: return [.solid]
case .undoAlt: return [.solid]
case .uniregistry: return [.brands]
case .unity: return [.brands]
case .universalAccess: return [.solid]
case .university: return [.solid]
case .unlink: return [.solid]
case .unlock: return [.solid]
case .unlockAlt: return [.solid]
case .untappd: return [.brands]
case .upload: return [.solid]
case .ups: return [.brands]
case .usb: return [.brands]
case .user: return [.solid, .regular]
case .userAlt: return [.solid]
case .userAltSlash: return [.solid]
case .userAstronaut: return [.solid]
case .userCheck: return [.solid]
case .userCircle: return [.solid, .regular]
case .userClock: return [.solid]
case .userCog: return [.solid]
case .userEdit: return [.solid]
case .userFriends: return [.solid]
case .userGraduate: return [.solid]
case .userInjured: return [.solid]
case .userLock: return [.solid]
case .userMd: return [.solid]
case .userMinus: return [.solid]
case .userNinja: return [.solid]
case .userNurse: return [.solid]
case .userPlus: return [.solid]
case .userSecret: return [.solid]
case .userShield: return [.solid]
case .userSlash: return [.solid]
case .userTag: return [.solid]
case .userTie: return [.solid]
case .userTimes: return [.solid]
case .users: return [.solid]
case .usersCog: return [.solid]
case .usps: return [.brands]
case .ussunnah: return [.brands]
case .utensilSpoon: return [.solid]
case .utensils: return [.solid]
case .vaadin: return [.brands]
case .vectorSquare: return [.solid]
case .venus: return [.solid]
case .venusDouble: return [.solid]
case .venusMars: return [.solid]
case .viacoin: return [.brands]
case .viadeo: return [.brands]
case .viadeoSquare: return [.brands]
case .vial: return [.solid]
case .vials: return [.solid]
case .viber: return [.brands]
case .video: return [.solid]
case .videoSlash: return [.solid]
case .vihara: return [.solid]
case .vimeo: return [.brands]
case .vimeoSquare: return [.brands]
case .vimeoV: return [.brands]
case .vine: return [.brands]
case .virus: return [.solid]
case .virusSlash: return [.solid]
case .viruses: return [.solid]
case .vk: return [.brands]
case .vnv: return [.brands]
case .voicemail: return [.solid]
case .volleyballBall: return [.solid]
case .volumeDown: return [.solid]
case .volumeMute: return [.solid]
case .volumeOff: return [.solid]
case .volumeUp: return [.solid]
case .voteYea: return [.solid]
case .vrCardboard: return [.solid]
case .vuejs: return [.brands]
case .walking: return [.solid]
case .wallet: return [.solid]
case .warehouse: return [.solid]
case .water: return [.solid]
case .waveSquare: return [.solid]
case .waze: return [.brands]
case .weebly: return [.brands]
case .weibo: return [.brands]
case .weight: return [.solid]
case .weightHanging: return [.solid]
case .weixin: return [.brands]
case .whatsapp: return [.brands]
case .whatsappSquare: return [.brands]
case .wheelchair: return [.solid]
case .whmcs: return [.brands]
case .wifi: return [.solid]
case .wikipediaW: return [.brands]
case .wind: return [.solid]
case .windowClose: return [.solid, .regular]
case .windowMaximize: return [.solid, .regular]
case .windowMinimize: return [.solid, .regular]
case .windowRestore: return [.solid, .regular]
case .windows: return [.brands]
case .wineBottle: return [.solid]
case .wineGlass: return [.solid]
case .wineGlassAlt: return [.solid]
case .wix: return [.brands]
case .wizardsOfTheCoast: return [.brands]
case .wolfPackBattalion: return [.brands]
case .wonSign: return [.solid]
case .wordpress: return [.brands]
case .wordpressSimple: return [.brands]
case .wpbeginner: return [.brands]
case .wpexplorer: return [.brands]
case .wpforms: return [.brands]
case .wpressr: return [.brands]
case .wrench: return [.solid]
case .xRay: return [.solid]
case .xbox: return [.brands]
case .xing: return [.brands]
case .xingSquare: return [.brands]
case .yCombinator: return [.brands]
case .yahoo: return [.brands]
case .yammer: return [.brands]
case .yandex: return [.brands]
case .yandexInternational: return [.brands]
case .yarn: return [.brands]
case .yelp: return [.brands]
case .yenSign: return [.solid]
case .yinYang: return [.solid]
case .yoast: return [.brands]
case .youtube: return [.brands]
case .youtubeSquare: return [.brands]
case .zhihu: return [.brands]
default: return []
}
}
}
/// An enumaration of FontAwesome Brands icon names
public enum FontAwesomeBrands: String {
case fiveHundredPixels = "fa-500px"
case accessibleIcon = "fa-accessible-icon"
case accusoft = "fa-accusoft"
case acquisitionsIncorporated = "fa-acquisitions-incorporated"
case adn = "fa-adn"
case adobe = "fa-adobe"
case adversal = "fa-adversal"
case affiliatetheme = "fa-affiliatetheme"
case airbnb = "fa-airbnb"
case algolia = "fa-algolia"
case alipay = "fa-alipay"
case amazon = "fa-amazon"
case amazonPay = "fa-amazon-pay"
case amilia = "fa-amilia"
case android = "fa-android"
case angellist = "fa-angellist"
case angrycreative = "fa-angrycreative"
case angular = "fa-angular"
case appStore = "fa-app-store"
case appStoreIos = "fa-app-store-ios"
case apper = "fa-apper"
case apple = "fa-apple"
case applePay = "fa-apple-pay"
case artstation = "fa-artstation"
case asymmetrik = "fa-asymmetrik"
case atlassian = "fa-atlassian"
case audible = "fa-audible"
case autoprefixer = "fa-autoprefixer"
case avianex = "fa-avianex"
case aviato = "fa-aviato"
case aws = "fa-aws"
case bandcamp = "fa-bandcamp"
case battleNet = "fa-battle-net"
case behance = "fa-behance"
case behanceSquare = "fa-behance-square"
case bimobject = "fa-bimobject"
case bitbucket = "fa-bitbucket"
case bitcoin = "fa-bitcoin"
case bity = "fa-bity"
case blackTie = "fa-black-tie"
case blackberry = "fa-blackberry"
case blogger = "fa-blogger"
case bloggerB = "fa-blogger-b"
case bluetooth = "fa-bluetooth"
case bluetoothB = "fa-bluetooth-b"
case bootstrap = "fa-bootstrap"
case btc = "fa-btc"
case buffer = "fa-buffer"
case buromobelexperte = "fa-buromobelexperte"
case buyNLarge = "fa-buy-n-large"
case buysellads = "fa-buysellads"
case canadianMapleLeaf = "fa-canadian-maple-leaf"
case ccAmazonPay = "fa-cc-amazon-pay"
case ccAmex = "fa-cc-amex"
case ccApplePay = "fa-cc-apple-pay"
case ccDinersClub = "fa-cc-diners-club"
case ccDiscover = "fa-cc-discover"
case ccJcb = "fa-cc-jcb"
case ccMastercard = "fa-cc-mastercard"
case ccPaypal = "fa-cc-paypal"
case ccStripe = "fa-cc-stripe"
case ccVisa = "fa-cc-visa"
case centercode = "fa-centercode"
case centos = "fa-centos"
case chrome = "fa-chrome"
case chromecast = "fa-chromecast"
case cloudscale = "fa-cloudscale"
case cloudsmith = "fa-cloudsmith"
case cloudversify = "fa-cloudversify"
case codepen = "fa-codepen"
case codiepie = "fa-codiepie"
case confluence = "fa-confluence"
case connectdevelop = "fa-connectdevelop"
case contao = "fa-contao"
case cottonBureau = "fa-cotton-bureau"
case cpanel = "fa-cpanel"
case creativeCommons = "fa-creative-commons"
case creativeCommonsBy = "fa-creative-commons-by"
case creativeCommonsNc = "fa-creative-commons-nc"
case creativeCommonsNcEu = "fa-creative-commons-nc-eu"
case creativeCommonsNcJp = "fa-creative-commons-nc-jp"
case creativeCommonsNd = "fa-creative-commons-nd"
case creativeCommonsPd = "fa-creative-commons-pd"
case creativeCommonsPdAlt = "fa-creative-commons-pd-alt"
case creativeCommonsRemix = "fa-creative-commons-remix"
case creativeCommonsSa = "fa-creative-commons-sa"
case creativeCommonsSampling = "fa-creative-commons-sampling"
case creativeCommonsSamplingPlus = "fa-creative-commons-sampling-plus"
case creativeCommonsShare = "fa-creative-commons-share"
case creativeCommonsZero = "fa-creative-commons-zero"
case criticalRole = "fa-critical-role"
case css3 = "fa-css3"
case css3Alt = "fa-css3-alt"
case cuttlefish = "fa-cuttlefish"
case dAndD = "fa-d-and-d"
case dAndDBeyond = "fa-d-and-d-beyond"
case dailymotion = "fa-dailymotion"
case dashcube = "fa-dashcube"
case delicious = "fa-delicious"
case deploydog = "fa-deploydog"
case deskpro = "fa-deskpro"
case dev = "fa-dev"
case deviantart = "fa-deviantart"
case dhl = "fa-dhl"
case diaspora = "fa-diaspora"
case digg = "fa-digg"
case digitalOcean = "fa-digital-ocean"
case discord = "fa-discord"
case discourse = "fa-discourse"
case dochub = "fa-dochub"
case docker = "fa-docker"
case draft2digital = "fa-draft2digital"
case dribbble = "fa-dribbble"
case dribbbleSquare = "fa-dribbble-square"
case dropbox = "fa-dropbox"
case drupal = "fa-drupal"
case dyalog = "fa-dyalog"
case earlybirds = "fa-earlybirds"
case ebay = "fa-ebay"
case edge = "fa-edge"
case elementor = "fa-elementor"
case ello = "fa-ello"
case ember = "fa-ember"
case empire = "fa-empire"
case envira = "fa-envira"
case erlang = "fa-erlang"
case ethereum = "fa-ethereum"
case etsy = "fa-etsy"
case evernote = "fa-evernote"
case expeditedssl = "fa-expeditedssl"
case facebook = "fa-facebook"
case facebookF = "fa-facebook-f"
case facebookMessenger = "fa-facebook-messenger"
case facebookSquare = "fa-facebook-square"
case fantasyFlightGames = "fa-fantasy-flight-games"
case fedex = "fa-fedex"
case fedora = "fa-fedora"
case figma = "fa-figma"
case firefox = "fa-firefox"
case firefoxBrowser = "fa-firefox-browser"
case firstOrder = "fa-first-order"
case firstOrderAlt = "fa-first-order-alt"
case firstdraft = "fa-firstdraft"
case flickr = "fa-flickr"
case flipboard = "fa-flipboard"
case fly = "fa-fly"
case fontAwesome = "fa-font-awesome"
case fontAwesomeAlt = "fa-font-awesome-alt"
case fontAwesomeFlag = "fa-font-awesome-flag"
case fontAwesomeLogoFull = "fa-font-awesome-logo-full"
case fonticons = "fa-fonticons"
case fonticonsFi = "fa-fonticons-fi"
case fortAwesome = "fa-fort-awesome"
case fortAwesomeAlt = "fa-fort-awesome-alt"
case forumbee = "fa-forumbee"
case foursquare = "fa-foursquare"
case freeCodeCamp = "fa-free-code-camp"
case freebsd = "fa-freebsd"
case fulcrum = "fa-fulcrum"
case galacticRepublic = "fa-galactic-republic"
case galacticSenate = "fa-galactic-senate"
case getPocket = "fa-get-pocket"
case gg = "fa-gg"
case ggCircle = "fa-gg-circle"
case git = "fa-git"
case gitAlt = "fa-git-alt"
case gitSquare = "fa-git-square"
case github = "fa-github"
case githubAlt = "fa-github-alt"
case githubSquare = "fa-github-square"
case gitkraken = "fa-gitkraken"
case gitlab = "fa-gitlab"
case gitter = "fa-gitter"
case glide = "fa-glide"
case glideG = "fa-glide-g"
case gofore = "fa-gofore"
case goodreads = "fa-goodreads"
case goodreadsG = "fa-goodreads-g"
case google = "fa-google"
case googleDrive = "fa-google-drive"
case googlePlay = "fa-google-play"
case googlePlus = "fa-google-plus"
case googlePlusG = "fa-google-plus-g"
case googlePlusSquare = "fa-google-plus-square"
case googleWallet = "fa-google-wallet"
case gratipay = "fa-gratipay"
case grav = "fa-grav"
case gripfire = "fa-gripfire"
case grunt = "fa-grunt"
case gulp = "fa-gulp"
case hackerNews = "fa-hacker-news"
case hackerNewsSquare = "fa-hacker-news-square"
case hackerrank = "fa-hackerrank"
case hips = "fa-hips"
case hireAHelper = "fa-hire-a-helper"
case hooli = "fa-hooli"
case hornbill = "fa-hornbill"
case hotjar = "fa-hotjar"
case houzz = "fa-houzz"
case html5 = "fa-html5"
case hubspot = "fa-hubspot"
case ideal = "fa-ideal"
case imdb = "fa-imdb"
case instagram = "fa-instagram"
case instagramSquare = "fa-instagram-square"
case intercom = "fa-intercom"
case internetExplorer = "fa-internet-explorer"
case invision = "fa-invision"
case ioxhost = "fa-ioxhost"
case itchIo = "fa-itch-io"
case itunes = "fa-itunes"
case itunesNote = "fa-itunes-note"
case java = "fa-java"
case jediOrder = "fa-jedi-order"
case jenkins = "fa-jenkins"
case jira = "fa-jira"
case joget = "fa-joget"
case joomla = "fa-joomla"
case js = "fa-js"
case jsSquare = "fa-js-square"
case jsfiddle = "fa-jsfiddle"
case kaggle = "fa-kaggle"
case keybase = "fa-keybase"
case keycdn = "fa-keycdn"
case kickstarter = "fa-kickstarter"
case kickstarterK = "fa-kickstarter-k"
case korvue = "fa-korvue"
case laravel = "fa-laravel"
case lastfm = "fa-lastfm"
case lastfmSquare = "fa-lastfm-square"
case leanpub = "fa-leanpub"
case less = "fa-less"
case line = "fa-line"
case linkedin = "fa-linkedin"
case linkedinIn = "fa-linkedin-in"
case linode = "fa-linode"
case linux = "fa-linux"
case lyft = "fa-lyft"
case magento = "fa-magento"
case mailchimp = "fa-mailchimp"
case mandalorian = "fa-mandalorian"
case markdown = "fa-markdown"
case mastodon = "fa-mastodon"
case maxcdn = "fa-maxcdn"
case mdb = "fa-mdb"
case medapps = "fa-medapps"
case medium = "fa-medium"
case mediumM = "fa-medium-m"
case medrt = "fa-medrt"
case meetup = "fa-meetup"
case megaport = "fa-megaport"
case mendeley = "fa-mendeley"
case microblog = "fa-microblog"
case microsoft = "fa-microsoft"
case mix = "fa-mix"
case mixcloud = "fa-mixcloud"
case mixer = "fa-mixer"
case mizuni = "fa-mizuni"
case modx = "fa-modx"
case monero = "fa-monero"
case napster = "fa-napster"
case neos = "fa-neos"
case nimblr = "fa-nimblr"
case node = "fa-node"
case nodeJs = "fa-node-js"
case npm = "fa-npm"
case ns8 = "fa-ns8"
case nutritionix = "fa-nutritionix"
case odnoklassniki = "fa-odnoklassniki"
case odnoklassnikiSquare = "fa-odnoklassniki-square"
case oldRepublic = "fa-old-republic"
case opencart = "fa-opencart"
case openid = "fa-openid"
case opera = "fa-opera"
case optinMonster = "fa-optin-monster"
case orcid = "fa-orcid"
case osi = "fa-osi"
case page4 = "fa-page4"
case pagelines = "fa-pagelines"
case palfed = "fa-palfed"
case patreon = "fa-patreon"
case paypal = "fa-paypal"
case pennyArcade = "fa-penny-arcade"
case periscope = "fa-periscope"
case phabricator = "fa-phabricator"
case phoenixFramework = "fa-phoenix-framework"
case phoenixSquadron = "fa-phoenix-squadron"
case php = "fa-php"
case piedPiper = "fa-pied-piper"
case piedPiperAlt = "fa-pied-piper-alt"
case piedPiperHat = "fa-pied-piper-hat"
case piedPiperPp = "fa-pied-piper-pp"
case piedPiperSquare = "fa-pied-piper-square"
case pinterest = "fa-pinterest"
case pinterestP = "fa-pinterest-p"
case pinterestSquare = "fa-pinterest-square"
case playstation = "fa-playstation"
case productHunt = "fa-product-hunt"
case pushed = "fa-pushed"
case python = "fa-python"
case qq = "fa-qq"
case quinscape = "fa-quinscape"
case quora = "fa-quora"
case rProject = "fa-r-project"
case raspberryPi = "fa-raspberry-pi"
case ravelry = "fa-ravelry"
case react = "fa-react"
case reacteurope = "fa-reacteurope"
case readme = "fa-readme"
case rebel = "fa-rebel"
case redRiver = "fa-red-river"
case reddit = "fa-reddit"
case redditAlien = "fa-reddit-alien"
case redditSquare = "fa-reddit-square"
case redhat = "fa-redhat"
case renren = "fa-renren"
case replyd = "fa-replyd"
case researchgate = "fa-researchgate"
case resolving = "fa-resolving"
case rev = "fa-rev"
case rocketchat = "fa-rocketchat"
case rockrms = "fa-rockrms"
case safari = "fa-safari"
case salesforce = "fa-salesforce"
case sass = "fa-sass"
case schlix = "fa-schlix"
case scribd = "fa-scribd"
case searchengin = "fa-searchengin"
case sellcast = "fa-sellcast"
case sellsy = "fa-sellsy"
case servicestack = "fa-servicestack"
case shirtsinbulk = "fa-shirtsinbulk"
case shopify = "fa-shopify"
case shopware = "fa-shopware"
case simplybuilt = "fa-simplybuilt"
case sistrix = "fa-sistrix"
case sith = "fa-sith"
case sketch = "fa-sketch"
case skyatlas = "fa-skyatlas"
case skype = "fa-skype"
case slack = "fa-slack"
case slackHash = "fa-slack-hash"
case slideshare = "fa-slideshare"
case snapchat = "fa-snapchat"
case snapchatGhost = "fa-snapchat-ghost"
case snapchatSquare = "fa-snapchat-square"
case soundcloud = "fa-soundcloud"
case sourcetree = "fa-sourcetree"
case speakap = "fa-speakap"
case speakerDeck = "fa-speaker-deck"
case spotify = "fa-spotify"
case squarespace = "fa-squarespace"
case stackExchange = "fa-stack-exchange"
case stackOverflow = "fa-stack-overflow"
case stackpath = "fa-stackpath"
case staylinked = "fa-staylinked"
case steam = "fa-steam"
case steamSquare = "fa-steam-square"
case steamSymbol = "fa-steam-symbol"
case stickerMule = "fa-sticker-mule"
case strava = "fa-strava"
case stripe = "fa-stripe"
case stripeS = "fa-stripe-s"
case studiovinari = "fa-studiovinari"
case stumbleupon = "fa-stumbleupon"
case stumbleuponCircle = "fa-stumbleupon-circle"
case superpowers = "fa-superpowers"
case supple = "fa-supple"
case suse = "fa-suse"
case swift = "fa-swift"
case symfony = "fa-symfony"
case teamspeak = "fa-teamspeak"
case telegram = "fa-telegram"
case telegramPlane = "fa-telegram-plane"
case tencentWeibo = "fa-tencent-weibo"
case theRedYeti = "fa-the-red-yeti"
case themeco = "fa-themeco"
case themeisle = "fa-themeisle"
case thinkPeaks = "fa-think-peaks"
case tradeFederation = "fa-trade-federation"
case trello = "fa-trello"
case tripadvisor = "fa-tripadvisor"
case tumblr = "fa-tumblr"
case tumblrSquare = "fa-tumblr-square"
case twitch = "fa-twitch"
case twitter = "fa-twitter"
case twitterSquare = "fa-twitter-square"
case typo3 = "fa-typo3"
case uber = "fa-uber"
case ubuntu = "fa-ubuntu"
case uikit = "fa-uikit"
case umbraco = "fa-umbraco"
case uniregistry = "fa-uniregistry"
case unity = "fa-unity"
case untappd = "fa-untappd"
case ups = "fa-ups"
case usb = "fa-usb"
case usps = "fa-usps"
case ussunnah = "fa-ussunnah"
case vaadin = "fa-vaadin"
case viacoin = "fa-viacoin"
case viadeo = "fa-viadeo"
case viadeoSquare = "fa-viadeo-square"
case viber = "fa-viber"
case vimeo = "fa-vimeo"
case vimeoSquare = "fa-vimeo-square"
case vimeoV = "fa-vimeo-v"
case vine = "fa-vine"
case vk = "fa-vk"
case vnv = "fa-vnv"
case vuejs = "fa-vuejs"
case waze = "fa-waze"
case weebly = "fa-weebly"
case weibo = "fa-weibo"
case weixin = "fa-weixin"
case whatsapp = "fa-whatsapp"
case whatsappSquare = "fa-whatsapp-square"
case whmcs = "fa-whmcs"
case wikipediaW = "fa-wikipedia-w"
case windows = "fa-windows"
case wix = "fa-wix"
case wizardsOfTheCoast = "fa-wizards-of-the-coast"
case wolfPackBattalion = "fa-wolf-pack-battalion"
case wordpress = "fa-wordpress"
case wordpressSimple = "fa-wordpress-simple"
case wpbeginner = "fa-wpbeginner"
case wpexplorer = "fa-wpexplorer"
case wpforms = "fa-wpforms"
case wpressr = "fa-wpressr"
case xbox = "fa-xbox"
case xing = "fa-xing"
case xingSquare = "fa-xing-square"
case yCombinator = "fa-y-combinator"
case yahoo = "fa-yahoo"
case yammer = "fa-yammer"
case yandex = "fa-yandex"
case yandexInternational = "fa-yandex-international"
case yarn = "fa-yarn"
case yelp = "fa-yelp"
case yoast = "fa-yoast"
case youtube = "fa-youtube"
case youtubeSquare = "fa-youtube-square"
case zhihu = "fa-zhihu"
/// An unicode code of FontAwesome icon
public var unicode: String {
switch self {
case .fiveHundredPixels: return "\u{f26e}"
case .accessibleIcon: return "\u{f368}"
case .accusoft: return "\u{f369}"
case .acquisitionsIncorporated: return "\u{f6af}"
case .adn: return "\u{f170}"
case .adobe: return "\u{f778}"
case .adversal: return "\u{f36a}"
case .affiliatetheme: return "\u{f36b}"
case .airbnb: return "\u{f834}"
case .algolia: return "\u{f36c}"
case .alipay: return "\u{f642}"
case .amazon: return "\u{f270}"
case .amazonPay: return "\u{f42c}"
case .amilia: return "\u{f36d}"
case .android: return "\u{f17b}"
case .angellist: return "\u{f209}"
case .angrycreative: return "\u{f36e}"
case .angular: return "\u{f420}"
case .appStore: return "\u{f36f}"
case .appStoreIos: return "\u{f370}"
case .apper: return "\u{f371}"
case .apple: return "\u{f179}"
case .applePay: return "\u{f415}"
case .artstation: return "\u{f77a}"
case .asymmetrik: return "\u{f372}"
case .atlassian: return "\u{f77b}"
case .audible: return "\u{f373}"
case .autoprefixer: return "\u{f41c}"
case .avianex: return "\u{f374}"
case .aviato: return "\u{f421}"
case .aws: return "\u{f375}"
case .bandcamp: return "\u{f2d5}"
case .battleNet: return "\u{f835}"
case .behance: return "\u{f1b4}"
case .behanceSquare: return "\u{f1b5}"
case .bimobject: return "\u{f378}"
case .bitbucket: return "\u{f171}"
case .bitcoin: return "\u{f379}"
case .bity: return "\u{f37a}"
case .blackTie: return "\u{f27e}"
case .blackberry: return "\u{f37b}"
case .blogger: return "\u{f37c}"
case .bloggerB: return "\u{f37d}"
case .bluetooth: return "\u{f293}"
case .bluetoothB: return "\u{f294}"
case .bootstrap: return "\u{f836}"
case .btc: return "\u{f15a}"
case .buffer: return "\u{f837}"
case .buromobelexperte: return "\u{f37f}"
case .buyNLarge: return "\u{f8a6}"
case .buysellads: return "\u{f20d}"
case .canadianMapleLeaf: return "\u{f785}"
case .ccAmazonPay: return "\u{f42d}"
case .ccAmex: return "\u{f1f3}"
case .ccApplePay: return "\u{f416}"
case .ccDinersClub: return "\u{f24c}"
case .ccDiscover: return "\u{f1f2}"
case .ccJcb: return "\u{f24b}"
case .ccMastercard: return "\u{f1f1}"
case .ccPaypal: return "\u{f1f4}"
case .ccStripe: return "\u{f1f5}"
case .ccVisa: return "\u{f1f0}"
case .centercode: return "\u{f380}"
case .centos: return "\u{f789}"
case .chrome: return "\u{f268}"
case .chromecast: return "\u{f838}"
case .cloudscale: return "\u{f383}"
case .cloudsmith: return "\u{f384}"
case .cloudversify: return "\u{f385}"
case .codepen: return "\u{f1cb}"
case .codiepie: return "\u{f284}"
case .confluence: return "\u{f78d}"
case .connectdevelop: return "\u{f20e}"
case .contao: return "\u{f26d}"
case .cottonBureau: return "\u{f89e}"
case .cpanel: return "\u{f388}"
case .creativeCommons: return "\u{f25e}"
case .creativeCommonsBy: return "\u{f4e7}"
case .creativeCommonsNc: return "\u{f4e8}"
case .creativeCommonsNcEu: return "\u{f4e9}"
case .creativeCommonsNcJp: return "\u{f4ea}"
case .creativeCommonsNd: return "\u{f4eb}"
case .creativeCommonsPd: return "\u{f4ec}"
case .creativeCommonsPdAlt: return "\u{f4ed}"
case .creativeCommonsRemix: return "\u{f4ee}"
case .creativeCommonsSa: return "\u{f4ef}"
case .creativeCommonsSampling: return "\u{f4f0}"
case .creativeCommonsSamplingPlus: return "\u{f4f1}"
case .creativeCommonsShare: return "\u{f4f2}"
case .creativeCommonsZero: return "\u{f4f3}"
case .criticalRole: return "\u{f6c9}"
case .css3: return "\u{f13c}"
case .css3Alt: return "\u{f38b}"
case .cuttlefish: return "\u{f38c}"
case .dAndD: return "\u{f38d}"
case .dAndDBeyond: return "\u{f6ca}"
case .dailymotion: return "\u{f952}"
case .dashcube: return "\u{f210}"
case .delicious: return "\u{f1a5}"
case .deploydog: return "\u{f38e}"
case .deskpro: return "\u{f38f}"
case .dev: return "\u{f6cc}"
case .deviantart: return "\u{f1bd}"
case .dhl: return "\u{f790}"
case .diaspora: return "\u{f791}"
case .digg: return "\u{f1a6}"
case .digitalOcean: return "\u{f391}"
case .discord: return "\u{f392}"
case .discourse: return "\u{f393}"
case .dochub: return "\u{f394}"
case .docker: return "\u{f395}"
case .draft2digital: return "\u{f396}"
case .dribbble: return "\u{f17d}"
case .dribbbleSquare: return "\u{f397}"
case .dropbox: return "\u{f16b}"
case .drupal: return "\u{f1a9}"
case .dyalog: return "\u{f399}"
case .earlybirds: return "\u{f39a}"
case .ebay: return "\u{f4f4}"
case .edge: return "\u{f282}"
case .elementor: return "\u{f430}"
case .ello: return "\u{f5f1}"
case .ember: return "\u{f423}"
case .empire: return "\u{f1d1}"
case .envira: return "\u{f299}"
case .erlang: return "\u{f39d}"
case .ethereum: return "\u{f42e}"
case .etsy: return "\u{f2d7}"
case .evernote: return "\u{f839}"
case .expeditedssl: return "\u{f23e}"
case .facebook: return "\u{f09a}"
case .facebookF: return "\u{f39e}"
case .facebookMessenger: return "\u{f39f}"
case .facebookSquare: return "\u{f082}"
case .fantasyFlightGames: return "\u{f6dc}"
case .fedex: return "\u{f797}"
case .fedora: return "\u{f798}"
case .figma: return "\u{f799}"
case .firefox: return "\u{f269}"
case .firefoxBrowser: return "\u{f907}"
case .firstOrder: return "\u{f2b0}"
case .firstOrderAlt: return "\u{f50a}"
case .firstdraft: return "\u{f3a1}"
case .flickr: return "\u{f16e}"
case .flipboard: return "\u{f44d}"
case .fly: return "\u{f417}"
case .fontAwesome: return "\u{f2b4}"
case .fontAwesomeAlt: return "\u{f35c}"
case .fontAwesomeFlag: return "\u{f425}"
case .fontAwesomeLogoFull: return "\u{f4e6}"
case .fonticons: return "\u{f280}"
case .fonticonsFi: return "\u{f3a2}"
case .fortAwesome: return "\u{f286}"
case .fortAwesomeAlt: return "\u{f3a3}"
case .forumbee: return "\u{f211}"
case .foursquare: return "\u{f180}"
case .freeCodeCamp: return "\u{f2c5}"
case .freebsd: return "\u{f3a4}"
case .fulcrum: return "\u{f50b}"
case .galacticRepublic: return "\u{f50c}"
case .galacticSenate: return "\u{f50d}"
case .getPocket: return "\u{f265}"
case .gg: return "\u{f260}"
case .ggCircle: return "\u{f261}"
case .git: return "\u{f1d3}"
case .gitAlt: return "\u{f841}"
case .gitSquare: return "\u{f1d2}"
case .github: return "\u{f09b}"
case .githubAlt: return "\u{f113}"
case .githubSquare: return "\u{f092}"
case .gitkraken: return "\u{f3a6}"
case .gitlab: return "\u{f296}"
case .gitter: return "\u{f426}"
case .glide: return "\u{f2a5}"
case .glideG: return "\u{f2a6}"
case .gofore: return "\u{f3a7}"
case .goodreads: return "\u{f3a8}"
case .goodreadsG: return "\u{f3a9}"
case .google: return "\u{f1a0}"
case .googleDrive: return "\u{f3aa}"
case .googlePlay: return "\u{f3ab}"
case .googlePlus: return "\u{f2b3}"
case .googlePlusG: return "\u{f0d5}"
case .googlePlusSquare: return "\u{f0d4}"
case .googleWallet: return "\u{f1ee}"
case .gratipay: return "\u{f184}"
case .grav: return "\u{f2d6}"
case .gripfire: return "\u{f3ac}"
case .grunt: return "\u{f3ad}"
case .gulp: return "\u{f3ae}"
case .hackerNews: return "\u{f1d4}"
case .hackerNewsSquare: return "\u{f3af}"
case .hackerrank: return "\u{f5f7}"
case .hips: return "\u{f452}"
case .hireAHelper: return "\u{f3b0}"
case .hooli: return "\u{f427}"
case .hornbill: return "\u{f592}"
case .hotjar: return "\u{f3b1}"
case .houzz: return "\u{f27c}"
case .html5: return "\u{f13b}"
case .hubspot: return "\u{f3b2}"
case .ideal: return "\u{f913}"
case .imdb: return "\u{f2d8}"
case .instagram: return "\u{f16d}"
case .instagramSquare: return "\u{f955}"
case .intercom: return "\u{f7af}"
case .internetExplorer: return "\u{f26b}"
case .invision: return "\u{f7b0}"
case .ioxhost: return "\u{f208}"
case .itchIo: return "\u{f83a}"
case .itunes: return "\u{f3b4}"
case .itunesNote: return "\u{f3b5}"
case .java: return "\u{f4e4}"
case .jediOrder: return "\u{f50e}"
case .jenkins: return "\u{f3b6}"
case .jira: return "\u{f7b1}"
case .joget: return "\u{f3b7}"
case .joomla: return "\u{f1aa}"
case .js: return "\u{f3b8}"
case .jsSquare: return "\u{f3b9}"
case .jsfiddle: return "\u{f1cc}"
case .kaggle: return "\u{f5fa}"
case .keybase: return "\u{f4f5}"
case .keycdn: return "\u{f3ba}"
case .kickstarter: return "\u{f3bb}"
case .kickstarterK: return "\u{f3bc}"
case .korvue: return "\u{f42f}"
case .laravel: return "\u{f3bd}"
case .lastfm: return "\u{f202}"
case .lastfmSquare: return "\u{f203}"
case .leanpub: return "\u{f212}"
case .less: return "\u{f41d}"
case .line: return "\u{f3c0}"
case .linkedin: return "\u{f08c}"
case .linkedinIn: return "\u{f0e1}"
case .linode: return "\u{f2b8}"
case .linux: return "\u{f17c}"
case .lyft: return "\u{f3c3}"
case .magento: return "\u{f3c4}"
case .mailchimp: return "\u{f59e}"
case .mandalorian: return "\u{f50f}"
case .markdown: return "\u{f60f}"
case .mastodon: return "\u{f4f6}"
case .maxcdn: return "\u{f136}"
case .mdb: return "\u{f8ca}"
case .medapps: return "\u{f3c6}"
case .medium: return "\u{f23a}"
case .mediumM: return "\u{f3c7}"
case .medrt: return "\u{f3c8}"
case .meetup: return "\u{f2e0}"
case .megaport: return "\u{f5a3}"
case .mendeley: return "\u{f7b3}"
case .microblog: return "\u{f91a}"
case .microsoft: return "\u{f3ca}"
case .mix: return "\u{f3cb}"
case .mixcloud: return "\u{f289}"
case .mixer: return "\u{f956}"
case .mizuni: return "\u{f3cc}"
case .modx: return "\u{f285}"
case .monero: return "\u{f3d0}"
case .napster: return "\u{f3d2}"
case .neos: return "\u{f612}"
case .nimblr: return "\u{f5a8}"
case .node: return "\u{f419}"
case .nodeJs: return "\u{f3d3}"
case .npm: return "\u{f3d4}"
case .ns8: return "\u{f3d5}"
case .nutritionix: return "\u{f3d6}"
case .odnoklassniki: return "\u{f263}"
case .odnoklassnikiSquare: return "\u{f264}"
case .oldRepublic: return "\u{f510}"
case .opencart: return "\u{f23d}"
case .openid: return "\u{f19b}"
case .opera: return "\u{f26a}"
case .optinMonster: return "\u{f23c}"
case .orcid: return "\u{f8d2}"
case .osi: return "\u{f41a}"
case .page4: return "\u{f3d7}"
case .pagelines: return "\u{f18c}"
case .palfed: return "\u{f3d8}"
case .patreon: return "\u{f3d9}"
case .paypal: return "\u{f1ed}"
case .pennyArcade: return "\u{f704}"
case .periscope: return "\u{f3da}"
case .phabricator: return "\u{f3db}"
case .phoenixFramework: return "\u{f3dc}"
case .phoenixSquadron: return "\u{f511}"
case .php: return "\u{f457}"
case .piedPiper: return "\u{f2ae}"
case .piedPiperAlt: return "\u{f1a8}"
case .piedPiperHat: return "\u{f4e5}"
case .piedPiperPp: return "\u{f1a7}"
case .piedPiperSquare: return "\u{f91e}"
case .pinterest: return "\u{f0d2}"
case .pinterestP: return "\u{f231}"
case .pinterestSquare: return "\u{f0d3}"
case .playstation: return "\u{f3df}"
case .productHunt: return "\u{f288}"
case .pushed: return "\u{f3e1}"
case .python: return "\u{f3e2}"
case .qq: return "\u{f1d6}"
case .quinscape: return "\u{f459}"
case .quora: return "\u{f2c4}"
case .rProject: return "\u{f4f7}"
case .raspberryPi: return "\u{f7bb}"
case .ravelry: return "\u{f2d9}"
case .react: return "\u{f41b}"
case .reacteurope: return "\u{f75d}"
case .readme: return "\u{f4d5}"
case .rebel: return "\u{f1d0}"
case .redRiver: return "\u{f3e3}"
case .reddit: return "\u{f1a1}"
case .redditAlien: return "\u{f281}"
case .redditSquare: return "\u{f1a2}"
case .redhat: return "\u{f7bc}"
case .renren: return "\u{f18b}"
case .replyd: return "\u{f3e6}"
case .researchgate: return "\u{f4f8}"
case .resolving: return "\u{f3e7}"
case .rev: return "\u{f5b2}"
case .rocketchat: return "\u{f3e8}"
case .rockrms: return "\u{f3e9}"
case .safari: return "\u{f267}"
case .salesforce: return "\u{f83b}"
case .sass: return "\u{f41e}"
case .schlix: return "\u{f3ea}"
case .scribd: return "\u{f28a}"
case .searchengin: return "\u{f3eb}"
case .sellcast: return "\u{f2da}"
case .sellsy: return "\u{f213}"
case .servicestack: return "\u{f3ec}"
case .shirtsinbulk: return "\u{f214}"
case .shopify: return "\u{f957}"
case .shopware: return "\u{f5b5}"
case .simplybuilt: return "\u{f215}"
case .sistrix: return "\u{f3ee}"
case .sith: return "\u{f512}"
case .sketch: return "\u{f7c6}"
case .skyatlas: return "\u{f216}"
case .skype: return "\u{f17e}"
case .slack: return "\u{f198}"
case .slackHash: return "\u{f3ef}"
case .slideshare: return "\u{f1e7}"
case .snapchat: return "\u{f2ab}"
case .snapchatGhost: return "\u{f2ac}"
case .snapchatSquare: return "\u{f2ad}"
case .soundcloud: return "\u{f1be}"
case .sourcetree: return "\u{f7d3}"
case .speakap: return "\u{f3f3}"
case .speakerDeck: return "\u{f83c}"
case .spotify: return "\u{f1bc}"
case .squarespace: return "\u{f5be}"
case .stackExchange: return "\u{f18d}"
case .stackOverflow: return "\u{f16c}"
case .stackpath: return "\u{f842}"
case .staylinked: return "\u{f3f5}"
case .steam: return "\u{f1b6}"
case .steamSquare: return "\u{f1b7}"
case .steamSymbol: return "\u{f3f6}"
case .stickerMule: return "\u{f3f7}"
case .strava: return "\u{f428}"
case .stripe: return "\u{f429}"
case .stripeS: return "\u{f42a}"
case .studiovinari: return "\u{f3f8}"
case .stumbleupon: return "\u{f1a4}"
case .stumbleuponCircle: return "\u{f1a3}"
case .superpowers: return "\u{f2dd}"
case .supple: return "\u{f3f9}"
case .suse: return "\u{f7d6}"
case .swift: return "\u{f8e1}"
case .symfony: return "\u{f83d}"
case .teamspeak: return "\u{f4f9}"
case .telegram: return "\u{f2c6}"
case .telegramPlane: return "\u{f3fe}"
case .tencentWeibo: return "\u{f1d5}"
case .theRedYeti: return "\u{f69d}"
case .themeco: return "\u{f5c6}"
case .themeisle: return "\u{f2b2}"
case .thinkPeaks: return "\u{f731}"
case .tradeFederation: return "\u{f513}"
case .trello: return "\u{f181}"
case .tripadvisor: return "\u{f262}"
case .tumblr: return "\u{f173}"
case .tumblrSquare: return "\u{f174}"
case .twitch: return "\u{f1e8}"
case .twitter: return "\u{f099}"
case .twitterSquare: return "\u{f081}"
case .typo3: return "\u{f42b}"
case .uber: return "\u{f402}"
case .ubuntu: return "\u{f7df}"
case .uikit: return "\u{f403}"
case .umbraco: return "\u{f8e8}"
case .uniregistry: return "\u{f404}"
case .unity: return "\u{f949}"
case .untappd: return "\u{f405}"
case .ups: return "\u{f7e0}"
case .usb: return "\u{f287}"
case .usps: return "\u{f7e1}"
case .ussunnah: return "\u{f407}"
case .vaadin: return "\u{f408}"
case .viacoin: return "\u{f237}"
case .viadeo: return "\u{f2a9}"
case .viadeoSquare: return "\u{f2aa}"
case .viber: return "\u{f409}"
case .vimeo: return "\u{f40a}"
case .vimeoSquare: return "\u{f194}"
case .vimeoV: return "\u{f27d}"
case .vine: return "\u{f1ca}"
case .vk: return "\u{f189}"
case .vnv: return "\u{f40b}"
case .vuejs: return "\u{f41f}"
case .waze: return "\u{f83f}"
case .weebly: return "\u{f5cc}"
case .weibo: return "\u{f18a}"
case .weixin: return "\u{f1d7}"
case .whatsapp: return "\u{f232}"
case .whatsappSquare: return "\u{f40c}"
case .whmcs: return "\u{f40d}"
case .wikipediaW: return "\u{f266}"
case .windows: return "\u{f17a}"
case .wix: return "\u{f5cf}"
case .wizardsOfTheCoast: return "\u{f730}"
case .wolfPackBattalion: return "\u{f514}"
case .wordpress: return "\u{f19a}"
case .wordpressSimple: return "\u{f411}"
case .wpbeginner: return "\u{f297}"
case .wpexplorer: return "\u{f2de}"
case .wpforms: return "\u{f298}"
case .wpressr: return "\u{f3e4}"
case .xbox: return "\u{f412}"
case .xing: return "\u{f168}"
case .xingSquare: return "\u{f169}"
case .yCombinator: return "\u{f23b}"
case .yahoo: return "\u{f19e}"
case .yammer: return "\u{f840}"
case .yandex: return "\u{f413}"
case .yandexInternational: return "\u{f414}"
case .yarn: return "\u{f7e3}"
case .yelp: return "\u{f1e9}"
case .yoast: return "\u{f2b1}"
case .youtube: return "\u{f167}"
case .youtubeSquare: return "\u{f431}"
case .zhihu: return "\u{f63f}"
}
}
}
|
gpl-3.0
|
9861cd5492cd83478e7fa1c721f49243
| 41.708738 | 84 | 0.562614 | 3.512643 | false | false | false | false |
ZacharyKhan/ZKCarousel
|
ZKCarousel/Classes/ZKCarouselSlide.swift
|
1
|
466
|
//
// ZKCarouselSlide.swift
// ZKCarousel
//
// Created by Zachary Khan on 8/22/20.
//
import UIKit
public struct ZKCarouselSlide {
public var image : UIImage
public var title : String?
public var description: String?
public init(image: UIImage,
title: String? = nil,
description: String? = nil) {
self.image = image
self.title = title
self.description = description
}
}
|
mit
|
5ec08eccc29b83d67b4629b2b16d67a6
| 19.26087 | 45 | 0.583691 | 4.160714 | false | false | false | false |
rutgerfarry/FreshFades
|
FreshFades/AppDelegate.swift
|
1
|
2018
|
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? = UIWindow()
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let musicViewController = MusicViewController()
let haircutChoiceViewController = HaircutChoiceViewController()
let profileViewController = ProfileViewController()
let musicNavigationController = UINavigationController(rootViewController: musicViewController)
let scheduleNavigationController = UINavigationController(rootViewController: haircutChoiceViewController)
let profileNavigationController = UINavigationController(rootViewController: profileViewController)
let tabBarController = UITabBarController()
musicNavigationController.tabBarItem = UITabBarItem(
title: "Music",
image: #imageLiteral(resourceName: "music_tab_bar"),
tag: 0)
scheduleNavigationController.tabBarItem = UITabBarItem(
title: "Schedule",
image: #imageLiteral(resourceName: "calendar_tab_bar"),
tag: 1)
profileNavigationController.tabBarItem = UITabBarItem(
title: "Profile",
image: #imageLiteral(resourceName: "profile_tab_bar"),
tag: 2)
// Tab bar setup
tabBarController.viewControllers = [
musicNavigationController,
scheduleNavigationController,
profileNavigationController
]
window!.tintColor = UIColor.Theme.tint
UINavigationBar.appearance().barStyle = .black
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().barTintColor = UIColor.Theme.tint
UINavigationBar.appearance().tintColor = .white
window!.rootViewController = tabBarController
window!.makeKeyAndVisible()
return true
}
}
|
mit
|
529b183fe915e1943227115a88d4e9f5
| 35.690909 | 114 | 0.689296 | 6.616393 | false | false | false | false |
Themaister/RetroArch
|
pkg/apple/HelperBar/HelperBarViewModel.swift
|
6
|
2682
|
//
// HelperBarViewModel.swift
// RetroArchiOS
//
// Created by Yoshi Sugawara on 3/1/22.
// Copyright © 2022 RetroArch. All rights reserved.
//
import Combine
protocol HelperBarViewModelDelegate: AnyObject {
func setNavigationBarHidden(_ isHidden: Bool)
func updateNavigationBarItems()
}
class HelperBarViewModel {
@Published var didInteractWithBar = false
private var cancellable: AnyCancellable?
private var timer: DispatchSourceTimer?
weak var delegate: HelperBarViewModelDelegate?
weak var actionDelegate: HelperBarActionDelegate?
lazy var barItems: [HelperBarItem] = [
KeyboardBarItem(actionDelegate: actionDelegate),
MouseBarItem(actionDelegate: actionDelegate)
]
var barItemMapping = [UIBarButtonItem: HelperBarItem]()
init(delegate: HelperBarViewModelDelegate? = nil, actionDelegate: HelperBarActionDelegate? = nil) {
self.delegate = delegate
self.actionDelegate = actionDelegate
setupSubscription()
}
// Create a timer that will hide the navigation bar after 3 seconds if it's not interacted with
private func setupTimer() {
timer = DispatchSource.makeTimerSource()
timer?.setEventHandler(handler: { [weak self] in
guard let self = self else { return }
if !self.didInteractWithBar {
DispatchQueue.main.async { [weak self] in
self?.didInteractWithBar = false
self?.delegate?.setNavigationBarHidden(true)
}
}
})
timer?.schedule(deadline: .now() + .seconds(3))
timer?.resume()
}
// Listen for changes on didInteractWithBar
private func setupSubscription() {
cancellable = $didInteractWithBar
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] didInteract in
print("didInteract changed to \(didInteract)")
if didInteract {
self?.delegate?.setNavigationBarHidden(false)
self?.timer?.cancel()
self?.setupTimer()
self?.didInteractWithBar = false
}
})
}
func createBarButtonItems() -> [UIBarButtonItem] {
barItemMapping.removeAll()
return barItems.map{ [weak self] item in
let barButtonItem = UIBarButtonItem(image: item.image, style: .plain, target: self, action: #selector(didTapBarItem(_:)))
self?.barItemMapping[barButtonItem] = item
return barButtonItem
}
}
@objc private func didTapBarItem(_ sender: UIBarButtonItem) {
guard let item = barItemMapping[sender] else { return }
item.action()
delegate?.updateNavigationBarItems()
}
}
|
gpl-3.0
|
1cebec548dd92f2af9a1db09c87e4fed
| 31.301205 | 130 | 0.658336 | 4.7875 | false | false | false | false |
cybertunnel/SplashBuddy
|
SplashBuddy/MainWebView.swift
|
1
|
1699
|
//
// CasperSplashWebView.swift
// SplashBuddy
//
// Created by ftiff on 04/08/16.
// Copyright © 2016 François Levaux-Tiffreau. All rights reserved.
//
import Cocoa
import WebKit
class MainWebView: WebView {
override func viewWillDraw() {
self.layer?.borderWidth = 1.0
self.layer?.borderWidth = 1.0
self.layer?.borderColor = NSColor.lightGray.cgColor
self.layer?.isOpaque = true
// Sets preferences to match IB
// NOTE: Possible issue with the IBOutlet connection
self.preferences.isJavaEnabled = false
self.preferences.isJavaScriptEnabled = false
self.preferences.javaScriptCanOpenWindowsAutomatically = false
self.preferences.loadsImagesAutomatically = true
self.preferences.allowsAnimatedImages = false
self.preferences.allowsAnimatedImageLooping = false
// An attempt at returning a localized version, if exists.
// presentation.html -> presentation_fr.html
let full_url = URL(fileURLWithPath: Preferences.sharedInstance.htmlAbsolutePath)
let extension_path = full_url.pathExtension
let base_path = full_url.deletingPathExtension().path
let languageCode = NSLocale.current.languageCode ?? "en"
let localized_path = "\(base_path)_\(languageCode).\(extension_path)"
if FileManager().fileExists(atPath: localized_path) {
self.mainFrame.load(URLRequest(url: URL(fileURLWithPath: localized_path)))
} else {
self.mainFrame.load(URLRequest(url: URL(fileURLWithPath: Preferences.sharedInstance.htmlAbsolutePath)))
}
}
}
|
apache-2.0
|
fb7bba659c3dc6955755e9e31da083f4
| 35.106383 | 115 | 0.664113 | 4.834758 | false | false | false | false |
i-miss-you/Nuke
|
Pod/Classes/GIF/AnimatedImage.swift
|
9
|
1659
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import UIKit
import FLAnimatedImage
public class AnimatedImage: UIImage {
public let animatedImage: FLAnimatedImage?
public init(animatedImage: FLAnimatedImage, posterImage: CGImageRef, posterImageScale: CGFloat, posterImageOrientation: UIImageOrientation) {
self.animatedImage = animatedImage
super.init(CGImage: posterImage, scale: posterImageScale, orientation: posterImageOrientation)
}
public required init?(coder aDecoder: NSCoder) {
self.animatedImage = nil
super.init(coder: aDecoder) // makes me sad every time
}
}
public class AnimatedImageDecoder: ImageDecoding {
public init() {}
public func imageWithData(data: NSData) -> UIImage? {
guard self.isAnimatedGIFData(data) else {
return nil
}
guard let image = FLAnimatedImage(animatedGIFData: data) where image.posterImage != nil else {
return nil
}
guard let poster = image.posterImage, posterCGImage = poster.CGImage else {
return nil
}
return AnimatedImage(animatedImage: image, posterImage: posterCGImage, posterImageScale: poster.scale, posterImageOrientation: poster.imageOrientation)
}
public func isAnimatedGIFData(data: NSData) -> Bool {
let sigLength = 3
if data.length < sigLength {
return false
}
var sig = [UInt8](count: sigLength, repeatedValue: 0)
data.getBytes(&sig, length:sigLength)
return sig[0] == 0x47 && sig[1] == 0x49 && sig[2] == 0x46
}
}
|
mit
|
e59389b697d851abbf8eb467d6e81138
| 34.297872 | 159 | 0.66305 | 4.673239 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.