blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 6
116
| path
stringlengths 5
872
| src_encoding
stringclasses 7
values | length_bytes
int64 10
4.68M
| score
float64 2.52
5.63
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 7
4.81M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
5e3a819dd328dd257688a2437b730b6d4616298d
|
Swift
|
fnazarios/weather-app
|
/Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/FlatMap.swift
|
UTF-8
| 5,988
| 2.8125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
//
// FlatMap.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/11/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// It's value is one because initial source subscription is always in CompositeDisposable
let FlatMapNoIterators = 1
class FlatMapSinkIter<SourceType, S: ObservableConvertibleType, O: ObserverType where O.E == S.E> : ObserverType {
typealias Parent = FlatMapSink<SourceType, S, O>
typealias DisposeKey = CompositeDisposable.DisposeKey
typealias E = O.E
private let _parent: Parent
private let _disposeKey: DisposeKey
init(parent: Parent, disposeKey: DisposeKey) {
_parent = parent
_disposeKey = disposeKey
}
func on(event: Event<E>) {
switch event {
case .Next(let value):
_parent._lock.lock(); defer { _parent._lock.unlock() } // lock {
_parent.forwardOn(.Next(value))
// }
case .Error(let error):
_parent._lock.lock(); defer { _parent._lock.unlock() } // lock {
_parent.forwardOn(.Error(error))
_parent.dispose()
// }
case .Completed:
_parent._group.removeDisposable(_disposeKey)
// If this has returned true that means that `Completed` should be sent.
// In case there is a race who will sent first completed,
// lock will sort it out. When first Completed message is sent
// it will set observer to nil, and thus prevent further complete messages
// to be sent, and thus preserving the sequence grammar.
if _parent._stopped && _parent._group.count == FlatMapNoIterators {
_parent._lock.lock(); defer { _parent._lock.unlock() } // lock {
_parent.forwardOn(.Completed)
_parent.dispose()
// }
}
}
}
}
class FlatMapSink<SourceType, S: ObservableConvertibleType, O: ObserverType where O.E == S.E> : Sink<O>, ObserverType {
typealias ResultType = O.E
typealias Element = SourceType
typealias Parent = FlatMap<SourceType, S>
private let _parent: Parent
private let _lock = NSRecursiveLock()
// state
private let _group = CompositeDisposable()
private let _sourceSubscription = SingleAssignmentDisposable()
private var _stopped = false
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func performMap(element: SourceType) throws -> S {
abstractMethod()
}
func on(event: Event<SourceType>) {
switch event {
case .Next(let element):
do {
let value = try performMap(element)
subscribeInner(value.asObservable())
}
catch let e {
forwardOn(.Error(e))
dispose()
}
case .Error(let error):
_lock.lock(); defer { _lock.unlock() } // lock {
forwardOn(.Error(error))
dispose()
// }
case .Completed:
_lock.lock(); defer { _lock.unlock() } // lock {
_stopped = true
if _group.count == FlatMapNoIterators {
forwardOn(.Completed)
dispose()
}
else {
_sourceSubscription.dispose()
}
//}
}
}
func subscribeInner(source: Observable<O.E>) {
let iterDisposable = SingleAssignmentDisposable()
if let disposeKey = _group.addDisposable(iterDisposable) {
let iter = FlatMapSinkIter(parent: self, disposeKey: disposeKey)
let subscription = source.subscribe(iter)
iterDisposable.disposable = subscription
}
}
func run() -> Disposable {
_group.addDisposable(_sourceSubscription)
let subscription = _parent._source.subscribe(self)
_sourceSubscription.disposable = subscription
return _group
}
}
class FlatMapSink1<SourceType, S: ObservableConvertibleType, O : ObserverType where S.E == O.E> : FlatMapSink<SourceType, S, O> {
override init(parent: Parent, observer: O) {
super.init(parent: parent, observer: observer)
}
override func performMap(element: SourceType) throws -> S {
return try _parent._selector1!(element)
}
}
class FlatMapSink2<SourceType, S: ObservableConvertibleType, O: ObserverType where S.E == O.E> : FlatMapSink<SourceType, S, O> {
private var _index = 0
override init(parent: Parent, observer: O) {
super.init(parent: parent, observer: observer)
}
override func performMap(element: SourceType) throws -> S {
return try _parent._selector2!(element, try incrementChecked(&_index))
}
}
class FlatMap<SourceType, S: ObservableConvertibleType>: Producer<S.E> {
typealias Selector1 = (SourceType) throws -> S
typealias Selector2 = (SourceType, Int) throws -> S
private let _source: Observable<SourceType>
private let _selector1: Selector1?
private let _selector2: Selector2?
init(source: Observable<SourceType>, selector: Selector1) {
_source = source
_selector1 = selector
_selector2 = nil
}
init(source: Observable<SourceType>, selector: Selector2) {
_source = source
_selector2 = selector
_selector1 = nil
}
override func run<O: ObserverType where O.E == S.E>(observer: O) -> Disposable {
let sink: FlatMapSink<SourceType, S, O>
if let _ = _selector1 {
sink = FlatMapSink1(parent: self, observer: observer)
}
else {
sink = FlatMapSink2(parent: self, observer: observer)
}
let subscription = sink.run()
sink.disposable = subscription
return sink
}
}
| true
|
c78573bc6a4c519ff28d047e18a84993ab7d2eaa
|
Swift
|
stevecotner/Poet
|
/Sources/Poet/ObservingTextView.swift
|
UTF-8
| 965
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
//
// ObservingTextView.swift
//
//
// Created by Stephen E. Cotner on 7/13/20.
//
import SwiftUI
public struct ObservingTextView: View {
@Observed public var text: String?
public var alignment: TextAlignment?
public var kerning: CGFloat
public init(_ text: Observed<String?>, alignment: TextAlignment? = nil, kerning: CGFloat = 0) {
self._text = text
self.alignment = alignment
self.kerning = kerning
}
@ViewBuilder public var body: some View {
if let text = text {
Text(text)
.kerning(kerning)
.multilineTextAlignment(alignment ?? .leading)
} else {
EmptyView()
}
}
}
// MARK: Preview
public struct ObservingTextView_Previews: PreviewProvider {
@Observable public static var helloText: String? = "Hello"
public static var previews: some View {
ObservingTextView($helloText, alignment: .leading)
}
}
| true
|
f1c2aa7d1df5ef5d3a54d4f425d009f2fd1b4350
|
Swift
|
keisukeYamagishi/swift
|
/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ComputeEffects.swift
|
UTF-8
| 8,740
| 2.625
| 3
|
[
"Apache-2.0",
"Swift-exception"
] |
permissive
|
//===--- ComputeEffects.swift - Compute function effects ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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 SIL
fileprivate typealias Selection = ArgumentEffect.Selection
fileprivate typealias Path = ArgumentEffect.Path
/// Computes effects for function arguments.
///
/// For example, if an argument does not escape, adds a non-escaping effect,
/// e.g. "[escapes !%0.**]":
///
/// sil [escapes !%0.**] @foo : $@convention(thin) (@guaranteed X) -> () {
/// bb0(%0 : $X):
/// %1 = tuple ()
/// return %1 : $()
/// }
///
/// The pass does not try to change or re-compute _defined_ effects.
/// Currently, only escaping effects are handled.
/// In future, this pass may also add other effects, like memory side effects.
let computeEffects = FunctionPass(name: "compute-effects", {
(function: Function, context: PassContext) in
var argsWithDefinedEffects = getArgIndicesWithDefinedEffects(of: function)
var escapeInfo = EscapeInfo(calleeAnalysis: context.calleeAnalysis)
var newEffects = Stack<ArgumentEffect>(context)
let returnInst = function.returnInstruction
for arg in function.arguments {
// We are not interested in arguments with trivial types.
if !arg.type.isNonTrivialOrContainsRawPointer(in: function) { continue }
// Also, we don't want to override defined effects.
if argsWithDefinedEffects.contains(arg.index) { continue }
// First check: is the argument (or a projected value of it) escaping at all?
if !escapeInfo.isEscapingWhenWalkingDown(object: arg, path: Path(.anything),
visitUse: { op, _, _ in
isOperandOfRecursiveCall(op) ? .ignore : .continueWalking
}) {
let selectedArg = Selection(arg, pathPattern: Path(.anything))
newEffects.push(ArgumentEffect(.notEscaping, selectedArg: selectedArg))
continue
}
// Now compute effects for two important cases:
// * the argument itself + any value projections, and...
if addArgEffects(arg, argPath: Path(), to: &newEffects, returnInst, &escapeInfo) {
// * single class indirections
_ = addArgEffects(arg, argPath: Path(.anyValueFields).push(.anyClassField),
to: &newEffects, returnInst, &escapeInfo)
}
}
context.modifyEffects(in: function) { (effects: inout FunctionEffects) in
effects.removeDerivedEffects()
effects.argumentEffects.append(contentsOf: newEffects)
}
newEffects.removeAll()
})
/// Returns true if an argument effect was added.
private
func addArgEffects(_ arg: FunctionArgument, argPath ap: Path,
to newEffects: inout Stack<ArgumentEffect>,
_ returnInst: ReturnInst?,
_ escapeInfo: inout EscapeInfo) -> Bool {
var toSelection: Selection?
// Correct the path if the argument is not a class reference itself, but a value type
// containing one or more references.
let argPath = arg.type.isClass ? ap : ap.push(.anyValueFields)
if escapeInfo.isEscapingWhenWalkingDown(object: arg, path: argPath,
visitUse: { op, path, followStores in
if op.instruction == returnInst {
// The argument escapes to the function return
if followStores {
// The escaping path must not introduce a followStores.
return .markEscaping
}
if let ta = toSelection {
if ta.value != .returnValue { return .markEscaping }
toSelection = Selection(.returnValue, pathPattern: path.merge(with: ta.pathPattern))
} else {
toSelection = Selection(.returnValue, pathPattern: path)
}
return .ignore
}
if isOperandOfRecursiveCall(op) {
return .ignore
}
return .continueWalking
},
visitDef: { def, path, followStores in
guard let destArg = def as? FunctionArgument else {
return .continueWalkingUp
}
// The argument escapes to another argument (e.g. an out or inout argument)
if followStores {
// The escaping path must not introduce a followStores.
return .markEscaping
}
let argIdx = destArg.index
if let ta = toSelection {
if ta.value != .argument(argIdx) { return .markEscaping }
toSelection = Selection(.argument(argIdx), pathPattern: path.merge(with: ta.pathPattern))
} else {
toSelection = Selection(.argument(argIdx), pathPattern: path)
}
return .continueWalkingDown
}) {
return false
}
let fromSelection = Selection(arg, pathPattern: argPath)
guard let toSelection = toSelection else {
newEffects.push(ArgumentEffect(.notEscaping, selectedArg: fromSelection))
return true
}
// If the function never returns, the argument can not escape to another arg/return.
guard let returnInst = returnInst else {
return false
}
let exclusive = isExclusiveEscape(fromArgument: arg, fromPath: argPath, to: toSelection, returnInst, &escapeInfo)
newEffects.push(ArgumentEffect(.escaping(toSelection, exclusive), selectedArg: fromSelection))
return true
}
/// Returns a set of argument indices for which there are "defined" effects (as opposed to derived effects).
private func getArgIndicesWithDefinedEffects(of function: Function) -> Set<Int> {
var argsWithDefinedEffects = Set<Int>()
for effect in function.effects.argumentEffects {
if effect.isDerived { continue }
if case .argument(let argIdx) = effect.selectedArg.value {
argsWithDefinedEffects.insert(argIdx)
}
switch effect.kind {
case .notEscaping:
break
case .escaping(let to, _):
if case .argument(let toArgIdx) = to.value {
argsWithDefinedEffects.insert(toArgIdx)
}
}
}
return argsWithDefinedEffects
}
/// Returns true if `op` is passed to a recursive call to the current function -
/// at the same argument index.
private func isOperandOfRecursiveCall(_ op: Operand) -> Bool {
let inst = op.instruction
if let applySite = inst as? FullApplySite,
let callee = applySite.referencedFunction,
callee == inst.function,
let argIdx = applySite.argumentIndex(of: op),
op.value == callee.arguments[argIdx] {
return true
}
return false
}
/// Returns true if when walking from the `toSelection` to the `fromArgument`,
/// there are no other arguments or escape points than `fromArgument`. Also, the
/// path at the `fromArgument` must match with `fromPath`.
private
func isExclusiveEscape(fromArgument: Argument, fromPath: Path, to toSelection: Selection,
_ returnInst: ReturnInst, _ escapeInfo: inout EscapeInfo) -> Bool {
switch toSelection.value {
// argument -> return
case .returnValue:
if escapeInfo.isEscaping(
object: returnInst.operand, path: toSelection.pathPattern,
visitUse: { op, path, followStores in
if op.instruction == returnInst {
if followStores { return .markEscaping }
if path.matches(pattern: toSelection.pathPattern) {
return .ignore
}
return .markEscaping
}
return .continueWalking
},
visitDef: { def, path, followStores in
guard let arg = def as? FunctionArgument else {
return .continueWalkingUp
}
if followStores { return .markEscaping }
if arg == fromArgument && path.matches(pattern: fromPath) {
return .continueWalkingDown
}
return .markEscaping
}) {
return false
}
// argument -> argument
case .argument(let toArgIdx):
let toArg = returnInst.function.arguments[toArgIdx]
if escapeInfo.isEscaping(object: toArg, path: toSelection.pathPattern,
visitDef: { def, path, followStores in
guard let arg = def as? FunctionArgument else {
return .continueWalkingUp
}
if followStores { return .markEscaping }
if arg == fromArgument && path.matches(pattern: fromPath) { return .continueWalkingDown }
if arg == toArg && path.matches(pattern: toSelection.pathPattern) { return .continueWalkingDown }
return .markEscaping
}) {
return false
}
}
return true
}
| true
|
1eaf6e5f46568c2ce89162f6fe600270b5711080
|
Swift
|
sergeybutorin/cashmeter
|
/Cashmeter/UserStories/SpendingStory/Spending/Interactor/SpendingInteractorOutput.swift
|
UTF-8
| 667
| 2.703125
| 3
|
[] |
no_license
|
//
// SpendingInteractorOutput.swift
// Cashmeter
//
// Created by Sergey Butorin on 22/04/2018.
// Copyright © 2018 Sergey Butorin. All rights reserved.
//
protocol SpendingInteractorOutput: class {
/**
Метод сообщает, что парсинг чека завершился успешно.
@param receiptInfo - распаршенные данные чека.
*/
func didParsedReceipt(with receiptInfo: ReceiptInfo)
/**
Метод сообщает, что парсинг чека завершился с ошибкой.
@param error - ошибка.
*/
func didFailParseReceipt(error: String)
}
| true
|
66577a165391aa17476ed11d93e63d0682f9e845
|
Swift
|
anishspillai/MallOfShopping
|
/MallOfShopping/Model/OrderedItems.swift
|
UTF-8
| 1,972
| 2.953125
| 3
|
[] |
no_license
|
//
// OrderedItems.swift
// MallOfShopping
//
// Created by Anish Pillai on 2020-04-13.
// Copyright © 2020 URV. All rights reserved.
//
import SwiftUI
import Combine
final class OrderedItems: ObservableObject {
@Published var orderedGroceries = [ORDERS]()
var total: Int {
if orderedGroceries.count > 0 {
return orderedGroceries.reduce(0) { $0 + $1.noOfItems }
} else {
return 0
}
}
var totalCost: String {
if (!orderedGroceries.isEmpty) {
//return "\(orderedGroceries.reduce(0) { $0 + Float($1.noOfItems) * $1.price}) Kr"
return String(format: "%.2f", orderedGroceries.reduce(0) { $0 + Float($1.noOfItems) * $1.price}) + " Kr"
} else {
return "0 Kr"
}
}
func add(item: ORDERS) {
orderedGroceries.append(item)
}
func removeGroceryFromTheList(idOfTheItem: String) {
let indexOfItem = self.orderedGroceries.firstIndex(where: { $0.id == idOfTheItem })
if(indexOfItem != nil) {
self.orderedGroceries.remove(at: (indexOfItem!))
}
}
func updateOrderCount(idOfTheItem: String, noOfItems: Int) {
let indexOfItem: Int = self.orderedGroceries.firstIndex(where: { $0.id == idOfTheItem })!
self.orderedGroceries[indexOfItem].noOfItems = noOfItems
}
func increament(idOfTheItem: String) {
let indexOfItem: Int = self.orderedGroceries.firstIndex(where: { $0.id == idOfTheItem })!
self.orderedGroceries[indexOfItem].noOfItems += 1
}
func decrement(idOfTheItem: String) {
let indexOfItem: Int = self.orderedGroceries.firstIndex(where: { $0.id == idOfTheItem })!
if(self.orderedGroceries[indexOfItem].noOfItems == 1) {
self.orderedGroceries.remove(at: (indexOfItem))
} else {
self.orderedGroceries[indexOfItem].noOfItems -= 1
}
}
}
| true
|
58c3a37409753fd918f1d529465ebac1e85aaa9f
|
Swift
|
cbracken/FlutterBar
|
/FlutterBar/FlutterStatusController.swift
|
UTF-8
| 2,668
| 2.78125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
//
// FlutterStatusController.swift
// FlutterBar
//
// Created by Chris Bracken on 25/5/17.
// Copyright © 2017 Chris Bracken. All rights reserved.
//
import Cocoa
enum BuildStatus {
case passing
case failing
case unknown
}
class FlutterStatusController : NSObject {
let statusItem = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength)
override init() {
super.init()
statusItem.menu = FlutterStatusController.createStatusMenu(target: self)
if let button = statusItem.button {
button.image = #imageLiteral(resourceName: "StatusBarIconRed")
button.image?.isTemplate = true
}
}
private class func createStatusMenu(target: AnyObject) -> NSMenu {
let statusMenu = NSMenu(title: "FlutterBar")
let openItem = NSMenuItem(title: "Open Dashboard...", action: #selector(FlutterStatusController.openDashboard(sender:)), keyEquivalent: "")
openItem.target = target
statusMenu.addItem(openItem)
let quitItem = NSMenuItem(title: "Quit", action: #selector(FlutterStatusController.quit(sender:)), keyEquivalent: "")
quitItem.target = target
statusMenu.addItem(quitItem)
return statusMenu
}
func openDashboard(sender: NSMenuItem) {
let dashboardUrl = URL(string: "https://flutter-dashboard.appspot.com/build.html")!
NSWorkspace.shared().open(dashboardUrl)
}
func quit(sender: NSMenuItem) {
NSApplication.shared().terminate(self)
}
func poll(interval: TimeInterval) {
Timer.scheduledTimer(withTimeInterval: interval, repeats: true, block: { [weak self] timer in self?.updateStatus() })
}
func updateStatus() {
let requestUrl = URL(string: "https://flutter-dashboard.appspot.com/api/public/build-status")!
let request = URLRequest(url: requestUrl)
let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
guard let data = data else {
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] {
if let result = json["AnticipatedBuildStatus"] {
let status = result == "Succeeded" ? BuildStatus.passing : BuildStatus.failing
DispatchQueue.main.async {
self?.updateStatusIcon(status: status)
}
}
}
} catch let parseError {
print("JSON parsing error: \(parseError)");
}
}
task.resume()
}
func updateStatusIcon(status: BuildStatus) {
if let image = statusItem.button?.image {
if (status == .passing) {
image.isTemplate = true
} else if (status == .failing) {
image.isTemplate = false
}
}
}
}
| true
|
35f4fee4db85ae668b7e6dd566271acf5155a81d
|
Swift
|
glushchenko/fsnotes
|
/FSNotes/Git/commons/Error.swift
|
UTF-8
| 2,313
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// Error.swift
// Git2Swift
//
// Created by Damien Giron on 31/07/2016.
// Copyright © 2016 Creabox. All rights reserved.
//
import Foundation
import Cgit2
public enum GitError : Error {
case invalidSHA(sha: String)
case notFound(ref: String)
case invalidSpec(spec: String)
case alreadyExists(ref: String)
case ambiguous(msg: String)
case invalidReference(msg: String, type: ReferenceType)
case unknownReference(msg: String)
case unknownError(msg: String, code: Int32, desc: String)
case unableToMerge(msg: String)
case modifiedElsewhere(ref: String)
case notImplemented(msg: String)
case uncommittedConflict
case noAddedFiles
func associatedValue() -> String {
switch self {
case .invalidSHA(sha: let sha):
return "Invalid sha \(sha)"
case .notFound(ref: let ref):
return "Not found ref \(ref)"
case .invalidSpec(spec: let spec):
return "Invalid spec \(spec)"
case .alreadyExists(ref: let ref):
return "Already exist ref \(ref)"
case .ambiguous(msg: let msg):
return "Ambiguous \(msg)"
case .invalidReference(msg: let msg, type: let type):
return "Invalid ref \(msg) \(type)"
case .unknownReference(msg: let msg):
return "Unknown ref \(msg)"
case .unknownError(msg: let msg, code: let code, desc: let desc):
return "\(msg) \(code) \(desc)"
case .unableToMerge(msg: let msg):
return "Unable to merge \(msg)"
case .modifiedElsewhere(ref: let ref):
return "Modified error \(ref)"
case .notImplemented(msg: let msg):
return "Not implemented \(msg)"
case .uncommittedConflict:
return "Uncommitted conflict"
case .noAddedFiles:
return "New files not found"
}
}
}
func gitUnknownError(_ msg: String, code: Int32) -> GitError {
return GitError.unknownError(msg: msg, code: code, desc: git_error_message())
}
///
/// Error message.
/// - Returns message.
///
func git_error_message() -> String {
let error = giterr_last()
if (error != nil) {
return "\(String(cString: error!.pointee.message))"
} else {
return ""
}
}
| true
|
045a03aa8743c8a625b3096edc30ca5cfc9d1957
|
Swift
|
Neemaphilippe/people-and-stocks-debugging
|
/PeopleAndAppleStockPrices/PeopleAndAppleStockPrices/StocksTableViewController.swift
|
UTF-8
| 1,510
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// PeopleAndAppleStockPrices
//
// Created by Alex Paul on 12/7/18.
// Copyright © 2018 Pursuit. All rights reserved.
//
import UIKit
class StocksTableViewController: UIViewController {
var stocks = [StocksByMonthAndYear]()
@IBOutlet weak var stocksTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
stocksTableView.dataSource = self
loadData()
}
private func loadData() {
stocks = Stock.getStocksSortedByMonthAndYear()
}
}
extension StocksTableViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return stocks.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stocks[section].stocks.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let stock = stocks[section]
return "\(stock.month) \(stock.year). AVG: \(stock.getMonthAverage())"
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let stock = stocks[indexPath.section].stocks[indexPath.row]
let cell = stocksTableView.dequeueReusableCell(withIdentifier: "stockCell", for: indexPath)
cell.textLabel?.text = "\(stock.day) \(stock.month) \(stock.year)"
cell.detailTextLabel?.text = "\(stock.uOpen)"
return cell
}
}
| true
|
a635df8fb56b1d9bc6d642ad8a46d49da9b2108d
|
Swift
|
ZhongshanHuang/KitDemo
|
/KitDemo/PotatoComponent/Extension/Foundation/Data+extension.swift
|
UTF-8
| 402
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// Data+extension.swift
// KitDemo
//
// Created by 黄山哥 on 2019/5/20.
// Copyright © 2019 黄中山. All rights reserved.
//
import Foundation
// MARK: - String isEmpty
extension Optional where Wrapped == Data {
var isEmpty: Bool {
switch self {
case .some(let value):
return value.isEmpty
case .none:
return true
}
}
}
| true
|
b1bf3cffb836995a4fb99160ef8898b6096c3fc8
|
Swift
|
jtcreative/ingine-ios
|
/ingine/ingine/TutorialViewController.swift
|
UTF-8
| 6,715
| 2.515625
| 3
|
[] |
no_license
|
//
// TutorialViewController.swift
// ingine
//
// Created by James Timberlake on 6/16/20.
// Copyright © 2020 ingine. All rights reserved.
//
import Foundation
import UIKit
class TutorialViewController : UIPageViewController {
let closeButton = UIButton()
let backButton = UIButton()
let nextButton = UIButton()
lazy var pageViews : [UIViewController] = {
return [
TutorialImageViewController(imageName: "tutorial1"),
TutorialImageViewController(imageName: "tutorial2"),
TutorialImageViewController(imageName: "tutorial3"),
TutorialImageViewController(imageName: "tutorial4"),
TutorialImageViewController(imageName: "tutorial5"),
TutorialImageViewController(imageName: "tutorial6") ]
}()
override func viewDidLoad() {
super.viewDidLoad()
UserDefaults.setSetting(setting: .DidViewTutorialPage, asValue: true)
setViewControllers([pageViews.first!], direction: .forward, animated: true, completion: { result in
})
dataSource = self
delegate = self
closeButton.setTitle("Close", for: .normal)
backButton.setTitle("Back", for: .normal)
nextButton.setTitle("Next", for: .normal)
closeButton.addTarget(self, action: #selector(closeView), for: .touchUpInside)
backButton.addTarget(self, action: #selector(backPage), for: .touchUpInside)
backButton.backgroundColor = .gray
backButton.alpha = 0.7
backButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
nextButton.addTarget(self, action: #selector(nextPage), for: .touchUpInside)
nextButton.backgroundColor = .gray
nextButton.alpha = 0.7
nextButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
view.addSubview(closeButton)
view.addSubview(backButton)
view.addSubview(nextButton)
closeButton.translatesAutoresizingMaskIntoConstraints = false
backButton.translatesAutoresizingMaskIntoConstraints = false
nextButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
closeButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
closeButton.heightAnchor.constraint(equalToConstant: 60).isActive = true
backButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
backButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
backButton.heightAnchor.constraint(equalToConstant: 60).isActive = true
nextButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
nextButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
nextButton.heightAnchor.constraint(equalToConstant: 60).isActive = true
updateButtons(atIndex: 0)
}
}
extension TutorialViewController : UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let index = pageViews.firstIndex { (vc) -> Bool in
return (vc == viewController)
}
guard index != nil,
index! > 0 else {
return nil
}
let beforeIndex = pageViews.index(before: index!)
return pageViews[beforeIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let index = pageViews.firstIndex { (vc) -> Bool in
return (vc == viewController)
}
guard index != nil,
index! < (pageViews.count - 1) else {
return nil
}
let nextIndex = pageViews.index(after: index!)
return pageViews[nextIndex]
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
guard let vc = viewControllers?.first,
let index = pageViews.firstIndex(of:vc) else {
return 1
}
updateButtons(atIndex: (index))
return 1
}
}
extension TutorialViewController : UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
guard let vc = previousViewControllers.first,
let index = pageViews.firstIndex(of:vc) else {
return
}
updateButtons(atIndex: (index + 1))
}
}
extension TutorialViewController {
@objc func closeView() {
presentingViewController?.dismiss(animated: true, completion: nil)
}
@objc func backPage() {
guard let currentPage = viewControllers?.first,
let currentIndex = pageViews.firstIndex(of: currentPage),
currentIndex > 0 else {
return
}
let prevIndex = pageViews.index(before: currentIndex)
setViewControllers([pageViews[prevIndex]], direction: .reverse, animated: true, completion: nil)
updateButtons(atIndex: prevIndex)
}
@objc func nextPage() {
guard let currentPage = viewControllers?.first,
let currentIndex = pageViews.firstIndex(of: currentPage),
currentIndex < (pageViews.count - 1) else {
closeView()
return
}
let nextIndex = pageViews.index(after: currentIndex)
setViewControllers([pageViews[nextIndex]], direction: .forward, animated: true, completion: nil)
updateButtons(atIndex: nextIndex)
}
func updateButtons(atIndex index:Int) {
guard index > 0 else {
backButton.isHidden = true
nextButton.setTitle("Next", for: .normal)
return
}
guard index < (pageViews.count - 1) else {
nextButton.setTitle("Finish", for: .normal)
return
}
backButton.isHidden = false
nextButton.setTitle("Next", for: .normal)
}
}
extension TutorialViewController {
override var supportedInterfaceOrientations:UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override var shouldAutorotate: Bool {
return false
}
}
| true
|
1d1b3248f21cd589988f03392be7fb53bdec7883
|
Swift
|
skaplar/eServices
|
/eUsluge/Networking/NewNetworkingClient.swift
|
UTF-8
| 992
| 2.890625
| 3
|
[] |
no_license
|
//
// NewNetworkingClient.swift
// eUsluge
//
// Created by Sebastijan Kaplar on 1/15/19.
// Copyright © 2019 Sebastijan Kaplar. All rights reserved.
//
import Foundation
import Alamofire
class NewNetworkingClient {
func genericFetch<T: Decodable>(urlString: String, completion: @escaping (T) -> ()) {
Alamofire.AF.request(urlString, method: .get).validate(statusCode: 200..<300).response { response in
guard response.error == nil else {
print("error calliing on \(urlString)")
return
}
guard let data = response.data else {
print("there was an error with the data")
return
}
do {
let model = try JSONDecoder().decode(T.self, from: data)
completion(model)
} catch let jsonErr {
print("failed to decode, \(jsonErr)")
}
}
}
}
| true
|
8bc8594dda49e52978d1c63c9559e068056104cf
|
Swift
|
AashAgarwal/iOS-App-Development
|
/DataPersistenceProject/DataPersistenceProject/ViewController.swift
|
UTF-8
| 1,825
| 2.859375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// DataPersistenceProject
//
// Created by Aashwatth Agarwal on 7/24/19.
// Copyright © 2019 Aashwatth Agarwal. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var darkModeSwitch: UISwitch!
var isDarkModeEnabled: Bool {
get {
return UserDefaults.standard.bool(forKey: "darkModeEnabled")
}
set {
UserDefaults.standard.set(newValue, forKey: "darkModeEnabled")
}
}
let manager = CoreDataManager()
override func viewDidLoad() {
super.viewDidLoad()
darkModeSwitch.isOn = isDarkModeEnabled
let people = manager.getAllPersons()
print(people)
addClass()
let newPeople = manager.getAllPersons()
print(newPeople)
let selectPeople = manager.getAllPeople(named: "Chris")
print(selectPeople)
// manager.delete(person: people[0])
// manager.save()
// print(manager.getAllPersons())
// print(people[0].name)
// let updatedPerson = manager.update(person: people[0], with: "CH")
// print(updatedPerson)
// manager.save()
// print(people)
// print(people[0].name)
// print(people)
// print(manager.createNewPerson(with: "Chris"))
// manager.save()
// print(manager.getAllPersons())
}
func addClass() {
manager.createNewPerson(with: "Ryan")
manager.createNewPerson(with: "Chris")
manager.createNewPerson(with: "iTony")
manager.createNewPerson(with: "Aash")
manager.createNewPerson(with: "Brian")
manager.save()
}
@IBAction func switchTapped(_ sender: Any) {
isDarkModeEnabled = !isDarkModeEnabled
}
}
| true
|
015bc0b1dcea17d84473f3ace66d059073ad8d7b
|
Swift
|
shakaib-developer/Assignment-4-AnimatedSet
|
/GraphicalSet-Assignment3/SetGame.swift
|
UTF-8
| 2,142
| 3.234375
| 3
|
[] |
no_license
|
//
// Set.swift
// GraphicalSet-Assignment3
//
// Created by Shakaib Akhtar on 21/08/2019.
// Copyright © 2019 iParagons. All rights reserved.
//
import Foundation
import UIKit
class SetGame {
var cards = [SetCard]()
var shapesArray = ["squiggles", "diamonds", "ovals"]
var colorsDict = ["red": #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1),"green": #colorLiteral(red: 0, green: 0.9768045545, blue: 0, alpha: 1), "purple": #colorLiteral(red: 0.5791940689, green: 0.1280144453, blue: 0.5726861358, alpha: 1)]
var fillingArray = ["filled","outline","striped"]
var countArray = [1, 2, 3]
init() {
for shapeValue in shapesArray {
for (_, colorValue) in colorsDict {
for fillingValue in fillingArray {
for count in countArray.indices {
let tempCard = SetCard(count: countArray[count], shape: shapeValue, color: colorValue, filling: fillingValue)
cards.append(tempCard)
}
}
}
}
}
func isMatch(selectedCards: Set<SetCard>) -> Bool {
var x = Array(selectedCards)
let numbersFeatures = Set([x[0].count, x[1].count, x[2].count])
let colorsFeatures = Set([x[0].color, x[1].color, x[2].color])
let symbolsFeatures = Set([x[0].shape, x[1].shape, x[2].shape])
let shadingsFeatures = Set([x[0].filling, x[1].filling, x[2].filling])
return (numbersFeatures.count == 1 || numbersFeatures.count == 3) &&
(colorsFeatures.count == 1 || colorsFeatures.count == 3) &&
(symbolsFeatures.count == 1 || symbolsFeatures.count == 3) &&
(shadingsFeatures.count == 1 || shadingsFeatures.count == 3)
}
func getCardProperties() -> SetCard? {
if cards.count > 0 {
let cardIndex = cards.count.arc4random
return cards.remove(at: cardIndex)
}
else {
return nil
}
}
}
| true
|
28519131d9d21a924b46ba66caecd68c92b17381
|
Swift
|
AlanVHz/iOSDevelopmentLab
|
/login/login/extensions.swift
|
UTF-8
| 519
| 2.6875
| 3
|
[] |
no_license
|
//
// extensions.swift
// login
//
// Created by Alan Vargas on 3/1/19.
// Copyright © 2019 Alan Vargas. All rights reserved.
//
import Foundation
import UIKit
extension UIColor{
// funcion de clase - significa que se puede usar sin necesidad de ser instanciada
class func myNavBarBackground() -> UIColor {
return UIColor(red:0.13, green:0.19, blue:0.25, alpha:1.0)
}
class func buttonsColor() -> UIColor {
return UIColor(red:0.77, green:0.94, blue:0.97, alpha:1.0)
}
}
| true
|
1c111675374bfcb7bc4ee36f7a17371a2b5916ae
|
Swift
|
Huang-lala/SAVIN_3
|
/FoodPin/Model/Restaurant.swift
|
UTF-8
| 5,998
| 2.984375
| 3
|
[] |
no_license
|
//
// Restaurant.swift
// FoodPin
//
// Created by NDHU_CSIE on 2020/11/19.
// Copyright © 2020 NDHU_CSIE. All rights reserved.
//
import UIKit
import CoreData
class Restaurant {
var name: String
var type: String
var location: String
var phone: String
var summary: String
var image: String
var isVisited: Bool
var rating: String
init(name: String, type: String, location: String, phone: String, summary: String, image: String, isVisited: Bool) {
self.name = name
self.type = type
self.location = location
self.phone = phone
self.summary = summary
self.image = image
self.isVisited = isVisited
self.rating = ""
}
static func writeRestaurantFromBegin() {
let sourceArray: [Restaurant] = [
Restaurant(name: "CACO", type: "Fashion Store", location: "台北市中正區忠孝西路一段47號B1 (台北車站K區地下街)", phone: "(02)2383-2529", summary: "CACO品牌起源2012年成立,台灣最大『美式授權服飾品牌』,擁有全台70間直營門市及自建官網,海外馬來西亞直營店。近年更快速整合實體門市與電商平台服務,提供消費者更優質體驗,並積極參與公益活動及社會回饋。", image: "cafedeadend.jpg", isVisited: false),
Restaurant(name: "QUEEN SHOP", type: "Fashion Store", location: "台北市大安區敦化南路一段161巷24號", phone: "(02)2771-9922", summary: "台灣原創自有品牌服裝不僅是外在表象,而是內蘊的生活感受呈現在季節與質感間取得完美平衡設計出實穿的衣著品給認真看待生活的你,擁有隨心所欲的勇氣穿喜歡的衣服wearing & showing做自己好看的樣子。", image: "Queenshop.jpg", isVisited: false),
Restaurant(name: "NET", type: "Fashion Store", location: "106071台北市大安區忠孝東路四段59號61號", phone: "(02)2721-4817", summary: "NET 以歐美休閒風格為基調,推出各個年齡層顧客都需要的商品,期待讓一家人都能找到適合自己的服飾,用「全家人的品牌」做為訴求以與一般平價服飾品牌產生市場區隔。", image: "teakha.jpg", isVisited: false),
Restaurant(name: "50% FIFTY PERCENT", type: "Fashion Store", location: "108台北市萬華區漢中街41-1號", phone: "(02)2382-5188", summary: "A Philosophy Let's dress up in chic style of youth. Making the vogue which easy to obtain.Catalyst Always stick to the fashion.Personality Have fun making my own costumes.Vision The campaign to spread the vogue of youth could make fans more self-confidence and charming.", image: "cafeloisl.jpg", isVisited: false),
Restaurant(name: "UNIQLO", type: "Fashion Store", location: "10444 台北市中山區南京西路15號6F", phone: "(02)2522-2801", summary:"源於日本價值之簡約風格、優越品質、經典品味,我們與時俱進、汲取時代靈感,以優雅的現代風尚,演繹出你的品味生活。精益求精的完美單品,簡約設計,低調藏著貼心的細節。精緻合身的剪裁與質感,讓每個人都輕鬆擁有舒適人生。", image: "petiteoyster.jpg", isVisited: false),
Restaurant(name: "GAP", type: "Fashion Store", location: "台北市信義區松壽路12號", phone: "(02)7737-9668", summary: "1969年,GAP的創始人當勞‧費雪正在美國加州的一家時裝店裏,挑選適合自己的牛仔褲。 可是選來選去都找不到一條合適的。 在這種動力的驅使下,當勞‧費雪創造了這一美國歷史性品牌---GAP。", image: "forkeerestaurant.jpg", isVisited: false),
Restaurant(name: "GU", type: "Fashion Store", location: "台北市南港區忠孝東路七段369號5樓", phone: "(02)2783-6456", summary: "來自東京最新潮流時尚。GU就是現在!代表東京時尚態度!將全球流行趨勢以東京潮流風格呈現友善的價格,讓人隨心所欲盡情享受自由穿搭,滿足了年輕人熱愛時尚的想像,藉由WERA TOKYO NOW宣言將自由時尚能量,帶給所有人。", image: "posatelier.jpg", isVisited: false),
Restaurant(name: "ZARA", type: "Fashion Store", location: "06台北市大安區忠孝東路四段201號", phone: "(02)2778-5080", summary: "Zara 是最重要的國際化時裝公司之一。屬於Inditex,世界上最大的經銷集團之一。我們通過自有商店網路將設計、製造、配送和銷售整合在一起,形成了獨特的商業模式,而客戶是這一模式的中心。", image: "bourkestreetbakery.jpg", isVisited: false),
Restaurant(name: "H&M", type: "Fashion Store", location: "108台北市萬華區漢中街116號", phone: "(02)7726-6666", summary: "We are a family of brands, driven by our desire to make great design available to everyone in a sustainable way. Together we offer fashion, design and services, that enable people to be inspired and to express their own personal style, making it easier to live in a more circular way.", image: "haighschocolate.jpg", isVisited: false),
]
var restaurant: RestaurantMO!
if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
for i in 0..<sourceArray.count {
restaurant = RestaurantMO(context: appDelegate.persistentContainer.viewContext)
restaurant.name = sourceArray[i].name
restaurant.type = sourceArray[i].type
restaurant.location = sourceArray[i].location
restaurant.phone = sourceArray[i].phone
restaurant.summary = sourceArray[i].summary
restaurant.isVisited = false
restaurant.rating = nil
restaurant.image = UIImage(named: sourceArray[i].image)!.pngData()
}
appDelegate.saveContext() //write once for all new restauranrs
}
}
}
| true
|
ef2d0e99ec5fc9a847758ab0a397a511f62bec2a
|
Swift
|
GregKeeley/HSData_Coding_Assessment
|
/HSData_Coding_Assessment/High School Detail View/HighSchoolDetailViewController.swift
|
UTF-8
| 3,461
| 2.59375
| 3
|
[] |
no_license
|
//
// HighSchoolDetailViewController.swift
// HSData_Coding_Assessment
//
// Created by Gregory Keeley on 5/5/21.
//
import UIKit
class HighSchoolDetailViewController: UIViewController {
//MARK:- IBOutlets
@IBOutlet weak var highSchoolNameLabel: UILabel!
@IBOutlet weak var numOfTestTakersLabel: UILabel!
@IBOutlet weak var totalSATScoreLabel: UILabel!
@IBOutlet weak var avgMathScoreLabel: UILabel!
@IBOutlet weak var avgReadingScoreLabel: UILabel!
@IBOutlet weak var avgWritingScoreLabel: UILabel!
@IBOutlet weak var totalSATScoreProgressBar: UIProgressView!
@IBOutlet weak var mathProgressBar: CustomProgressBar!
@IBOutlet weak var readingProgressBar: CustomProgressBar!
@IBOutlet weak var writingProgressBar: CustomProgressBar!
//MARK:- Variables/Constants
var satScoreViewModel: HighSchoolSATScoreViewModel?
//MARK:- Initializer
init(satScoreViewModel: HighSchoolSATScoreViewModel) {
self.satScoreViewModel = satScoreViewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
//MARK:- View Life Cycles
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.prefersLargeTitles = false
navigationController?.navigationBar.tintColor = .white
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
override func viewWillDisappear(_ animated: Bool) {
navigationController?.navigationBar.prefersLargeTitles = true
}
//MARK:- Functions
private func configureView() {
highSchoolNameLabel.text = satScoreViewModel?.schoolName
highSchoolNameLabel.tintColor = AppColors.primaryDarkBlue
highSchoolNameLabel.font = UIFont.boldSystemFont(ofSize: 36)
highSchoolNameLabel.adjustsFontSizeToFitWidth = true
numOfTestTakersLabel.text = "Total Test Takers: \(satScoreViewModel?.numOfTestTakers ?? -1)"
totalSATScoreLabel.text = "\(satScoreViewModel?.totalSATScore ?? -1)"
avgMathScoreLabel.text = "\(satScoreViewModel?.avgMathScore ?? -1)"
avgReadingScoreLabel.text = "\(satScoreViewModel?.avgCriticalReadingScore ?? -1)"
avgWritingScoreLabel.text = "\(satScoreViewModel?.avgWritingScore ?? -1)"
// Note: SAT Scoring and ranges based on the calculator found here: https://www.albert.io/blog/sat-score-calculator/
// TODO: Make a better calculation for the progress bar to more accurately reflect the score for each subject
totalSATScoreProgressBar.tintColor = AppColors.primaryDarkBlue
totalSATScoreProgressBar.progress = Float(Double(satScoreViewModel?.totalSATScore ?? 0) / 1600)
mathProgressBar.gradientColors = [AppColors.primaryGreen.cgColor, AppColors.primaryGreen.cgColor]
mathProgressBar.progress = CGFloat(Double(satScoreViewModel?.avgMathScore ?? 0) / 600)
readingProgressBar.gradientColors = [AppColors.primaryOrange.cgColor, AppColors.primaryOrange.cgColor]
readingProgressBar.progress = CGFloat(Double(satScoreViewModel?.avgCriticalReadingScore ?? 0) / 500)
writingProgressBar.gradientColors = [AppColors.primaryLiteBlue.cgColor, AppColors.primaryLiteBlue.cgColor]
writingProgressBar.progress = CGFloat(Double(satScoreViewModel?.avgWritingScore ?? 0) / 500)
}
}
| true
|
9bb9f604bbb53c4e25ef4f3492e4f8622331d616
|
Swift
|
nimrodzhang/Muti-calendar
|
/Muti-calendar/BackgroundViewController.swift
|
UTF-8
| 8,108
| 2.8125
| 3
|
[] |
no_license
|
//
// BackgroundViewController.swift
// Muti-calendar
//
// Created by Apple on 2017/12/26.
// Copyright © 2017年 Apple. All rights reserved.
//
import UIKit
import CoreData
class BackgroundViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var BackgroundCollectionView: UICollectionView!
var images: Array<UIImage> = []
var ChosenImage: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
BackgroundCollectionView.delegate = self
BackgroundCollectionView.dataSource = self
loadPhotos()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Collection View
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10 + images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.row == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImagePickerCell", for: indexPath) as! ImagePickerCollectionViewCell
return cell
}
else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BackgroundCell", for: indexPath) as! BackgroundCollectionViewCell
let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(cellLongPressed(recognizer:)))
cell.addGestureRecognizer(gestureRecognizer)
if indexPath.row < images.count+1 {
cell.backgroundImageView.image = images[indexPath.row-1]
}
else {
cell.backgroundImageView.image = UIImage(named: "BGI\(indexPath.row-images.count-1)")
}
return cell
}
}
@objc func cellLongPressed(recognizer: UIGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.began {
let location = recognizer.location(in: self.BackgroundCollectionView)
let indexPath = self.BackgroundCollectionView.indexPathForItem(at: location)!
if indexPath.row > 0 && indexPath.row < images.count+1 {
let alert = UIAlertController(title: "删除这个背景?", message: nil, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let confirmAction = UIAlertAction(title: "确定", style: .destructive, handler: { (action) in
let cell = self.BackgroundCollectionView.cellForItem(at: indexPath) as! BackgroundCollectionViewCell
let image = cell.backgroundImageView.image
let index = self.images.index(of: image!)
self.images.remove(at: index!)
self.deleteAPhoto(selectedImage: image!)
self.BackgroundCollectionView.reloadData()
})
alert.addAction(cancelAction)
alert.addAction(confirmAction)
self.present(alert, animated: true, completion: nil)
}
else {
let alert = UIAlertController(title: "该背景不能删除", message: nil, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
alert.addAction(confirmAction)
self.present(alert, animated: true, completion: nil)
}
}
}
@IBAction func chooseImageFromLibrary(_ sender: UIButton) {
let imagePickerController = UIImagePickerController()
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
//MARK: - ImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
images.append(selectedImage)
addAPhoto(selectedImage: selectedImage)
self.BackgroundCollectionView.reloadData()
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
func loadPhotos() {
if !images.isEmpty {
images.removeAll()
}
let appDel = UIApplication.shared.delegate as! AppDelegate
let container = appDel.persistentContainer
let context = container.viewContext
let fetch: NSFetchRequest<Bgimage> = Bgimage.fetchRequest()
//fetch.predicate = NSPredicate(format: "??? == %@", NSNumber(value: curWeekday))
do {
let photoDatas = try context.fetch(fetch)
for imageData in photoDatas {
let temp = UIImage(data: imageData.photoData! as Data)
images.append(temp!)
}
}catch let error {
print("load error:\(error)")
}
}
func addAPhoto(selectedImage: UIImage) {
let appDel = UIApplication.shared.delegate as! AppDelegate
let container = appDel.persistentContainer
let context = container.viewContext
let image = NSEntityDescription.insertNewObject(forEntityName: "Bgimage", into: context) as! Bgimage
let imageData = UIImagePNGRepresentation(selectedImage)! as NSData
image.photoData = imageData
do {
try context.save()
}catch {
print("save error at newcoursemanually")
}
}
func deleteAPhoto(selectedImage: UIImage) {
let appDel = UIApplication.shared.delegate as! AppDelegate
let container = appDel.persistentContainer
let context = container.viewContext
let fetch: NSFetchRequest<Bgimage> = Bgimage.fetchRequest()
let imageData = UIImagePNGRepresentation(selectedImage)! as NSData
fetch.predicate = NSPredicate(format: "photoData == %@", imageData)
do {
let rsts = try context.fetch(fetch)
for data in rsts {
context.delete(data)
}
}catch {
print("seek error at bg table")
}
do {
try context.save()
}catch {
print("context can't save! at bg table")
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
let des = segue.destination as! CalendarViewController
let cell = sender as! BackgroundCollectionViewCell
ChosenImage = cell.backgroundImageView.image
des.backgroundImage.image = cell.backgroundImageView.image
}
}
| true
|
262e2813f3733e634fc81751520ef770936b1729
|
Swift
|
huangzhentong/leetcode
|
/中等/24. 两两交换链表中的节点.swift
|
UTF-8
| 1,643
| 3.765625
| 4
|
[] |
no_license
|
//
// 24. 两两交换链表中的节点.swift
//
//
// Created by KT--stc08 on 2020/7/9.
//
import Foundation
/*
24. 两两交换链表中的节点
难度
中等
543
收藏
分享
切换为英文
关注
反馈
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
*/
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
class Solution {
func swapPairs(_ head: ListNode?) -> ListNode? {
var allVal = [Int]()
var next = head
while next != nil {
allVal.append(next!.val)
next = next?.next
}
if allVal.count < 2 {
return head
}
else
{
let count = allVal.count / 2
var allNode : ListNode?
for i in 0..<count {
allVal.swapAt(i*2, i*2+1)
}
var nextNode : ListNode?
for val in allVal {
let node = ListNode(val)
if nextNode == nil {
nextNode = node
}
else{
nextNode?.next = node
nextNode = node
}
if allNode == nil {
allNode = nextNode
}
}
return allNode
}
return head
}
}
| true
|
662f75828bcba63258cdf8dfa5fa85b40d6b7f93
|
Swift
|
luanvantotnghiepbaovi2017/JustDraw
|
/JustDraw/JustDraw/ViewModels/TShirtViewModel/TShirtViewModel.swift
|
UTF-8
| 1,493
| 2.765625
| 3
|
[] |
no_license
|
//
// TShirtViewModel.swift
// JustDraw
//
// Created by Bao on 5/12/18.
// Copyright © 2018 TranQuocBao. All rights reserved.
//
import Foundation
import iso4217
class TShirtViewModel: Product {
// MARK: Properties
private var tshirt: TShirt
var nameText: String {
return tshirt.vietnamName
}
var priceText: String {
let price = Price(value: tshirt.price, currency: .vnd)
return "\(price)"
}
var discountPriceText: String {
if productIsNotDiscounted() {
return ""
}
let discountPrice = Price(value: tshirt.price * (1 - (Double(tshirt.discount) / 100.0)), currency: .vnd)
return "\(discountPrice)"
}
var discountInfoText: String {
if productIsNotDiscounted() {
return ""
}
return "-\(tshirt.discount)%"
}
var reviewText: String {
return "(\(tshirt.review))"
}
var storeAddressText: String {
return tshirt.storeAddress
}
var productImage: URL? {
guard let imageURL = URL(string: tshirt.mainImage) else { return nil }
return imageURL
}
var productMainImageHeight: CGFloat {
return tshirt.mainImageHeight
}
// MARK: Constructor
init(tshirt: TShirt) {
self.tshirt = tshirt
}
// MARK: Methods
func productIsNotDiscounted() -> Bool {
return tshirt.discount == 0 ? true : false
}
}
| true
|
fefd994bf0d270d0c9d22dff622769d0396f8760
|
Swift
|
surbhihanda06/ForDonar
|
/ForDonors/CampaignConfirmationPage/Model/PerksToSend.swift
|
UTF-8
| 1,691
| 2.59375
| 3
|
[] |
no_license
|
//
// PerksToSend.swift
// ForDonors
//
// Created by NITS_Mac3 on 31/03/18.
// Copyright © 2018 NATIT. All rights reserved.
//
import Foundation
import ObjectMapper
class PerksToSend: Mappable
{
var campaign_name: String? = ""
var description: String? = ""
var estimated_delivery_date: String? = ""
var id: Int = 0
var perks_image: String? = ""
var price: Int = 0
var shipping: Int = 0
var title: String? = ""
var items: NSMutableArray = NSMutableArray()
/// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point
public required init?(map: Map)
{
}
/// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process.
init(campaign_name: String, description: String, estimated_delivery_date: String, id: Int, perks_image: String, price: Int, title: String) {
self.campaign_name = campaign_name
self.description = description
self.estimated_delivery_date = estimated_delivery_date
self.id = id
self.perks_image = perks_image
self.price = price
self.title = title
}
public func mapping(map: Map)
{
self.campaign_name <- map["campaign_name"]
self.description <- map["description"]
self.estimated_delivery_date <- map["estimatedDeliveryDate"]
self.id <- map["id"]
self.perks_image <- map["perks_image"]
self.price <- map["price"]
self.shipping <- map["shipping"]
self.title <- map["title"]
self.items <- map["items"]
}
}
| true
|
bfbd1ec874a62871be09cefb2ffa364cd0e4e2e5
|
Swift
|
bensu1013/Slycerean
|
/Slycerean/Slycerean/BSAIBattleUnit.swift
|
UTF-8
| 3,651
| 2.71875
| 3
|
[] |
no_license
|
//
// BSAIBattleUnit.swift
// Slycerean
//
// Created by Benjamin Su on 11/2/17.
// Copyright © 2017 Benjamin Su. All rights reserved.
//
import Foundation
import SpriteKit
class BSAIBattleUnit: BSBattleUnit, PathfinderDataSource {
var actionStack = [()->()]()
func takeTurn(inScene scene: BSBattleScene, completion: @escaping () -> ()) {
self.scene = scene
actionStack.append(completion)
let enemyTeam = scene.battleController.userTeam
let pathFinder = AStarPathfinder()
pathFinder.dataSource = self
var paths = [[TileCoord]]()
for unit in enemyTeam.party {
//cant land on unit
var tempPaths = [[TileCoord]]()
if let topPath = pathFinder.shortestPathFromTileCoord(self.tileCoord, toTileCoord: unit.tileCoord.top) {
let path = topPath
tempPaths.append(path)
}
if let bottomPath = pathFinder.shortestPathFromTileCoord(self.tileCoord, toTileCoord: unit.tileCoord.bottom) {
let path = bottomPath
tempPaths.append(path)
}
if let leftPath = pathFinder.shortestPathFromTileCoord(self.tileCoord, toTileCoord: unit.tileCoord.left) {
let path = leftPath
tempPaths.append(path)
}
if let rightPath = pathFinder.shortestPathFromTileCoord(self.tileCoord, toTileCoord: unit.tileCoord.right) {
let path = rightPath
tempPaths.append(path)
}
let shortestPath = tempPaths.sorted(by: { $0.count < $1.count }).first
if let shortestPath = shortestPath {
paths.append(shortestPath)
}
}
if paths.isEmpty {
} else {
paths.sort(by: { $0.count < $1.count })
self.moveComponent.moveAlong(path: paths[0], completion: {
self.spriteComponent.run(SKAction.wait(forDuration: 1.0))
scene.sceneState = .turnEnd
})
}
}
func useActions() {
let wait = SKAction.wait(forDuration: 4.0)
let action = SKAction.run {
let nextAction = self.actionStack.removeLast()
nextAction()
}
let complete = SKAction.run { [weak self] in
if !self!.actionStack.isEmpty {
self?.useActions()
}
}
self.spriteComponent.run(SKAction.sequence([action, wait, complete]))
}
func walkableAdjacentTilesCoordsForTileCoord(_ tileCoord: TileCoord) -> [TileCoord] {
let canMoveUp = scene?.gameBoard.isValidWalkingTile(for: tileCoord.top) ?? false
let canMoveLeft = scene?.gameBoard.isValidWalkingTile(for: tileCoord.left) ?? false
let canMoveDown = scene?.gameBoard.isValidWalkingTile(for: tileCoord.bottom) ?? false
let canMoveRight = scene?.gameBoard.isValidWalkingTile(for: tileCoord.right) ?? false
var walkableCoords = [TileCoord]()
if canMoveUp {
walkableCoords.append(tileCoord.top)
}
if canMoveLeft {
walkableCoords.append(tileCoord.left)
}
if canMoveDown {
walkableCoords.append(tileCoord.bottom)
}
if canMoveRight {
walkableCoords.append(tileCoord.right)
}
return walkableCoords
}
func costToMoveFromTileCoord(_ fromTileCoord: TileCoord, toAdjacentTileCoord toTileCoord: TileCoord) -> Int {
return 5
}
}
| true
|
861224f55bb64addf282f27baf47311d9df5d9c3
|
Swift
|
ezequielbrrt/swiftui-testing
|
/DoMemory/DoMemory/Modules/Menu/MenuView/MenuView.swift
|
UTF-8
| 3,523
| 2.859375
| 3
|
[] |
no_license
|
//
// MenuView.swift
// DoMemory
//
// Created by Ezequiel Barreto on 23/09/20.
//
import SwiftUI
import WaterfallGrid
struct MenuView: View {
@ObservedObject var viewModel = MenuViewModel()
@State var showNewView = false
init() {
UINavigationBar.appearance().largeTitleTextAttributes = [
.foregroundColor: Color.secundaryColor.uiColor(), .font: UIFont.righteous(size: 35)]
UINavigationBar.appearance().titleTextAttributes = [ .foregroundColor: Color.secundaryColor.uiColor(), .font: UIFont.righteous(size: 19)]
}
var body: some View {
NavigationView {
Group {
if viewModel.isLoading {
LoadingView()
} else {
VStack {
NavigationLink(
destination: SettingsView(listener: viewModel),
isActive: $showNewView
) {
EmptyView()
}.isDetailLink(false)
WaterfallGrid(viewModel.memoramaArray) { memorama in
NavigationLink(destination: MemorizeView(viewModel: MemorizeViewModel(memorama: memorama))
.navigationBarTitle("")
.navigationBarHidden(true)
) {
MemoramaCard(memorama: memorama)
}.isDetailLink(true)
}
HStack {
Text(Strings.yourPoints + ": " + viewModel.getUserPoints())
.foregroundColor(.primaryColor)
.font(.patrickHand(size: 25)).padding()
Spacer()
Image("tiendas")
.resizable()
.frame(width: 40, height: 40, alignment: .center).padding()
}
}
}
}
.background(Color.grayBackground)
.navigationBarItems(leading:
Button(action: {
self.showNewView = true
}, label: { Image("configuraciones")
.resizable()
.frame(width: 40, height: 40, alignment: .center) }))
.navigationBarTitle(Text("DoMemory"))
}.onAppear {
print("appear")
}
}
}
struct MemoramaCard: View {
var memorama: Memorama
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 10)
.stroke(lineWidth: 1)
.fill(Color.blue)
VStack(alignment: .leading) {
Text(memorama.name).font(.patrickHand(size: 25))
Text(memorama.name).font(.patrickHand(size: 16)).foregroundColor(.gray)
Text(memorama.description).font(.patrickHand(size: 20)).foregroundColor(.white)
}
}.padding()
}
}
struct MenuView_Previews: PreviewProvider {
static var previews: some View {
MenuView()
}
}
| true
|
37228993793ce6c40eba50367879314e8e7893f5
|
Swift
|
mparrish91/calendar_module_swift
|
/Year.swift
|
UTF-8
| 1,377
| 2.53125
| 3
|
[] |
no_license
|
//
// Year.swift
// Calendar
//
// Created by Malcolm Parrish on 11/17/15.
// Copyright © 2015 WordWise. All rights reserved.
//
import Foundation
class Year:NSObject {
//MARK: Properties
var isLeapYear: Bool?
var term: Int?
var monthArray:[Month]?
init?(term: Int) {
self.term = term
if term % 4 == 0 {
if term % 100 == 0 && term % 400 != 0 {
self.isLeapYear = false
}else{
self.isLeapYear = true
}
}
//initialize month array
if self.isLeapYear == true{
self.monthArray = [Month(name: "January")!,Month(name: "FebruaryLeap")!,Month(name: "March")!,Month(name: "April")!,Month(name: "May")!,Month(name: "June")!,Month(name: "August")!,Month(name: "September")!,Month(name: "October")!,Month(name: "November")!,Month(name: "December")! ]
}else{
self.monthArray = [Month(name: "January")!,Month(name: "February")!,Month(name: "March")!,Month(name: "April")!,Month(name: "May")!,Month(name: "June")!,Month(name: "August")!,Month(name: "September")!,Month(name: "October")!,Month(name: "November")!,Month(name: "December")! ]
//Initialization should fail if there is no term
// if term == nil {
// return nil
// }
}
}
}
| true
|
16bb545ab2ae406c6ae42a5315e786dcde7e0488
|
Swift
|
radyslavkrechet/PDPRecipes
|
/Recipes/Source/App/Modules/Categories/CategoriesViewModel.swift
|
UTF-8
| 859
| 3.015625
| 3
|
[] |
no_license
|
import RxSwift
class CategoriesViewModel: ViewModel {
var categories: Observable<[Category]> {
return categoriesSubject.asObservable()
}
private let categoriesSubject = PublishSubject<[Category]>()
private let getCategoriesUseCase: GetCategoriesUseCase
init(getCategoriesUseCase: GetCategoriesUseCase) {
self.getCategoriesUseCase = getCategoriesUseCase
}
func getCategories() {
getCategoriesUseCase.getCategories(success: { [weak self] categories in
self?.proccess(categories)
}, failure: { [weak self] error in
self?.proccess(error)
})
}
// MARK: - Private
private func proccess(_ categories: [Category]) {
categoriesSubject.onNext(categories)
}
// MARK: - ViewModel
override func tryAgain() {
getCategories()
}
}
| true
|
b95f5a67f2dae5ccdbebb963f5bbaa5e2e33b57b
|
Swift
|
wangch6688/SwiftStudyDemo
|
/Swift_04.playground/Contents.swift
|
UTF-8
| 1,079
| 4.25
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
//字符串
//1.空字符串
var emptyStr = ""
var emptyStr1 = String()
//检查字符串是否为空
let isEmpty = emptyStr1.isEmpty
//2.拼接
let name = "wang"
let weight = "160"
var fullStr = name + "体重是" + weight
//3.构造字符串 强制类型转换 基本上所有的类型都可以转换成字符串
let height = String(190)
let a = 50
let b = Double(a)
let c = String(a)
//4.拼接单个的字符
let d : Character = "!"
fullStr.append(d)
fullStr.append(Character("!"))
//字符串不是指针,而是实际的值
//5.值类型
var muStr = "123"
muStr += "456"
let consStr = "abc"
//========================================
//字符串常用的发方法
//1.插值字符串
let user = "Jobs"
//将另外一个值放到字符串中间,不一定特指字符串
var password = "\(user)is nubility!"
let userID = 007
password = "\(userID)\(password)"
//2.转义字符
var word = "Li Lei Says:\"Hello World!\""
//Unicode swift对Unicode的字符基本全部支持
//Unicode编码
"\u{24}"
"\u{2048}"
| true
|
acd91d3bf520f3bfad848e4ac0a644f1ab9ae170
|
Swift
|
edgar2209/proy-swift
|
/Practicas/practica1-tiposdedatos.playground/Contents.swift
|
UTF-8
| 1,063
| 3.734375
| 4
|
[] |
no_license
|
import UIKit
var mivariable = 1
var str = "Hola Mundo"
let PI = 3.1416
var MiVariable = 2
var miVariable = 3 //como se llama? Camel Case
print(mivariable)
print(MiVariable)
print(miVariable)
var cadena = "Hola IOS"
cadena = "Swift"
let nombre1:String = "Walter"
var apellido1:String = "White"
let saludo1:String = "Hola"
print("Hola \(nombre1) \(apellido1)")
let nombre2:String = "Walter Jr"
let saludo2:String = "Hola \(nombre2)"
print(saludo2)
let CORREO = "billgates@microsoft.com"
var entero = 1
var a:Int = 10
var b:Int = 20
var suma:Int = a + b
var resta:Int = a - b
var mult:Int = a * b
var x:Double = 10
var y:Double = 10
var pi:Double = x/y
var radio:Double = 1.5
var area:Double = pi * ( radio * radio)
var residuo = 30 % 4
var negativo = -40
var positivo = +40
positivo += 10
var flotante = 1.5
print(flotante)
print("El valor del area es: \(area)")
var i:Int = 0 ; var j:Int = 0
//Boolean
var valorpositivo:Bool = true
var valornegativo:Bool = false
var p = 10
var q = 10
var comparacion:Bool = p == q
print(comparacion)
| true
|
3a48e475c818da539877bc35f42cc424ef54f565
|
Swift
|
SirishaVanamali/Momento
|
/Xpresso/SignUpViewController.swift
|
UTF-8
| 5,700
| 2.578125
| 3
|
[] |
no_license
|
//
// SignUpViewController.swift
// Xpresso
//
// Created by Bharam,Kamala Priya on 4/1/17.
// Copyright © 2017 Bharam,Kamala Priya. All rights reserved.
//
import UIKit
import Parse
class SignUpViewController: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
Username.resignFirstResponder()
pwd.resignFirstResponder()
FName.resignFirstResponder()
LName.resignFirstResponder()
Email.resignFirstResponder()
npwd.resignFirstResponder()
return true
}
override func viewDidLoad() {
Username.delegate = self
pwd.delegate = self
FName.delegate = self
LName.delegate = self
Email.delegate = self
npwd.delegate = self
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func textFieldDidBeginEditing(_ textField: UITextField) {
moveTextField(textField: npwd, moveDistance: -220, up: true)
}
// keyboard hiddens
func textFieldDidEndEditing(_ textField: UITextField) {
moveTextField(textField: npwd, moveDistance: -220, up: false)
}
// userdefined method to show animation for keyboard
func moveTextField(textField: UITextField, moveDistance: Int, up:Bool)
{
let moveDuration = 0.3
let movement: CGFloat = CGFloat(up ? moveDistance : -moveDistance)
UIView.beginAnimations("animateTextField", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(moveDuration)
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()
}
func alert(message: NSString, title: NSString) {
let alert = UIAlertController(title: title as String, message: message as String, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
@IBAction func SignUp(_ sender: Any) {
let imageData = UIImagePNGRepresentation(self.DP.image!)
//create a parse file to store in cloud
let parseImageFile = PFFile(name: "Image.png", data: imageData!)
let user = PFUser()
user.username = Username.text!
user.password = pwd.text!
user.email = Email.text!
user["Image"] = parseImageFile
// Signing up using the Parse API
user.signUpInBackground {
(success, error) -> Void in
if let error = error as NSError? {
let errorString = error.userInfo["error"] as? NSString
self.alert(message: errorString!, title: "Error")
} else {
user.saveInBackground(block: { (d, NSError) in
if d {
let alert:UIAlertController = UIAlertController(title: "Success", message: "Registration Successful", preferredStyle: .alert)
let defaultAction:UIAlertAction = UIAlertAction(title: "OK", style: .cancel, handler: {action in self.dismiss(animated: true, completion: nil)})
alert.addAction(defaultAction)
self.present(alert, animated: true, completion: nil)
}
else {
self.alert(message: "Some Thing went wrong on our side, Try Later", title: "Sorry!")
}
})
}
}
}
func displayAlertWithTitle(_ title:String, message:String){
let alert:UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction:UIAlertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(defaultAction)
self.present(alert, animated: true, completion: nil)
}
@IBOutlet weak var FName: UITextField!
@IBOutlet weak var LName: UITextField!
@IBOutlet weak var Email: UITextField!
@IBOutlet weak var Username: UITextField!
@IBOutlet weak var pwd: UITextField!
@IBOutlet weak var npwd: UITextField!
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBOutlet weak var DP: UIImageView!
@IBAction func DPButton(_ sender: UIButton) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
DP.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismiss(animated: true, completion: nil)
}
}
| true
|
75b22d2f9be364fb6989a510027f0f10bef99cdb
|
Swift
|
Build-Week-Anywhere-Fitness1-April-2020/iOS
|
/AnywhereFitness/AnywhereFitness/View Controllers/Client/SearchPage1ViewController.swift
|
UTF-8
| 3,626
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// SearchPage1ViewController.swift
// AnywhereFitness
//
// Created by Christopher Devito on 4/29/20.
// Copyright © 2020 Christopher Devito. All rights reserved.
//
import UIKit
class SearchPage1ViewController: UIViewController {
// MARK: - Properties
var course: CourseRepresentation?
let courseController = CourseController.shared
var courseLevelArray = CourseController.shared.courseIntensityArray
var classTypeArray = CourseController.shared.classTypeArray
var searchResults: [CourseRepresentation] = []
var mySearchResults: [CourseRepresentation] = []
// MARK: - IBOutlets
@IBOutlet weak var classTypeUIPicker: UIPickerView!
@IBOutlet weak var courseLevel: UIPickerView!
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet var backgroundView: UIView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
courseLevel.dataSource = self
courseLevel.delegate = self
classTypeUIPicker.dataSource = self
classTypeUIPicker.delegate = self
locationTextField.layer.borderWidth = 1
backgroundView.setBackground()
let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:)))
view.addGestureRecognizer(tap)
}
// MARK: - IBActions
@IBAction func searchButtonTapped(_ sender: Any) {
let classType = classTypeUIPicker.selectedRow(inComponent: 1)
let courseIntensity = courseLevel.selectedRow(inComponent: 1)
let myLevel = courseLevelArray[1][courseIntensity]
let myLocation = locationTextField.text
searchResults = courseController.allCourses
mySearchResults = searchResults.filter { $0.classType == classType
&& $0.intensity == myLevel
&& $0.location == myLocation }
print(mySearchResults)
performSegue(withIdentifier: "SearchSegue1", sender: self)
}
@IBAction func unwindAndClear(unwindSegue: UIStoryboardSegue) {
locationTextField.text = ""
classTypeUIPicker.selectRow(0, inComponent: 1, animated: true)
courseLevel.selectRow(0, inComponent: 1, animated: true)
}
@IBAction func unwindAndTab(unwindSegue: UIStoryboardSegue) {
locationTextField.text = ""
classTypeUIPicker.selectRow(0, inComponent: 1, animated: true)
courseLevel.selectRow(0, inComponent: 1, animated: true)
tabBarController?.selectedIndex = 0
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SearchSegue1" {
guard let page2VC = segue.destination as? SearchResultsViewController else { return }
page2VC.courses = mySearchResults
}
}
}
extension SearchPage1ViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
if pickerView.tag == 0 {
return classTypeArray.count
} else {
return courseLevelArray.count
}
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 0 {
return classTypeArray[component].count
} else {
return courseLevelArray[component].count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 0 {
return classTypeArray[component][row]
} else {
return courseLevelArray[component][row]
}
}
}
| true
|
2251d486f5f0877a244e945156c529e7d90e5ad9
|
Swift
|
YuriParfenov/ConvertingOfNumbers
|
/Desktop/GitHub/ConvertingOfNumbers/ConvertingOfNumbers/ViewController.swift
|
UTF-8
| 3,810
| 2.84375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// перевод чисел
//
// Created by Юрий Парфенов on 13/11/2018.
// Copyright © 2018 Юрий Парфенов. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController, UITextFieldDelegate{
var DigitInt: Int64 = 0
var modulo: Int64 = 0
var result: String = ""
var Rresult: String = ""
var DigitStr: String = ""
var ArrayInt = [Int64]()
var lenght : Int64 = 0
var result2: Int64 = 0
func NilCheck(){
if Digit.text!.isEmpty{
MainLabel.text = "Field is not filled"
}else{
if Int64(Digit.text!) != nil{
DigitInt = Int64(Digit.text!)!
}else{
MainLabel.text = "Error"
}
}
}
func calculaton(){
DigitStr = String(DigitInt)
ArrayInt = DigitStr.compactMap{Int64(String($0))}
lenght = Int64(ArrayInt.count)
if From10to2Btn.isHighlighted{
while DigitInt > 0{
modulo = DigitInt % Int64(2)
result = result + String(modulo)
DigitInt = (DigitInt - modulo) / 2
Rresult = String(result.reversed())
}
MainLabel.text = Rresult
NilCheck()
}else if From2to10Btn.isHighlighted{
if lenght == 1{
if DigitStr == "0"{
MainLabel.text = "0"
NilCheck()
}else if DigitStr == "1"{
MainLabel.text = "1"
NilCheck()
}else{
MainLabel.text = "number is not a binary system"
}
}else{
for (index, element) in ArrayInt.enumerated(){
if element == 0 || element == 1{
result2 = result2 + element * Int64(pow(2,(Double(lenght - Int64(index) - Int64(1)))))
MainLabel.text = String(result2)
NilCheck()
}else{
MainLabel.text = "number is not a binary system"
NilCheck()
}
}
}
}
}
func ClearAll(){
MainLabel.text = "0"
modulo = 0
result = ""
Rresult = ""
DigitStr = ""
ArrayInt.removeAll()
lenght = 0
result2 = 0
}
@IBAction func ClearBtn(_ sender: UIButton) {
ClearAll()
Digit.text = ""
}
@IBAction func From10to2(_ sender: UIButton) {
if MainLabel.text == "0" {
NilCheck()
calculaton()
}else{
ClearAll()
NilCheck()
calculaton()
}
}
@IBAction func From2to10(_ sender: UIButton){
if MainLabel.text == "0"{
NilCheck()
calculaton()
}else{
ClearAll()
NilCheck()
calculaton()
}
}
@IBOutlet weak var From10to2Btn: UIButton!
@IBOutlet weak var From2to10Btn: UIButton!
@IBOutlet weak var MainLabel: UILabel!
@IBOutlet weak var Digit: UITextField!
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
Digit.resignFirstResponder()
return true
}
override func viewDidLoad() {
super.viewDidLoad()
Digit.delegate = self
}
}
| true
|
14a6bdba0b81bbc0364557d6b83a41cefde94830
|
Swift
|
uts-ios-dev/uts-ios-2019-project3-group-156
|
/Focus booster/Focus booster/ChartFormatter.swift
|
UTF-8
| 436
| 2.703125
| 3
|
[] |
no_license
|
//
// ChartFormatter.swift
// Focus booster
//
// Created by lvino on 2/6/19.
// Copyright © 2019 Theron Ann. All rights reserved.
//
import Foundation
import Charts
class ChartStringFormatter: NSObject, IAxisValueFormatter {
var nameValues: [String]! = ["A", "B", "C", "D"]
public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return String(describing: nameValues[Int(value)])
}
}
| true
|
8001d32b840bf76895e4478b106802e1e6b771bf
|
Swift
|
xilosada/BitcoinFinder
|
/BitcoinFinder/OfferInfo.swift
|
UTF-8
| 458
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// OfferInfo.swift
// BitcoinFinder
//
// Created by X.I. Losada on 16/01/16.
// Copyright © 2016 xiLosada. All rights reserved.
//
import Foundation
public struct OfferInfo {
let price: Double
let type: Int
let place: Place
let trader: Trader
init(price: Double, type: Int, place: Place, trader: Trader) {
self.price = price
self.type = type
self.place = place
self.trader = trader
}
}
| true
|
ebb599ab8fb31f4bf44502f329c02a1acfc0c3f9
|
Swift
|
dabaicaifen/MockTwitter
|
/TwitterMock/Adapters/Realm/Changeset.swift
|
UTF-8
| 768
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// Changeset.swift
// TwitterMock
//
// Created by Tracy Wu on 2019-04-03.
// Copyright © 2019 TW. All rights reserved.
//
import Foundation
struct Changeset {
let deletions: [Int]
let insertions: [Int]
let modifications: [Int]
var isEmpty: Bool {
return deletions.isEmpty && insertions.isEmpty && modifications.isEmpty
}
public static func empty() -> Changeset {
return Changeset(deletions: [],
insertions: [],
modifications: [])
}
static func modifications(_ modifications: [Int]) -> Changeset {
return Changeset(deletions: [],
insertions: [],
modifications: modifications)
}
}
| true
|
a4af39bf51e0c055414cba8b4fd9e402a9e5a9b9
|
Swift
|
adit99/Tips-Swift
|
/tips/SettingsViewController.swift
|
UTF-8
| 2,999
| 2.703125
| 3
|
[] |
no_license
|
//
// SettingsViewController.swift
// tips
//
// Created by Aditya Jayaraman on 1/3/15.
// Copyright (c) 2015 Aditya Jayaraman. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var splitByLabel: UILabel!
@IBOutlet weak var splitByStep: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
splitByLabel.text = "1"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onClick(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBOutlet weak var defaultTipControl: UISegmentedControl!
@IBAction func onDefaultTipControlChange(sender: AnyObject) {
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(defaultTipControl.selectedSegmentIndex, forKey: "defaultTipControl")
defaults.synchronize()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
println("Settings view will appear")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
println("Settings view did appear")
var defaults = NSUserDefaults.standardUserDefaults()
let defaultTip = defaults.integerForKey("defaultTipControl")
defaultTipControl.selectedSegmentIndex = defaultTip
var defaultSplitBy = defaults.integerForKey("defaultSplitBy")
if (defaultSplitBy == 0) {
defaultSplitBy = 1
}
splitByStep.value = Double(defaultSplitBy)
var b:String = String(format:"%d", defaultSplitBy)
splitByLabel.text = b
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
println("Settings view will disappear")
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
println("Settings view did disappear")
}
@IBAction func onTapChange(sender: AnyObject) {
println("on tap change")
var b:String = String(format:"%0.0f", splitByStep.value)
splitByLabel.text = b
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(Int(splitByStep.value), forKey: "defaultSplitBy")
defaults.synchronize()
}
}
| true
|
f1be122f9d8c5a67626afb184eb168a006e94289
|
Swift
|
yakushevichsv/contactisGroupTestTask
|
/ContactisGroupTestTask/Model/TextAnalyzer.swift
|
UTF-8
| 20,010
| 3.109375
| 3
|
[] |
no_license
|
//
// TextAnalyzer.swift
// ContactisGroupTestTask
//
// Created by Siarhei Yakushevich on 7/26/17.
// Copyright © 2017 Siarhei Yakushevich. All rights reserved.
//
import Foundation
//MARK: - TextAnalyzer
class TextAnalyzer {
private var _text = ""
var text: String {
set {
_text = newValue.lowercased()
}
get {
return _text
}
}
let queue: DispatchQueue
let basicNumbers : [String: TextAnalyzer.NumberType] = ["one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight":8,
"nine":9,
"ten":10,
"eleven": 11,
"twelve": 12,
"thirteen":13,
"fourteen":14,
"fifteen": 15,
"sixteen":16,
"seventeen": 17,
"eighteen":18,
"nineteen": 19,
"twenty": 20,
"thirty":30,
"forty": 40,
"fifty": 50,
"sixty": 60,
"seventy": 70,
"eighty": 80,
"ninety":90]
lazy var basicNumbersOpposite: [TextAnalyzer.NumberType: String] = {
var result: [TextAnalyzer.NumberType: String] = [:]
for basicPair in self.basicNumbers {
result[basicPair.value] = basicPair.key
}
return result
}()
let multipliersSingal : [String: TextAnalyzer.NumberType] =
["hundred" : 1e+2,
"hundreds" : 1e+2,
"thousands" : 1e+3,
"thousand" : 1e+3 ,
"million" : 1e+6,
"millions" : 1e+6,
"billion" : 1e+9,
"billions" : 1e+9,
"trillion" : 1e+12,
"trillions" : 1e+12 ]
lazy var multipliersSignalOpposite: [TextAnalyzer.NumberType : String] = {
var result: [TextAnalyzer.NumberType: String] = [:]
for basicPair in self.multipliersSingal {
if (result[basicPair.value] == nil && basicPair.key.characters.last != "s") {
result[basicPair.value] = basicPair.key
}
}
return result
}()
typealias NumberType = Double
convenience init() {
self.init(expression: "")
}
init(expression text:String) {
self.queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
self.text = text
}
func analyze(completion:@escaping ((_ value: TextAnalyzer.NumberType)->Void)) {
self.queue.async { [weak self] in
guard let sSelf = self else { return}
let result = sSelf.analyzeInner()
completion(result)
}
}
func analyzeInner() -> TextAnalyzer.NumberType {
let objects = createArithmeticExpressions()
let result = process(arithmeticExpressions: objects)
return result
}
class func convertToString(_ value : TextAnalyzer.NumberType) -> String {
//TODO: refactor this.
return TextAnalyzer().convertToString(value)
}
/*
Convert value to string representation
345 -> three hundred forty five....
* Can be done using
* NSNumberFormatter *numberFormatter = [[NSNumberFormatter new];
* [numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
*/
func convertToString(_ value : TextAnalyzer.NumberType) -> String {
var intValue = Int(value)
assert(value == Double(intValue)) // support just only integer items...
var digits = [Int]()
var tempInt = intValue
while (tempInt != 0 ){
let newIntValue = tempInt/10
let reminder = tempInt - newIntValue * 10
digits.append(reminder)
tempInt = newIntValue
}
digits.reverse()
let maxPower = digits.count - 1
let supportedPowers = [12, 9 , 6, 3, 2, 0]
var index = supportedPowers.startIndex
//Can be thousand of trillions...
var providedPower = maxPower
var result = ""
var partStr = ""
while (index != supportedPowers.endIndex && providedPower >= 0) {
let currentPower = supportedPowers[index]
if (currentPower <= providedPower) {
let divider = Int(pow(Double(10),Double(currentPower)))
let valuePart = intValue/divider
partStr = ""
if valuePart < 100 {
if let fValueStr = self.basicNumbersOpposite[TextAnalyzer.NumberType(valuePart)] {
partStr = fValueStr
}
else if (valuePart > 20) {
let wholePart = valuePart/10
let valueWithoutReminder = wholePart * 10
let reminder = valuePart - valueWithoutReminder
let decimalsStr = self.basicNumbersOpposite[TextAnalyzer.NumberType(valueWithoutReminder)]!
let digitsStr = self.basicNumbersOpposite[TextAnalyzer.NumberType(reminder)]!
partStr = "\(decimalsStr)-\(digitsStr)"
}
if (valuePart >= 10 ) {
providedPower -= 2
}
else {
providedPower -= 1
}
}
else {
partStr = convertToString(TextAnalyzer.NumberType(valuePart))
}
if valuePart != 0, let str = self.multipliersSignalOpposite[TextAnalyzer.NumberType(divider)] {
partStr.append(" ")
partStr.append(str)
/*if (valuePart != 1) {
partStr.append("s")
}*/
if (!result.isEmpty) {
result.append(" ")
}
result.append(partStr)
partStr = ""
}
intValue -= valuePart * divider
}
index = supportedPowers.index(after: index)
}
if (!partStr.isEmpty) {
if (!result.isEmpty) {
result.append(" ")
}
result.append(partStr)
}
return result
}
func createArithmeticExpressions() -> [ArithmeticExpression] {
//remove "whitespace"
let pText = self.text.condensedWhitespace.replacingOccurrences(of: "-", with: " ") //fifty-nine
//divide sence into tags...
let components = pText.components(separatedBy: " ")
let temp = components.flatMap { self.multipliersSingal[$0] }
var multipliers: [TextAnalyzer.NumberType] = []
var prevMutliplier = TextAnalyzer.NumberType(0)
for multiplier in temp {
if (multiplier > prevMutliplier) {
prevMutliplier = multiplier
}
else {
multipliers.append(prevMutliplier)
prevMutliplier = multiplier
}
}
if (prevMutliplier != 0) {
multipliers.append(prevMutliplier)
}
var multiplierIndex = multipliers.startIndex
var detectingNumber = false
var value: NumberType? = nil
var minusDetectedCount = 0
var isPositive = true
var prevOperation: ArithmeticExpression? = nil
var prevPartValue: NumberType? = nil
var objects = [ArithmeticExpression]()
for i in components.startIndex..<components.endIndex {
let component = components[i]
if let fDigit = self.basicNumbers[component] {
if (!detectingNumber) {
detectingNumber = true
prevPartValue = fDigit
value = nil
if let op = prevOperation, !objects.isEmpty {
objects.append(op)
prevOperation = nil
}
}
else {
if var prev = prevPartValue {
prev += fDigit
prevPartValue = prev
}
else {
prevPartValue = fDigit
}
}
}
else if let multiplier = self.multipliersSingal[component] {
if var prev = prevPartValue {
prev *= multiplier
prevPartValue = prev
}
else {
prevPartValue = 1 //1 million instead of million
}
let needResetPrev = multipliers.endIndex != multiplierIndex ? multipliers[multiplierIndex] == multiplier : true
if needResetPrev {
if multipliers.endIndex != multiplierIndex {
multiplierIndex = multipliers.index(after: multiplierIndex)
}
if var val = value {
val += prevPartValue!
value = val
}
else {
value = prevPartValue!
}
prevPartValue = nil
}
}
else if let operation = Operation(rawValue: component){
prevOperation = ArithmeticExpression.operation(operation: operation)
if (detectingNumber) {
if let prev = prevPartValue {
if (value == nil) {
value = prev
}
else {
value! += prev
}
}
if (value == nil) {
value = NumberType(0)
}
if (!isPositive) {
value! *= -1
isPositive = true
}
let tempValue = ArithmeticExpression.value(value: value!)
objects.append(tempValue)
detectingNumber = false
}
else if operation == .minus {
if (minusDetectedCount == 0) {
minusDetectedCount += 1
isPositive = false
prevOperation = ArithmeticExpression.operation(operation: Operation.plus)
}
else {
isPositive = true
debugPrint("WARNING double minus detected!")
prevOperation = ArithmeticExpression.operation(operation: Operation.plus)
}
}
else {
minusDetectedCount = 0
if operation == .plus {
if (!isPositive) {
//Store minus....
prevOperation = ArithmeticExpression.operation(operation: Operation.minus)
isPositive = true
}
}
}
}
else if component == "by" ||
component == "and" { // multiply by , divide by, one million and
continue
}
else {
debugPrint("WARNING unsupported operation detected! \(component)")
}
}
if (detectingNumber) {
if let prev = prevPartValue {
if (value == nil) {
value = prev
}
else {
value! += prev
}
}
if (value == nil) {
value = NumberType(0)
}
if (!isPositive) {
value! *= -1
isPositive = true
}
let tempValue = ArithmeticExpression.value(value: value!)
objects.append(tempValue)
detectingNumber = false
}
else if let op = prevOperation {
objects.append(op)
prevOperation = nil
}
return objects
}
func process(arithmeticExpressions objects: [ArithmeticExpression]) -> TextAnalyzer.NumberType {
let opIndexes = detect(inObjects: objects)
var newObjects: [ArithmeticExpression] = []
var result = TextAnalyzer.NumberType(0)
if let fIndexes = opIndexes.first {
let fRangeValues = simplify(inObjects: objects, operationIndexes: fIndexes) //TODO: should have a flag... No need to process all operations, just multiplication.
//During second call addition, and substraction.
var prevRange = objects.startIndex
for rangeValue in fRangeValues {
// Copy items before range & after range...
let subRange = objects[prevRange..<rangeValue.range.lowerBound]
newObjects.append(contentsOf: subRange)
newObjects.append(ArithmeticExpression.value(value: rangeValue.value))
prevRange = objects.index(after: rangeValue.range.upperBound).advanced(by: 1)
}
let subRange = objects[prevRange..<objects.endIndex]
newObjects.append(contentsOf: subRange)
}
if let opIndexes2 = detect(inObjects: newObjects).first {
let fRangeValues = simplify(inObjects: newObjects, operationIndexes: opIndexes2)
//assert(fRangeValues.count == 1 )
result = fRangeValues.first?.value ?? TextAnalyzer.NumberType(0)
}
else {
result = newObjects.first?.accessValue() ?? TextAnalyzer.NumberType(0)
}
return result
}
func detect(inObjects objects:[ArithmeticExpression]) -> [[Array<Operation>.Index]] { //multiply, divide -> plus, minus...
var index = objects.startIndex
var firstLevel: [Array<Operation>.Index] = []
var secondLevel: [Array<Operation>.Index] = []
while (index != objects.endIndex) {
let element = objects[index]
if let op = element.accessOperation() {
switch op {
case .multiply: fallthrough
case .divide:
firstLevel.append(index)
break
case .plus: fallthrough
case .minus:
secondLevel.append(index)
break
}
}
index = objects.index(after: index)
}
var result: [[Array<Operation>.Index]] = []
if (!firstLevel.isEmpty) {
result.append(firstLevel)
}
if (!secondLevel.isEmpty) {
result.append(secondLevel)
}
return result
}
func simplify(inObjects objects:[ArithmeticExpression], operationIndexes indexes:[Array<Operation>.Index]) -> [(range: Range<Array<Operation>.Index>, value: TextAnalyzer.NumberType) ] {
let startIndex = indexes.startIndex
let endIndex = indexes.endIndex
var prevValue: TextAnalyzer.NumberType! = nil
var index = startIndex
var innerIndex = objects.startIndex
var prevIndex = innerIndex
var groupIndex: Array<Operation>.Index! = nil
var result: [(range:Range<Array<Operation>.Index>, value: TextAnalyzer.NumberType)] = []
while (index != endIndex) {
var defValue: TextAnalyzer.NumberType! = nil
innerIndex = indexes[index]
if let op = objects[innerIndex].accessOperation() {
switch op {
case .multiply: fallthrough
case .divide:
defValue = TextAnalyzer.NumberType(1)
break
case .minus: fallthrough
case .plus:
defValue = TextAnalyzer.NumberType(0)
break
}
}
var lValue: TextAnalyzer.NumberType! = nil
if (innerIndex - prevIndex == 2) {
lValue = prevValue
}
else {
if (groupIndex != nil) {
result.append((range: groupIndex..<innerIndex, value: prevValue))
groupIndex = nil
}
lValue = defValue
if (innerIndex != objects.startIndex) {
let tIndex = objects.index(before: innerIndex)
if (groupIndex == nil) {
groupIndex = tIndex
}
if let value = objects[tIndex].accessValue() {
lValue = value
}
else {
debugPrint("Warning!")
}
}
}
var rValue = defValue
if (innerIndex != objects.endIndex) {
let tIndex = objects.index(after: innerIndex)
if tIndex != objects.endIndex , let value = objects[tIndex].accessValue() {
rValue = value
}
else {
debugPrint("Warning!")
}
}
var result = TextAnalyzer.NumberType(0)
if let op = objects[innerIndex].accessOperation(), let r = rValue, let l = lValue {
switch op {
case .multiply:
result = l * r
break
case .divide:
result = l / r
break
case .minus:
result = l - r
break
case .plus:
result = l + r
break
}
}
prevValue = result
prevIndex = innerIndex
index = indexes.index(after: index)
}
if (groupIndex != nil) {
result.append((range: groupIndex..<innerIndex, value: prevValue))
groupIndex = nil
}
return result
}
}
| true
|
c1cc4c63b3d0d7433ef68cafc400934c65e6d632
|
Swift
|
patel-pragnesh/RetailInventory
|
/RetailInventoryToSwift/Classes/Views/Cells/SelectDetailCell.swift
|
UTF-8
| 993
| 2.625
| 3
|
[] |
no_license
|
//
// SelectDetailCell.swift
// RetailInventoryToSwift
//
// Created by Sak, Andrey2 on 6/23/16.
// Copyright © 2016 Anashkin, Evgeny. All rights reserved.
//
import UIKit
class SelectDetailCell: BaseCell {
static let cellIdentifier = String(SelectDetailCell)
@IBOutlet private weak var selectionItemLabel: UILabel!
@IBOutlet private weak var checkMarkImage: UIImageView!
var isSelected: Bool! {
didSet {
checkMarkImage.hidden = !isSelected
}
}
var selectionItem: AnyObject! {
didSet {
if let selectedDepartment = selectionItem as? Department {
selectionItemLabel.text = selectedDepartment.name
}
if let selectedVendor = selectionItem as? Vendor {
selectionItemLabel.text = selectedVendor.name
}
if let selectedTax = selectionItem as? Tax {
selectionItemLabel.text = selectedTax.taxName
}
}
}
}
| true
|
c8afdef398f52a2b24525fcca47aa3e3a7732962
|
Swift
|
EtienneWt/GramiOS
|
/Gram/promotion.swift
|
UTF-8
| 4,548
| 2.875
| 3
|
[] |
no_license
|
//
// promotion.swift
// Gram
//
// Created by EPF Projets Sceaux on 12/11/2019.
// Copyright © 2019 EPF Projets Sceaux. All rights reserved.
//
// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let promotion = try promotion(json)
//
// To read values from URLs:
//
// let task = URLSession.shared.promotionTask(with: url) { promotion, response, error in
// if let promotion = promotion {
// ...
// }
// }
// task.resume()
import Foundation
// MARK: - promotion
struct promotion: Codable {
let id: Int
let name, promotionDescription: String
let priceValue, recipeID: JSONNull?
let offerType: String
let percentageValue: Int
let numberOfArticle: JSONNull?
let categoryID: Int
let recipeName: JSONNull?
let categoryName: String
enum CodingKeys: String, CodingKey {
case id, name
case promotionDescription
case priceValue
case recipeID
case offerType
case percentageValue
case numberOfArticle
case categoryID
case recipeName
case categoryName
}
}
// MARK: promotion convenience initializers and mutators
extension promotion {
init(data: Data) throws {
self = try JSONDecoder().decode(promotion.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
id: Int? = nil,
name: String? = nil,
promotionDescription: String? = nil,
priceValue: JSONNull?? = nil,
recipeID: JSONNull?? = nil,
offerType: String? = nil,
percentageValue: Int? = nil,
numberOfArticle: JSONNull?? = nil,
categoryID: Int? = nil,
recipeName: JSONNull?? = nil,
categoryName: String? = nil
) -> promotion {
return promotion(
id: id ?? self.id,
name: name ?? self.name,
promotionDescription: promotionDescription ?? self.promotionDescription,
priceValue: priceValue ?? self.priceValue,
recipeID: recipeID ?? self.recipeID,
offerType: offerType ?? self.offerType,
percentageValue: percentageValue ?? self.percentageValue,
numberOfArticle: numberOfArticle ?? self.numberOfArticle,
categoryID: categoryID ?? self.categoryID,
recipeName: recipeName ?? self.recipeName,
categoryName: categoryName ?? self.categoryName
)
}
func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
// MARK: - URLSession response handlers
extension URLSession {
fileprivate func codableTask<T: Codable>(with url: URL, completionHandler: @escaping (T?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
return self.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
completionHandler(nil, response, error)
return
}
completionHandler(try? JSONDecoder().decode(T.self, from: data), response, nil)
}
}
func promotionTask(with url: URL, completionHandler: @escaping (promotion?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
return self.codableTask(with: url, completionHandler: completionHandler)
}
}
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
| true
|
f5c5b60b00c670cf050a2fec3b856a682fa551cd
|
Swift
|
ar2-url/bitso-currency
|
/BitsoChallenge/Model/Model.swift
|
UTF-8
| 469
| 2.59375
| 3
|
[] |
no_license
|
//
// Model.swift
// BitsoChallenge
//
// Created by Juan carlos De la parra on 06/05/21.
//
import Foundation
struct Book: Codable {
var payload: [BookItem?]
}
struct BookItem: Codable {
var book: String?
}
struct Prices: Codable {
var payload: [BookPrice?]
}
struct BookPrice: Codable {
var book: String?
var volume: String?
var high: String?
var last: String?
var low: String?
var vwap: String?
var ask: String?
var bid: String?
}
| true
|
d139e43f30c527cd40b4453b1a37d5d5bd60182a
|
Swift
|
maddiemonfort/iOSClass
|
/InstaCloud/ParseStarterProject/instacode.swift
|
UTF-8
| 1,604
| 2.828125
| 3
|
[] |
no_license
|
@IBAction func SignUp(sender: AnyObject) {
//check to see if data is there
if(username.text != "" && password.text != "" && email.text != "") {
let user = PFUser()
user.username = username.text
user.password = password.text
user.email = email.text
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error:NSError?) -> Void in
if error == nil {
//User added
//self.errorMess.text = "Account added"
self.performSegueWithIdentifier("AcctCreated", sender: nil)
}
else {
self.errorMess.text = error?.description
}
}
}
else {
self.errorMess.text = "Please fill in all fields."
}
}
@IBAction func SignIn(sender: AnyObject) {
if username.text != "" && password.text != "" {
PFUser.logInWithUsernameInBackground (username.text!, password: password.text!) {
(user: PFUser?, error: NSError?) -> Void in
if user != nil {
//Do stuff after successful login.
//print("You logged in!!")
self.performSegueWithIdentifier("SignIn", sender: nil)
}
else {
self.ErrMess.text = error?.description
}
}
}
else {
ErrMess.text = "Please fill in all text fields."
}
}
| true
|
04b3d9edbc10e1a226fd95e0d8501426c40a75ab
|
Swift
|
sgr-ksmt/Quiche
|
/Sources/Query+Ex.swift
|
UTF-8
| 1,892
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// Query+Ex.swift
// Quiche
//
// Created by suguru-kishimoto on 2018/05/28.
import Foundation
import FirebaseFirestore
private func keyPathToField<R,V>(_ keyPath: KeyPath<R, V>) -> String {
guard let field = keyPath._kvcKeyPathString else {
fatalError("invalid keyPath: \(keyPath)")
}
return field
}
public extension Query {
public func whereField<R, V>(_ keyPath: KeyPath<R, V>, isEqualTo value: V) -> Query {
return whereField(keyPathToField(keyPath), isEqualTo: value)
}
public func whereField<R, V>(_ keyPath: KeyPath<R, V>, isEqualTo value: V) -> Query where V: RawRepresentable {
return whereField(keyPathToField(keyPath), isEqualTo: value.rawValue)
}
public func whereField<R, V>(_ keyPath: KeyPath<R, V>, isLessThan value: V) -> Query {
return whereField(keyPathToField(keyPath), isLessThan: value)
}
public func whereField<R, V>(_ keyPath: KeyPath<R, V>, isLessThanOrEqualTo value: V) -> Query {
return whereField(keyPathToField(keyPath), isLessThanOrEqualTo: value)
}
public func whereField<R, V>(_ keyPath: KeyPath<R, V>, isGreaterThan value: V) -> Query {
return whereField(keyPathToField(keyPath), isGreaterThan: value)
}
public func whereField<R, V>(_ keyPath: KeyPath<R, V>, isGreaterThanOrEqualTo value: V) -> Query {
return whereField(keyPathToField(keyPath), isGreaterThanOrEqualTo: value)
}
public func order<R, V>(by keyPath: KeyPath<R, V>) -> Query {
return order(by: keyPathToField(keyPath))
}
public func order<R, V>(by keyPath: KeyPath<R, V>, descending: Bool) -> Query {
return order(by: keyPathToField(keyPath), descending: descending)
}
public func whereReference(_ field: String, isEqualTo reference: DocumentReference) -> Query {
return whereField(field, isEqualTo: reference)
}
}
| true
|
ab48a2386f9f2e0a9b549f907094490527f106fa
|
Swift
|
Burenkovuser/MyPersonList
|
/MyPersonList/Person.swift
|
UTF-8
| 537
| 2.703125
| 3
|
[] |
no_license
|
//
// Person.swift
// MyPersonList
//
// Created by Vasilii on 09/08/2019.
// Copyright © 2019 Vasilii Burenkov. All rights reserved.
//
import Foundation
struct Person {
var name: String
var surname: String
var email: String
var phone: String
}
let names = ["Victor", "Bob", "Ivan", "Vasilii", "Stas"]
let surnames = ["Kuznecov", "Ivanov", "Petrov", "Sidorov", "Burenkov"]
let emails = ["aaa@gmail.com", "bbb@gmail.com", "ccc@gmail.com", "ddd@gmail.com", "sss@gmail.com"]
let phones = ["111-111-11", "222-22-22", "333-33-33", "444-44-44", "555-55-55"]
| true
|
d8c86b8fd93282750d59b678a4ecd94483d41ff3
|
Swift
|
saiadk/MVVMDemo
|
/MVVMDemo/Networking/Request/RequestableProtocol.swift
|
UTF-8
| 1,403
| 2.984375
| 3
|
[] |
no_license
|
//
// RequestProtocol.swift
// MVVMDemo
//
// Created by Mangaraju, Venkata Maruthu Sesha Sai [GCB-OT NE] on 7/8/18.
// Copyright © 2018 Demo. All rights reserved.
//
import Foundation
/// <#Description#>
///
/// - get: GET HTTP Method
/// - post: POST HTTP Method
/// - put: PUT HTTP Method
/// - delete: DELETE HTTP Method
enum HTTPMethod:String{
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
/// Protocol that defines the interface to implement a class/struct that can act as a request generator
protocol Requestable {
var URI: String { get set }
var httpMethod: HTTPMethod { get set }
var timeoutInterval: TimeInterval { get set }
var queryParams: [String:String]? { get set }
var bodyParams: [String:Any]? { get set }
var headers: [String:Any]? { get set }
}
/// Provided default implementations for requirements that are not mandatory for every request
extension Requestable{
var queryParams: [String:String]? {
get{
return nil
}
set{
}
}
var timeoutInterval: TimeInterval {
get{
return 30.0
}
set{
}
}
var bodyParams: [String:Any]? {
get{
return nil
}
set{
}
}
var headers: [String:Any]? {
get{
return nil
}
set{
}
}
}
| true
|
c6c712e14808f9a8dfcd58f30add196eb824442a
|
Swift
|
baxterma/Daisy
|
/Sources/Daisy/Promise.swift
|
UTF-8
| 6,375
| 3.546875
| 4
|
[
"MIT"
] |
permissive
|
//
// Promise.swift
// Daisy
//
// Created by Alasdair Baxter on 28/12/2016.
// Copyright © 2016 Alasdair Baxter. All rights reserved.
//
import Dispatch
/// The states a promise can be in.
enum PromiseState<Result> {
/// The promise is unresolved.
case unresolved
/// The promise has been fulfilled with a value (resolved).
case fulfilled(result: Result)
/// The promise has been rejected with an error (resolved).
case rejected(error: Error)
/// The promise has been cancelled, possibly with an indirect error (resolved).
case cancelled(indirectError: Error?)
}
/// A promise is used as a means of resolving a future. An asynchronous task or function
/// creates a promise, and keeps it private from the outside world (only exposing the promise's future).
///
/// When the work to be done is finished (be it successfully or unsuccessfully), the promise is resolved by
/// calling `fulfil(with:)`, `reject(with:)`, **or** `cancel(withIndirectError:)` **once**.
/// Calling any of these functions more than once (regardless if it is a different one each time) will do nothing.
///
/// A promise only acts as a write-only means of setting a future. The result from a resolved promise must be accessed using its
/// `future` property, and the mechanisms future provides.
public final class Promise<Result> {
//MARK: Properties
private var _future: Future<Result>!
/// The promise's future.
public var future: Future<Result> {
return _future!
}
private var _state: PromiseState<Result> = .unresolved // so we can protect `state`, and have a non-sync-ed way of accessing it
/// The current state of the promise.
private(set) var state: PromiseState<Result> {
set { // not sync-ed, as its private to promise, and we're sure to sync any setting
// validate the state change
switch _state {
case .unresolved:
_state = newValue
// if the state change is moving from a resolved state, trap (this really shouldn't happen)
// because `state` can only be set privately, an invalid change is a bug in Daisy
case .fulfilled(_), .rejected(error: _), .cancelled(indirectError: _):
fatalError("Daisy: Attempting to move a promise (\(Unmanaged.passUnretained(self).toOpaque())) from the \(_state) state to the \(newValue) state.")
}
}
get { return internalQueue.sync { _state } } // sync-ed because this can be accessed outside of promise
}
/// Returns `true` iff the receiver has been resolved, otherwise returns `false`.
public var isResolved: Bool {
return internalQueue.sync {
if case .unresolved = _state { return false }
else { return true }
}
}
/// A private queue for synchronisation.
fileprivate let internalQueue = DispatchQueue(label: "com.Daisy.PrivatePromiseIsolationQueue")
//MARK: Initialisers
/// Initialises an unresolved promise.
public init() {
_future = Future<Result>(promise: self)
}
/// Initialises a resolved promise, fulfilled with `result`.
///
/// - parameter result: The result the promise should be fulfilled with.
public convenience init(fulfilledWith result: Result) {
self.init()
fulfil(with: result)
}
/// Initialises a resolved promise, rejected with `error`.
///
/// - parameter error: The error the promise should be rejected with.
public convenience init(rejectedWith error: Error) {
self.init()
reject(with: error)
}
/// Initialises a resolved promise, cancelled with `indirectError`.
///
/// - parameter indirectError: The (optional) indirect error the promise should be cancelled with.
public convenience init(cancelledWithIndirectError indirectError: Error?) {
self.init()
cancel(withIndirectError: indirectError)
}
//MARK: Resolving Methods
/// Fulfills the receiver with `result`.
///
/// Does nothing if the receiver is already resolved.
///
/// - parameter result: The result to fulfil the receiver with.
public func fulfil(with result: Result) {
internalQueue.async {
guard case .unresolved = self._state else {
print("Daisy: Warning: Attempting to fulfill a \(type(of: self)) (\(Unmanaged.passUnretained(self).toOpaque())) that is already resolved (\(self._state))")
return
}
self.state = .fulfilled(result: result)
self.future.resolve(using: self)
}
}
/// Rejects the receiver with `error`.
///
/// Does nothing if the receiver is already resolved.
///
/// - parameter error: The error to reject the receiver with.
public func reject(with error: Error) {
internalQueue.async {
guard case .unresolved = self._state else {
print("Daisy: Warning: Attempting to reject a \(type(of: self)) (\(Unmanaged.passUnretained(self).toOpaque())) that is already resolved (\(self._state))")
return
}
self.state = .rejected(error: error)
self.future.resolve(using: self)
}
}
/// Cancels the receiver, optionally with `indirectError`.
///
/// Does nothing if the receiver is already resolved.
///
/// - parameter indirectError: The (optional) indirect error to cancel the
/// receiver with.
public func cancel(withIndirectError indirectError: Error? = nil) {
internalQueue.async {
guard case .unresolved = self._state else {
print("Daisy: Warning: Attempting to cancel a \(type(of: self)) (\(Unmanaged.passUnretained(self).toOpaque())) that is already resolved (\(self._state))")
return
}
self.state = .cancelled(indirectError: indirectError)
self.future.resolve(using: self)
}
}
}
| true
|
753513e6d4ce2b628335a80bc2046086e8dbf3ee
|
Swift
|
sun-yryr/agqr-program-guide
|
/Sources/App/Commands/ScrapingAgqrCommand.swift
|
UTF-8
| 1,362
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
import Fluent
import Vapor
struct ScrapingAgqr: Command {
let parser: ProgramGuideParsing
let repository: ProgramGuideSaving
let client = DownloadAgqrProgramGuide()
struct Signature: CommandSignature {
@Option(name: "url")
var url: String?
}
var help: String = "Download program guide and parse to json."
func run(using context: CommandContext, signature: Signature) throws {
context.console.info("Start Process")
defer {
context.console.info("End Process")
}
let future = client.execute(app: context.application, url: signature.url)
.unwrap(or: fatalError("htmlデータの取得に失敗しました"))
.flatMap { res -> EventLoopFuture<Void> in
do {
let programGuide = try self.parser.parse(res)
context.console.info(programGuide.map { element in element.program.startDatetime.toString() }.joined(separator: ","))
return context.application.eventLoopGroup.future()
} catch {
return context.application.eventLoopGroup.future(error: error)
}
}
do {
try future.wait()
} catch {
print("Batch failure")
print(error.localizedDescription)
}
}
}
| true
|
6fdfbe43e9d13290e87e4c84971e98438320e158
|
Swift
|
Free-tek/jobfizzer-user-ios
|
/UberdooX/Common_Class/Constant+Extension.swift
|
UTF-8
| 949
| 2.875
| 3
|
[] |
no_license
|
//
// Constant+Extension.swift
// MVCDemo
//
// Created by Pyramidions on 24/09/18.
// Copyright © 2018 Pyramidions. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController
{
func showAlert(title: String,msg : String)
{
let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
extension UIView {
func roundCorners(_ corners:UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
| true
|
26dd2eec688d96c8b25269517a5b14ccab21e102
|
Swift
|
8gb/FastDraw
|
/FastDraw/FastDraw/GestureRecognizerModel.swift
|
UTF-8
| 5,499
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// GestureRecognizerModel.swift
// realtimedrawing
//
// Created by 张睿杰 on 2019/11/11.
// Copyright © 2019 张睿杰. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizer
typealias Rectangle = (minX: CGFloat, minY: CGFloat, maxX: CGFloat, maxY: CGFloat)
public protocol GestureRecognizerModelDelegate: class {
func firstTouchDetected()
}
public class GestureRecognizerModel: UIGestureRecognizer {
public var brush: Brush!
public var stroke: Stroke!
public weak var scrollView: UIScrollView?
public weak var gestureDelegate: GestureRecognizerModelDelegate?
private var adjustForce: CGFloat = 0.4
private var adjustTime: CGFloat = 10000
private var previousTime: CGFloat?
private var previousPoint: CGPoint?
private var previousForce: CGFloat?
private var strokecolor: UIColor = .black
private var rect: Rectangle?
private var width: CGFloat = 3.2
private var coordinateSpaceView: UIView?
private var ensuredReferenceView: UIView {
if let view = coordinateSpaceView {
return view
} else {
return view!
}
}
private func append(touches: Set<UITouch>, event: UIEvent?) {
guard let touch = touches.first else {return}
savePoint(touch: touch, predicted: false)
}
private func savePoint(touch: UITouch, predicted: Bool) {
var touchForce: CGFloat
if touch.type == .direct {
touchForce = 1
} else {
touchForce = touch.force
}
let currentPoint = touch.preciseLocation(in: ensuredReferenceView)
if rect != nil {
if rect!.minX > currentPoint.x {
rect!.minX = currentPoint.x
}
if rect!.minY > currentPoint.y {
rect!.minY = currentPoint.y
}
if rect!.maxX < currentPoint.x {
rect!.maxX = currentPoint.x
}
if rect!.maxY < currentPoint.y {
rect!.maxY = currentPoint.y
}
} else {
rect = (minX: currentPoint.x, minY: currentPoint.y, maxX: currentPoint.x, maxY: currentPoint.y)
}
if touch.type == .direct {
if let previousTime = self.previousTime,
let previousPoint = self.previousPoint {
let currentTime = CGFloat(touch.timestamp)
let interval = currentTime - previousTime
let move = distance(previousPoint, currentPoint)
let speed = move / interval
var scale: CGFloat = 1.0
if scrollView != nil {
scale = scrollView!.zoomScale
}
if let previousForce = previousForce {
if speed > 1000 / scale && previousForce > 0.5 {
touchForce = previousForce - 0.1
} else if speed < 500 / scale && previousForce < 1.5 {
touchForce = previousForce + 0.1
} else {
touchForce = previousForce
}
}
self.previousTime = currentTime
self.previousPoint = currentPoint
self.previousForce = touchForce
} else {
self.previousPoint = currentPoint
self.previousTime = CGFloat(touch.timestamp)
}
}
touchForce = (touchForce + adjustForce) / 2
if brush.type == .eraser {
touchForce = 1
}
var point = Point()
point.force = Float(touchForce)
point.x = Float(currentPoint.x)
point.y = Float(currentPoint.y)
if point.x == stroke.offsetPoints.last?.x && point.y == stroke.offsetPoints.last?.y {
return
}
if stroke.offsetPoints.count == 0 {
stroke.basePoint = point
}
stroke.offsetPoints.append(Point.with{
$0.x = point.x - stroke.basePoint.x
$0.y = point.y - stroke.basePoint.y
$0.force = point.force
})
}
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
stroke = Stroke()
stroke.id = Int64.random(in: Int64.min ... Int64.max)
stroke.color = brush.color.hexa
stroke.width = Float(brush.width)
switch brush.type {
case .pen:
stroke.type = .pen
case .highlighter:
stroke.type = .highlighter
default:
stroke.type = .unknown
}
append(touches: touches, event: event)
state = .began
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if numberOfTouches == 1 {
gestureDelegate?.firstTouchDetected()
append(touches: touches, event: event)
state = .changed
} else {
state = .failed
}
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
append(touches: touches, event: event)
state = .ended
self.previousPoint = nil
self.previousTime = nil
self.previousForce = nil
}
public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
append(touches: touches, event: event)
}
}
| true
|
ead2419ab2c72c4b70be64c51bd3b34a13b99e3b
|
Swift
|
sven0311/hackatum2019
|
/Bay´n´b-Storyboard/Bay´n´b-Storyboard/TripsViewController.swift
|
UTF-8
| 1,501
| 2.75
| 3
|
[] |
no_license
|
//
// TripsViewController.swift
// Bay´n´b-Storyboard
//
// Created by Sven Andabaka on 23.11.19.
// Copyright © 2019 TUM LS1. All rights reserved.
//
import UIKit
class TripsViewController: UIViewController {
static var trips: [(PublicTransport?, Car?, Accommodation, Activity)] = [] {
didSet {
viewController?.tripTableView?.reloadData()
guard let tab = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController else {
return
}
tab.selectedIndex = 1
}
}
static var viewController: TripsViewController!
@IBOutlet weak var tripTableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
TripsViewController.viewController = self
tripTableView!.dataSource = self
tripTableView?.tableFooterView = UIView()
}
}
extension TripsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TripsViewController.trips.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let table = tableView.dequeueReusableCell(withIdentifier: "TripsViewCell")
let tripsTable = table as! TripsTableViewCell
tripsTable.trip = TripsViewController.trips[indexPath.row]
return tripsTable
}
}
| true
|
53f6ba22056450a150d843699fc498ce8f437999
|
Swift
|
presto95/HGCodeBaseUI
|
/Sources/UI.swift
|
UTF-8
| 996
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
//
// UI.swift
// ViewBuilderSwift
//
// Created by Presto on 08/08/2019.
// Copyright © 2019 presto. All rights reserved.
//
import UIKit
import Then
/// Defines a protocol that replaces the responsibility of Interface Builder.
///
/// You should make an object responsible for being UI of another object conforms to this protocol.
public protocol UI: Then {
associatedtype Owner: UIOwner
/// An owner of this UI object.
///
/// It is recommended to declare it as `unowned`.
///
/// It must conforms `UIOwner` protocol.
var owner: Owner { get }
/// A root view.
///
/// If the `owner` is a `UIViewController` object, this represents `owner.view`.
///
/// If the `owner` is a `UIView` object, this represents this itself.
var view: UIView { get }
init(owner: Owner)
}
public extension UI where Owner: UIViewController {
var view: UIView {
return owner.view
}
}
public extension UI where Owner: UIView {
var view: UIView {
return owner
}
}
| true
|
321fed820ee539c6e31b6110db9a8c1092e48a76
|
Swift
|
maryjenel/VIPER-Challenge
|
/Challenge/UserViewController.swift
|
UTF-8
| 2,224
| 2.671875
| 3
|
[] |
no_license
|
//
// UserViewController.swift
// Challenge
//
// Created by Jenel Myers on 7/14/17.
// Copyright © 2017 PetSmart. All rights reserved.
//
import Foundation
import UIKit
protocol UserViewInput {
func displayUsers(_ users:[User])
}
protocol UserViewOutput {
func getUsers()
}
class UserViewController: UIViewController {
var output: UserViewOutput!
var router: UserRouterInput!
var users: [User] = []
@IBOutlet weak var tableView: UITableView!
override func awakeFromNib() {
super.awakeFromNib()
UserConfigurator.sharedInstance.configure(viewController: self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.output.getUsers()
}
fileprivate func showError(_ title: String, message: String) {
QueueHelper.executeOnMainQueue {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "ok", style: .cancel) { action in })
self.present(alert, animated: true, completion: nil)
}
}
}
extension UserViewController: UserViewInput {
func displayUsers(_ users: [User]) {
self.users = users
self.reloadTable()
}
func displayError(_ error: UserRequestModel.Error) {
switch error {
case let .apiError(.some(message)):
self.showError("sorry", message: message)
case let .noData(.some(message)):
self.showError("sorry", message: message)
default:
break
}
}
}
extension UserViewController: UITableViewDataSource, UITableViewDelegate {
func reloadTable() {
QueueHelper.executeOnMainQueue {
self.tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
let user = self.users[indexPath.row]
cell.configure(forUser: user)
return cell
}
}
| true
|
a768adee0a08fc2d032b3f7e25cb9d4f28946e44
|
Swift
|
catalandres/MeasuringCup
|
/MeasuringCupTests/NIST44Tests.swift
|
UTF-8
| 30,818
| 2.90625
| 3
|
[] |
no_license
|
//
// NIST44Tests.swift
// MeasuringCup
//
// Created by Andrés Catalán on 2016–05–16.
// Copyright © 2016 Ayre. All rights reserved.
//
import XCTest
@testable import MeasuringCup
/// The National Institute of Standard and Technology (NIST) publishes a handbook of [Specifications, Tolerances, and Other Technical Requirements for Weighing and Measuring Devices](http://www.nist.gov/pml/wmd/pubs/hb44-14.cfm, called Handbook 44. In the [Appendix C](http://www.nist.gov/pml/wmd/pubs/upload/appc-14-hb44-final.pdf) it includes the General Tables of Unites of Measurement, with conversion values between many of the units that `MeasuringCup` represents. It is taken here as substance for unit tests to verify the relationships between units.
class NIST44Tests: XCTestCase {
// Page C-3, Units of Length
func test_C3_length() {
XCTAssertEqual(10.millimeters, 1.centimeters)
XCTAssertEqual(10.centimeters, 1.decimeters)
XCTAssertEqual(10.centimeters, 100.millimeters)
XCTAssertEqual(10.decimeters, 1.meters)
XCTAssertEqual(10.decimeters, 1000.millimeters)
XCTAssertEqual(10.meters, 1.decameters)
XCTAssertEqual(10.decameters, 1.hectometers)
XCTAssertEqual(10.decameters, 100.meters)
XCTAssertEqual(10.hectometers, 1.kilometers)
XCTAssertEqual(10.hectometers, 1000.meters)
}
// Page C-3, Units of Area
func test_C3_area() {
XCTAssertEqual(100.squareMillimeters, 1.squareCentimeters)
XCTAssertEqual(100.squareCentimeters, 1.squareDecimeters)
XCTAssertEqual(100.squareDecimeters, 1.squareMeters)
XCTAssertEqual(100.squareMeters, 1.squareDecameters)
XCTAssertEqual(100.squareMeters, 1.ares)
XCTAssertEqual(100.squareDecameters, 1.squareHectometers)
XCTAssertEqual(100.squareDecameters, 1.hectares)
XCTAssertEqual(100.squareHectometers, 1.squareKilometers)
}
// Page C-4, Units of Liquid Volume
func test_C4_liquidVolume() {
XCTAssertEqual(10.milliliters, 1.centiliters)
XCTAssertEqual(10.centiliters, 1.deciliters)
XCTAssertEqual(10.centiliters, 100.milliliters)
XCTAssertEqual(10.deciliters, 1.liters)
XCTAssertEqual(10.deciliters, 1000.milliliters)
XCTAssertEqual(10.liters, 1.decaliters)
XCTAssertEqual(10.decaliters, 1.hectoliters)
XCTAssertEqual(10.decaliters, 100.liters)
XCTAssertEqual(10.hectoliters, 1.kiloliters)
XCTAssertEqual(10.hectoliters, 1000.liters)
}
// Page C-4, Units of Volume
func test_C4_volume() {
XCTAssertEqual(1000.cubicMillimeters, 1.cubicCentimeters)
XCTAssertEqual(1000.cubicCentimeters, 1.cubicDecimeters)
XCTAssertEqual(1000.cubicCentimeters, 1000000.cubicMillimeters)
XCTAssertEqual(1000.cubicDecimeters, 1.cubicMeters)
XCTAssertEqual(1000.cubicDecimeters, 1000000.cubicCentimeters)
XCTAssertEqual(1000.cubicDecimeters, 1000000000.cubicMillimeters)
}
// Page C-4, Units of Mass
func test_C4_mass() {
XCTAssertEqual(10.milligrams, 1.centigrams)
XCTAssertEqual(10.centigrams, 1.decigrams)
XCTAssertEqual(10.centigrams, 100.milligrams)
XCTAssertEqual(10.decigrams, 1.grams)
XCTAssertEqual(10.decigrams, 1000.milligrams)
XCTAssertEqual(10.grams, 1.decagrams)
XCTAssertEqual(10.decagrams, 1.hectograms)
XCTAssertEqual(10.decagrams, 100.grams)
XCTAssertEqual(10.hectograms, 1.kilograms)
XCTAssertEqual(10.hectograms, 1000.grams)
XCTAssertEqual(1000.kilograms, 1.megagrams)
XCTAssertEqual(1000.kilograms, 1.metricTons)
}
func test_C4_USlength() {
XCTAssertEqual(12.inches, 1.feet)
XCTAssertEqual(3.feet, 1.yards)
XCTAssertEqual(16.5.surveyFeet, 1.surveyRods)
XCTAssertEqual(40.surveyRods, 1.surveyFurlongs)
XCTAssertEqual(40.surveyRods, 660.surveyFeet)
XCTAssertEqual(8.surveyFurlongs, 1.surveyMiles)
XCTAssertEqual(8.surveyFurlongs, 5280.surveyFeet)
XCTAssertEqual(1852.meters, 1.nauticalMiles)
}
func test_C5_USarea() {
XCTAssertEqual(144.squareInches, 1.squareFeet)
XCTAssertEqual(9.squareFeet, 1.squareYards)
XCTAssertEqual(9.squareFeet, 1296.squareInches)
XCTAssertEqual(272.25.squareSurveyFeet, 1.squareSurveyRods)
XCTAssertEqual(160.squareSurveyRods, 1.acres)
XCTAssertEqual(160.squareSurveyRods, 43560.squareSurveyFeet)
XCTAssertEqual(640.acres, 1.squareSurveyMiles)
// Untested: 1 mile square = 1 section of land
// 6 miles square = 1 township = 36 sections = 36 square miles
}
func test_C5_USvolume() {
XCTAssertEqual(1728.cubicInches, 1.cubicFeet)
XCTAssertEqual(27.cubicFeet, 1.cubicYards)
}
func test_C5_surveyorsChain() {
XCTAssertEqual(0.66.surveyFeet, 1.surveyLinks)
XCTAssertEqual(100.surveyLinks, 1.surveyChains)
XCTAssertEqual(100.surveyLinks, 4.surveyRods)
XCTAssertEqual(100.surveyLinks, 66.surveyFeet)
XCTAssertEqual(80.surveyChains, 1.surveyMiles)
XCTAssertEqual(80.surveyChains, 320.surveyRods)
XCTAssertEqual(80.surveyChains, 5280.surveyFeet)
}
func test_C5_USliquidVolume() {
XCTAssertEqual(4.gills(.american), 1.pints(.american))
XCTAssertEqual(4.gills(.american), 28.875.cubicInches)
XCTAssertEqual(2.pints(.american), 1.quarts(.american))
XCTAssertEqual(2.pints(.american), 57.75.cubicInches)
XCTAssertEqual(4.quarts(.american), 1.gallons(.american))
XCTAssertEqual(4.quarts(.american), 231.cubicInches)
XCTAssertEqual(4.quarts(.american), 8.pints(.american))
XCTAssertEqual(4.quarts(.american), 32.gills(.american))
}
func test_C5_apothecariesLiquidVolume() {
XCTAssertEqual(60.minims(.american), 1.fluidDrams(.american))
XCTAssertEqual(60.minims(.american), 0.2255859375.cubicInches)
XCTAssertEqual(8.fluidDrams(.american), 1.fluidOunces(.american))
XCTAssertEqual(8.fluidDrams(.american), 1.8046875.cubicInches)
XCTAssertEqual(16.fluidOunces(.american), 1.pints(.american))
XCTAssertEqual(16.fluidOunces(.american), 28.875.cubicInches)
XCTAssertEqual(16.fluidOunces(.american), 128.fluidDrams(.american))
XCTAssertEqual(2.pints(.american), 1.quarts(.american))
XCTAssertEqual(2.pints(.american), 57.75.cubicInches)
XCTAssertEqual(2.pints(.american), 256.fluidDrams(.american))
XCTAssertEqual(2.pints(.american), 32.fluidOunces(.american))
XCTAssertEqual(4.quarts(.american), 1.gallons(.american))
XCTAssertEqual(4.quarts(.american), 231.cubicInches)
XCTAssertEqual(4.quarts(.american), 1024.fluidDrams(.american))
XCTAssertEqual(4.quarts(.american), 128.fluidOunces(.american))
}
func test_C6_USdryVolume() {
XCTAssertEqual(2.dryPints, 1.dryQuarts)
XCTAssertEqual(1.dryQuarts, 67.200_625.cubicInches)
XCTAssertEqual(8.dryQuarts, 1.pecks(.american))
XCTAssertEqual(8.dryQuarts, 16.dryPints)
XCTAssertEqual(8.dryQuarts, 537.605.cubicInches)
XCTAssertEqual(4.pecks(.american), 1.bushels(.american))
XCTAssertEqual(4.pecks(.american), 32.dryQuarts)
XCTAssertEqual(4.pecks(.american), 2_150.42.cubicInches)
}
func test_C6_avoirdupoisMass() {
// Untested: 1 microlb = 0.000001 lb
XCTAssertEqual((27 + 11.0/32).grains, 1.drams)
XCTAssertEqual(16.drams, 1.ounces)
XCTAssertEqual(16.drams, 437.5.grains)
XCTAssertEqual(16.ounces, 1.pounds)
XCTAssertEqual(16.ounces, 256.drams)
XCTAssertEqual(16.ounces, 7_000.grains)
XCTAssertEqual(100.pounds, 1.hundredweights(.american))
XCTAssertEqual(20.hundredweights(.american), 1.tons(.american))
XCTAssertEqual(20.hundredweights(.american), 2_000.pounds)
XCTAssertEqual(112.pounds, 1.longHundredweights)
XCTAssertEqual(20.longHundredweights, 1.longTons)
XCTAssertEqual(20.longHundredweights, 2_240.pounds)
}
func test_C6_troyMass() {
XCTAssertEqual(24.grains, 1.pennyweights)
XCTAssertEqual(20.pennyweights, 1.ouncesTroy)
XCTAssertEqual(12.ouncesTroy, 1.poundsTroy)
XCTAssertEqual(12.ouncesTroy, 240.pennyweights)
XCTAssertEqual(12.ouncesTroy, 5_760.grains)
}
func test_C7_apothecariesMass() {
XCTAssertEqual(20.grains, 1.scruples)
XCTAssertEqual(3.scruples, 1.dramsApothecaries)
XCTAssertEqual(3.scruples, 60.grains)
XCTAssertEqual(8.dramsApothecaries, 1.ouncesApothecaries)
XCTAssertEqual(8.dramsApothecaries, 24.scruples)
XCTAssertEqual(8.dramsApothecaries, 480.grains)
XCTAssertEqual(12.ouncesApothecaries, 1.poundsApothecaries)
XCTAssertEqual(12.ouncesApothecaries, 96.dramsApothecaries)
XCTAssertEqual(12.ouncesApothecaries, 288.scruples)
XCTAssertEqual(12.ouncesApothecaries, 5_760.grains)
}
func test_C7_massBritish() {
XCTAssertEqual(14.pounds, 1.stone)
XCTAssertEqual(2.stone, 1.quarters(.british))
XCTAssertEqual(2.stone, 28.pounds)
XCTAssertEqual(4.quarters(.british), 1.hundredweights(.british))
XCTAssertEqual(4.quarters(.british), 112.pounds)
XCTAssertEqual(20.hundredweights(.british), 1.tons(.british))
XCTAssertEqual(20.hundredweights(.british), 2240.pounds)
}
func test_C7_apothecariesLiquidVolumeBritish() {
XCTAssertEqual(8.pints(.british), 1.gallons(.british))
XCTAssertEqual(8.pints(.british), 160.fluidOunces(.british))
}
func test_C8_length_international() {
XCTAssertEqual(1.inches, 2.54.centimeters)
XCTAssertEqual(1.inches, 0.025_4.meters)
XCTAssertEqual(1.feet, 12.inches)
XCTAssertEqual(1.feet, 30.48.centimeters)
XCTAssertEqual(1.feet, 0.3048.meters)
XCTAssertEqual(1.yards, 36.inches)
XCTAssertEqual(1.yards, 3.feet)
XCTAssertEqual(1.yards, 91.44.centimeters)
XCTAssertEqual(1.yards, 0.9144.meters)
XCTAssertEqual(1.miles, 63_360.inches)
XCTAssertEqual(1.miles, 5_280.feet)
XCTAssertEqual(1.miles, 1_760.yards)
XCTAssertEqual(1.miles, 160_934.4.centimeters)
XCTAssertEqual(1.miles, 1_609.344.meters)
XCTAssertEqual(1.centimeters, 0.01.meters)
XCTAssertEqual(1.meters, 100.centimeters)
}
func test_C8_length_survey() {
XCTAssertEqual(1.surveyLinks, 0.66.surveyFeet)
XCTAssertEqual(1.surveyLinks, 0.04.surveyRods)
XCTAssertEqual(1.surveyLinks, 0.01.surveyChains)
XCTAssertEqual(1.surveyLinks, 0.000_125.surveyMiles)
XCTAssertEqual(1.surveyRods, 25.surveyLinks)
XCTAssertEqual(1.surveyRods, 16.5.surveyFeet)
XCTAssertEqual(1.surveyRods, 0.25.surveyChains)
XCTAssertEqual(1.surveyRods, 0.003_125.surveyMiles)
XCTAssertEqual(1.surveyChains, 100.surveyLinks)
XCTAssertEqual(1.surveyChains, 66.surveyFeet)
XCTAssertEqual(1.surveyChains, 4.surveyRods)
XCTAssertEqual(1.surveyChains, 0.012_5.surveyMiles)
XCTAssertEqual(1.surveyMiles, 8_000.surveyLinks)
XCTAssertEqual(1.surveyMiles, 5_280.surveyFeet)
XCTAssertEqual(1.surveyMiles, 320.surveyRods)
XCTAssertEqual(1.surveyMiles, 80.surveyChains)
}
func test_C8_footnote() {
XCTAssertEqual(1.feet, 0.999_998.surveyFeet)
XCTAssertEqual(1.miles, 0.999_998.surveyMiles)
}
func test_C9_area_international() {
XCTAssertEqual(1.squareInches, 6.451_6.squareCentimeters)
XCTAssertEqual(1.squareInches, 0.000_645_16.squareMeters)
XCTAssertEqual(1.squareFeet, 144.squareInches)
XCTAssertEqual(1.squareFeet, 929.030_4.squareCentimeters)
XCTAssertEqual(1.squareFeet, 0.092_903_04.squareMeters)
XCTAssertEqual(1.squareYards, 1_296.squareInches)
XCTAssertEqual(1.squareYards, 9.squareFeet)
XCTAssertEqual(1.squareYards, 8361.273_6.squareCentimeters)
XCTAssertEqual(1.squareYards, 0.836_127_36.squareMeters)
XCTAssertEqual(1.squareMiles, 4_014_489_600.0.squareInches)
XCTAssertEqual(1.squareMiles, 27_878_400.squareFeet)
XCTAssertEqual(1.squareMiles, 3_097_600.squareYards)
XCTAssertEqual(1.squareMiles, 25_899_881_103.36.squareCentimeters)
XCTAssertEqual(1.squareMiles, 2_589_988.110_336.squareMeters)
XCTAssertEqual(1.squareCentimeters, 0.000_1.squareMeters)
XCTAssertEqual(1.squareMeters, 10_000.squareCentimeters)
}
func test_C9_footnote() {
XCTAssertEqual(1.surveyFeet, (1200.0/3937).meters)
XCTAssertEqual(1.feet, (12 * 0.0254).meters)
XCTAssertEqual(1.feet, (0.0254 * 39.37).surveyFeet)
}
func test_C9_area_survey() {
XCTAssertEqual(1.squareSurveyRods, 272.25.squareSurveyFeet)
XCTAssertEqual(1.squareSurveyRods, 0.062_5.squareSurveyChains)
XCTAssertEqual(1.squareSurveyRods, 0.006_25.acres)
XCTAssertEqual(1.squareSurveyRods, 0.000_009_765_625.squareSurveyMiles)
XCTAssertEqual(1.squareSurveyChains, 4_356.squareSurveyFeet)
XCTAssertEqual(1.squareSurveyChains, 16.squareSurveyRods)
XCTAssertEqual(1.squareSurveyChains, 0.1.acres)
XCTAssertEqual(1.squareSurveyChains, 0.000_156_25.squareSurveyMiles)
XCTAssertEqual(1.acres, 43_560.squareSurveyFeet)
XCTAssertEqual(1.acres, 160.squareSurveyRods)
XCTAssertEqual(1.acres, 10.squareSurveyChains)
XCTAssertEqual(1.acres, 0.001_562_5.squareSurveyMiles)
XCTAssertEqual(1.squareSurveyMiles, 27_878_400.squareSurveyFeet)
XCTAssertEqual(1.squareSurveyMiles, 102_400.squareSurveyRods)
XCTAssertEqual(1.squareSurveyMiles, 6_400.squareSurveyChains)
XCTAssertEqual(1.squareSurveyMiles, 640.acres)
XCTAssertEqual(1.squareMeters, 0.000_1.hectares)
XCTAssertEqual(1.hectares, 10_000.squareMeters)
}
func test_C10_volume() {
XCTAssertEqual(1.cubicInches, 16.387_064.cubicCentimeters)
XCTAssertEqual(1.cubicInches, 16.387_064.milliliters)
XCTAssertEqual(1.cubicInches, 0.016_387_064.cubicDecimeters)
XCTAssertEqual(1.cubicInches, 0.016_387_064.liters)
XCTAssertEqual(1.cubicInches, 0.000_016_387_064.cubicMeters)
XCTAssertEqual(1.cubicFeet, 1_728.cubicInches)
XCTAssertEqual(1.cubicFeet, 28_316.846_592.cubicCentimeters)
XCTAssertEqual(1.cubicFeet, 28_316.846_592.milliliters)
XCTAssertEqual(1.cubicFeet, 28.316_846_592.cubicDecimeters)
XCTAssertEqual(1.cubicFeet, 28.316_846_592.liters)
XCTAssertEqual(1.cubicFeet, 0.028_316_846_592.cubicMeters)
XCTAssertEqual(1.cubicYards, 46_656.cubicInches)
XCTAssertEqual(1.cubicYards, 27.cubicFeet)
XCTAssertEqual(1.cubicYards, 764_554.857_984.cubicCentimeters)
XCTAssertEqual(1.cubicYards, 764_554.857_984.milliliters)
XCTAssertEqual(1.cubicYards, 764.554_857_984.cubicDecimeters)
XCTAssertEqual(1.cubicYards, 764.554_857_984.liters)
XCTAssertEqual(1.cubicYards, 0.764_554_857_984.cubicMeters)
XCTAssertEqual(1.cubicCentimeters, 0.001.cubicDecimeters)
XCTAssertEqual(1.cubicCentimeters, 0.001.liters)
XCTAssertEqual(1.cubicCentimeters, 0.000_001.cubicMeters)
XCTAssertEqual(1.milliliters, 0.001.cubicDecimeters)
XCTAssertEqual(1.milliliters, 0.001.liters)
XCTAssertEqual(1.milliliters, 0.000_001.cubicMeters)
XCTAssertEqual(1.cubicDecimeters, 1_000.cubicCentimeters)
XCTAssertEqual(1.cubicDecimeters, 1_000.milliliters)
XCTAssertEqual(1.cubicDecimeters, 0.001.cubicMeters)
XCTAssertEqual(1.liters, 1_000.cubicCentimeters)
XCTAssertEqual(1.liters, 1_000.milliliters)
XCTAssertEqual(1.liters, 0.001.cubicMeters)
XCTAssertEqual(1.cubicMeters, 1_000_000.cubicCentimeters)
XCTAssertEqual(1.cubicMeters, 1_000_000.milliliters)
XCTAssertEqual(1.cubicMeters, 1_000.cubicDecimeters)
XCTAssertEqual(1.cubicMeters, 1_000.liters)
}
func test_C11_dryVolume() {
XCTAssertEqual(1.dryPints, 0.5.dryQuarts)
XCTAssertEqual(1.dryPints, 0.062_5.pecks(.american))
XCTAssertEqual(1.dryPints, 0.015_625.bushels(.american))
XCTAssertEqual(1.dryQuarts, 2.dryPints)
XCTAssertEqual(1.dryQuarts, 0.125.pecks(.american))
XCTAssertEqual(1.dryQuarts, 0.031_25.bushels(.american))
XCTAssertEqual(1.pecks(.american), 16.dryPints)
XCTAssertEqual(1.pecks(.american), 8.dryQuarts)
XCTAssertEqual(1.pecks(.american), 0.25.bushels(.american))
XCTAssertEqual(1.pecks(.american), 537.605.cubicInches)
XCTAssertEqual(1.bushels(.american), 64.dryPints)
XCTAssertEqual(1.bushels(.american), 32.dryQuarts)
XCTAssertEqual(1.bushels(.american), 4.pecks(.american))
XCTAssertEqual(1.bushels(.american), 2_150.42.cubicInches)
XCTAssertEqual(1.bushels(.american), 35.239_070_166_88.liters)
XCTAssertEqual(1.bushels(.american), 0.035_239_070_166_88.cubicMeters)
XCTAssertEqual(1.cubicInches, 0.016_387_064.liters)
XCTAssertEqual(1.cubicInches, 0.000_016_387_064.cubicMeters)
XCTAssertEqual(1.cubicFeet, 1728.cubicInches)
XCTAssertEqual(1.cubicFeet, 28.316_846_592.liters)
XCTAssertEqual(1.cubicFeet, 0.028_316_846_592.cubicMeters)
XCTAssertEqual(1.liters, 0.001.cubicMeters)
XCTAssertEqual(1.cubicMeters, 1_000.liters)
}
func test_C11_liquidVolume() {
XCTAssertEqual(1.fluidDrams(.american), 60.minims(.american))
XCTAssertEqual(1.fluidDrams(.american), 0.125.fluidOunces(.american))
XCTAssertEqual(1.fluidDrams(.american), 0.031_25.gills(.american))
XCTAssertEqual(1.fluidDrams(.american), 0.007_812_5.pints(.american))
XCTAssertEqual(1.fluidDrams(.american), 0.003_906_25.quarts(.american))
XCTAssertEqual(1.fluidDrams(.american), 0.000_976_562_5.gallons(.american))
XCTAssertEqual(1.fluidOunces(.american), 480.minims(.american))
XCTAssertEqual(1.fluidOunces(.american), 8.fluidDrams(.american))
XCTAssertEqual(1.fluidOunces(.american), 0.25.gills(.american))
XCTAssertEqual(1.fluidOunces(.american), 0.062_5.pints(.american))
XCTAssertEqual(1.fluidOunces(.american), 0.031_25.quarts(.american))
XCTAssertEqual(1.fluidOunces(.american), 0.007_812_5.gallons(.american))
XCTAssertEqual(1.fluidOunces(.american), 1.804_687_5.cubicInches)
XCTAssertEqual(1.gills(.american), 1_920.minims(.american))
XCTAssertEqual(1.gills(.american), 32.fluidDrams(.american))
XCTAssertEqual(1.gills(.american), 4.fluidOunces(.american))
XCTAssertEqual(1.gills(.american), 0.25.pints(.american))
XCTAssertEqual(1.gills(.american), 0.125.quarts(.american))
XCTAssertEqual(1.gills(.american), 0.031_25.gallons(.american))
XCTAssertEqual(1.gills(.american), 7.218_75.cubicInches)
XCTAssertEqual(1.pints(.american), 7_680.minims(.american))
XCTAssertEqual(1.pints(.american), 128.fluidDrams(.american))
XCTAssertEqual(1.pints(.american), 16.fluidOunces(.american))
XCTAssertEqual(1.pints(.american), 4.gills(.american))
XCTAssertEqual(1.pints(.american), 0.5.quarts(.american))
XCTAssertEqual(1.pints(.american), 0.125.gallons(.american))
XCTAssertEqual(1.pints(.american), 28.875.cubicInches)
XCTAssertEqual(1.quarts(.american), 15_360.minims(.american))
XCTAssertEqual(1.quarts(.american), 256.fluidDrams(.american))
XCTAssertEqual(1.quarts(.american), 32.fluidOunces(.american))
XCTAssertEqual(1.quarts(.american), 8.gills(.american))
XCTAssertEqual(1.quarts(.american), 2.pints(.american))
XCTAssertEqual(1.quarts(.american), 0.25.gallons(.american))
XCTAssertEqual(1.quarts(.american), 57.75.cubicInches)
XCTAssertEqual(1.gallons(.american), 61_440.minims(.american))
XCTAssertEqual(1.gallons(.american), 1_024.fluidDrams(.american))
XCTAssertEqual(1.gallons(.american), 128.fluidOunces(.american))
XCTAssertEqual(1.gallons(.american), 32.gills(.american))
XCTAssertEqual(1.gallons(.american), 8.pints(.american))
XCTAssertEqual(1.gallons(.american), 4.quarts(.american))
XCTAssertEqual(1.gallons(.american), 231.cubicInches)
XCTAssertEqual(1.gallons(.american), 231.cubicInches)
XCTAssertEqual(1.gallons(.american), 3_785.411_784.milliliters)
XCTAssertEqual(1.gallons(.american), 3.785_411_784.liters)
XCTAssertEqual(1.cubicFeet, 1728.cubicInches)
XCTAssertEqual(1.milliliters, 0.001.liters)
XCTAssertEqual(1.liters, 1_000.milliliters)
}
func test_C12_mass() {
XCTAssertEqual(1.ounces, 0.062_5.pounds)
XCTAssertEqual(1.ounces, 0.000_625.hundredweights(.american))
XCTAssertEqual(1.ounces, 0.000_031_25.tons(.american))
XCTAssertEqual(1.ounces, 0.028_349_523_125.kilograms)
XCTAssertEqual(1.ounces, 0.000_028_349_523_125.metricTons)
XCTAssertEqual(1.pounds, 16.ounces)
XCTAssertEqual(1.pounds, 0.01.hundredweights(.american))
XCTAssertEqual(1.pounds, 0.000_5.tons(.american))
XCTAssertEqual(1.pounds, 0.453_592_37.kilograms)
XCTAssertEqual(1.pounds, 0.000_453_592_37.metricTons)
XCTAssertEqual(1.hundredweights(.american), 1_600.ounces)
XCTAssertEqual(1.hundredweights(.american), 100.pounds)
XCTAssertEqual(1.hundredweights(.american), 0.05.tons(.american))
XCTAssertEqual(1.hundredweights(.american), 45.359_237.kilograms)
XCTAssertEqual(1.hundredweights(.american), 0.045_359_237.metricTons)
XCTAssertEqual(1.tons(.american), 32_000.ounces)
XCTAssertEqual(1.tons(.american), 2_000.pounds)
XCTAssertEqual(1.tons(.american), 20.hundredweights(.american))
XCTAssertEqual(1.tons(.american), 907.184_74.kilograms)
XCTAssertEqual(1.tons(.american), 0.907_184_74.metricTons)
XCTAssertEqual(1.longTons, 35_840.ounces)
XCTAssertEqual(1.longTons, 2_240.pounds)
XCTAssertEqual(1.longTons, 22.4.hundredweights(.american))
XCTAssertEqual(1.longTons, 1.12.tons(.american))
XCTAssertEqual(1.longTons, 1_016.046_908_8.kilograms)
XCTAssertEqual(1.longTons, 1.016_046_908_8.metricTons)
XCTAssertEqual(1.kilograms, 0.001.metricTons)
XCTAssertEqual(1.metricTons, 1_000.kilograms)
}
func test_C13_mass() {
XCTAssertEqual(1.grains, 0.05.scruples)
XCTAssertEqual(1.grains, 64.798_91.milligrams)
XCTAssertEqual(1.grains, 0.064_798_91.grams)
XCTAssertEqual(1.grains, 0.000_064_798_91.kilograms)
XCTAssertEqual(1.scruples, 20.grains)
XCTAssertEqual(1.scruples, 1_295.978_2.milligrams)
XCTAssertEqual(1.scruples, 1.295_978_2.grams)
XCTAssertEqual(1.scruples, 0.001_295_978_2.kilograms)
XCTAssertEqual(1.pennyweights, 24.grains)
XCTAssertEqual(1.pennyweights, 1.2.scruples)
XCTAssertEqual(1.pennyweights, 0.4.dramsApothecaries)
XCTAssertEqual(1.pennyweights, 0.05.ouncesTroy)
XCTAssertEqual(1.pennyweights, 0.05.ouncesApothecaries)
XCTAssertEqual(1.pennyweights, 1_555.173_84.milligrams)
XCTAssertEqual(1.pennyweights, 1.555_173_84.grams)
XCTAssertEqual(1.pennyweights, 0.001_555_173_84.kilograms)
XCTAssertEqual(1.drams, 27.343_75.grains)
XCTAssertEqual(1.drams, 1.367_187_5.scruples)
XCTAssertEqual(1.drams, 0.062_5.ounces)
XCTAssertEqual(1.drams, 1_771.845_195_312_5.milligrams)
XCTAssertEqual(1.drams, 1.771_845_195_312_5.grams)
XCTAssertEqual(1.drams, 0.001_771_845_195_312_5.kilograms)
XCTAssertEqual(1.dramsApothecaries, 60.grains)
XCTAssertEqual(1.dramsApothecaries, 3.scruples)
XCTAssertEqual(1.dramsApothecaries, 2.5.pennyweights)
XCTAssertEqual(1.dramsApothecaries, 0.125.ouncesTroy)
XCTAssertEqual(1.dramsApothecaries, 0.125.ouncesApothecaries)
XCTAssertEqual(1.dramsApothecaries, 3_887.934_6.milligrams)
XCTAssertEqual(1.dramsApothecaries, 3.887_934_6.grams)
XCTAssertEqual(1.dramsApothecaries, 0.003_887_934_6.kilograms)
XCTAssertEqual(1.ounces, 437.5.grains)
XCTAssertEqual(1.ounces, 21.875.scruples)
XCTAssertEqual(1.ounces, 16.drams)
XCTAssertEqual(1.ounces, 0.062_5.pounds)
XCTAssertEqual(1.ounces, 28_349.523_125.milligrams)
XCTAssertEqual(1.ounces, 28.349_523_125.grams)
XCTAssertEqual(1.ounces, 0.028_349_523_125.kilograms)
XCTAssertEqual(1.ouncesApothecaries, 480.grains)
XCTAssertEqual(1.ouncesApothecaries, 24.scruples)
XCTAssertEqual(1.ouncesApothecaries, 20.pennyweights)
XCTAssertEqual(1.ouncesApothecaries, 8.dramsApothecaries)
XCTAssertEqual(1.ouncesApothecaries, 1.ouncesTroy)
XCTAssertEqual(1.ouncesApothecaries, 31_103.476_8.milligrams)
XCTAssertEqual(1.ouncesApothecaries, 31.103_476_8.grams)
XCTAssertEqual(1.ouncesApothecaries, 0.031_103_476_8.kilograms)
XCTAssertEqual(1.ouncesTroy, 480.grains)
XCTAssertEqual(1.ouncesTroy, 24.scruples)
XCTAssertEqual(1.ouncesTroy, 20.pennyweights)
XCTAssertEqual(1.ouncesTroy, 8.dramsApothecaries)
XCTAssertEqual(1.ouncesTroy, 1.ouncesApothecaries)
XCTAssertEqual(1.ouncesTroy, 31_103.476_8.milligrams)
XCTAssertEqual(1.ouncesTroy, 31.103_476_8.grams)
XCTAssertEqual(1.ouncesTroy, 0.031_103_476_8.kilograms)
XCTAssertEqual(1.poundsApothecaries, 5_760.grains)
XCTAssertEqual(1.poundsApothecaries, 288.scruples)
XCTAssertEqual(1.poundsApothecaries, 240.pennyweights)
XCTAssertEqual(1.poundsApothecaries, 96.dramsApothecaries)
XCTAssertEqual(1.poundsApothecaries, 12.ouncesApothecaries)
XCTAssertEqual(1.poundsApothecaries, 12.ouncesTroy)
XCTAssertEqual(1.poundsApothecaries, 1.poundsTroy)
XCTAssertEqual(1.poundsApothecaries, 373_241.721_6.milligrams)
XCTAssertEqual(1.poundsApothecaries, 373.241_721_6.grams)
XCTAssertEqual(1.poundsApothecaries, 0.373_241_721_6.kilograms)
XCTAssertEqual(1.poundsTroy, 5_760.grains)
XCTAssertEqual(1.poundsTroy, 288.scruples)
XCTAssertEqual(1.poundsTroy, 240.pennyweights)
XCTAssertEqual(1.poundsTroy, 96.dramsApothecaries)
XCTAssertEqual(1.poundsTroy, 12.ouncesApothecaries)
XCTAssertEqual(1.poundsTroy, 12.ouncesTroy)
XCTAssertEqual(1.poundsTroy, 1.poundsApothecaries)
XCTAssertEqual(1.poundsTroy, 373_241.721_6.milligrams)
XCTAssertEqual(1.poundsTroy, 373.241_721_6.grams)
XCTAssertEqual(1.poundsTroy, 0.373_241_721_6.kilograms)
XCTAssertEqual(1.pounds, 7_000.grains)
XCTAssertEqual(1.pounds, 350.scruples)
XCTAssertEqual(1.pounds, 256.drams)
XCTAssertEqual(1.pounds, 16.ounces)
XCTAssertEqual(1.pounds, 453_592.37.milligrams)
XCTAssertEqual(1.pounds, 453.592_37.grams)
XCTAssertEqual(1.pounds, 0.453_592_37.kilograms)
XCTAssertEqual(1.milligrams, 0.001.grams)
XCTAssertEqual(1.milligrams, 0.000_001.kilograms)
XCTAssertEqual(1.grams, 1_000.milligrams)
XCTAssertEqual(1.grams, 0.001.kilograms)
XCTAssertEqual(1.kilograms, 1_000_000.milligrams)
XCTAssertEqual(1.kilograms, 1_000.grams)
}
func test_C15_length() {
XCTAssertEqual(1.ångströms, 0.1.nanometers)
XCTAssertEqual(1.ångströms, 0.000_1.micrometers)
XCTAssertEqual(1.ångströms, 0.000_000_1.millimeters)
XCTAssertEqual(1.surveyChains, 66.surveyFeet)
XCTAssertEqual(1.fathoms, 6.feet)
XCTAssertEqual(1.feet, 0.304_8.meters)
XCTAssertEqual(1.surveyFurlongs, 10.surveyChains)
XCTAssertEqual(1.surveyFurlongs, 660.surveyFeet)
XCTAssertEqual(1.surveyFurlongs, 0.125.surveyMiles)
XCTAssertEqual(1.inches, 2.54.centimeters)
XCTAssertEqual(1.leagues, 3.miles)
XCTAssertEqual(1.surveyLinks, 0.66.surveyFeet)
XCTAssertEqual(1.micrometers, 0.001.millimeters)
}
func test_C16_length() {
XCTAssertEqual(1.miles, 5_280.feet)
XCTAssertEqual(1.nauticalMiles, 1_852.meters)
XCTAssertEqual(1.millimeters, 0.001.meters)
XCTAssertEqual(1.surveyRods, 16.5.surveyFeet)
XCTAssertEqual(1.yards, 0.914_4.meters)
}
func test_C16_area() {
XCTAssertEqual(1.acres, 43_560.squareSurveyFeet)
XCTAssertEqual(1.squareInches, 6.451_6.squareCentimeters)
}
func test_C17_volume() {
// Untested: 1 bushel = 2150.42 cubic inches
XCTAssertEqual(1.cords, 128.cubicFeet)
XCTAssertEqual(1.cups, 8.fluidOunces(.american))
XCTAssertEqual(1.cups, 0.5.pints(.american))
}
func test_C18_volume() {
XCTAssertEqual(1.fluidDrams(.american), 0.125.fluidOunces(.american))
XCTAssertEqual(1.gallons(.american), 231.cubicInches)
XCTAssertEqual(1.gallons(.american), 128.fluidOunces(.american))
XCTAssertEqual(1.gills(.american), 4.fluidOunces(.american))
XCTAssertEqual(1.quarts(.american), 57.75.cubicInches)
}
func test_C19_volume() {
XCTAssertEqual(1.tablespoons, 3.teaspoons)
XCTAssertEqual(1.tablespoons, 0.5.fluidOunces(.american))
XCTAssertEqual(1.teaspoons, (1.0/3).tablespoons)
}
func test_C19_mass() {
XCTAssertEqual(1.carats, 200.milligrams)
XCTAssertEqual(1.dramsApothecaries, 60.grains)
XCTAssertEqual(1.grains, 64.798_91.milligrams)
XCTAssertEqual(1.longHundredweights, 112.pounds)
XCTAssertEqual(1.hundredweights(.american), 100.pounds)
XCTAssertEqual(1.ounces, 437.5.grains)
XCTAssertEqual(1.ouncesTroy, 480.grains)
XCTAssertEqual(1.ouncesApothecaries, 480.grains)
}
func test_C20_mass() {
XCTAssertEqual(1.pounds, 7_000.grains)
XCTAssertEqual(1.pounds, 453.592_37.grams)
XCTAssertEqual(1.poundsTroy, 5760.grains)
XCTAssertEqual(1.poundsApothecaries, 5760.grains)
XCTAssertEqual(1.scruples, 20.grains)
XCTAssertEqual(1.longTons, 2240.pounds)
XCTAssertEqual(1.longTons, 1.12.tons(.american))
XCTAssertEqual(1.tons(.american), 2000.pounds)
}
}
| true
|
d2856ed6a007aae7a1869c3ed56dca1a24d59f91
|
Swift
|
kersuzananthony/ios-swift-spriteKit-bat-bat-fly
|
/Bat bat fly!/TrapDown.swift
|
UTF-8
| 720
| 2.53125
| 3
|
[] |
no_license
|
//
// TrapDown.swift
// Bat bat fly!
//
// Created by Kersuzan on 21/01/2016.
// Copyright © 2016 Kersuzan. All rights reserved.
//
import SpriteKit
class TrapDown: Trap {
convenience init() {
self.init(initWithTexture: GameManager.sharedInstance.trapDown)
self.anchorPoint = CGPoint(x: 0.5, y: 0)
self.trapClosedFrame = GameManager.sharedInstance.trapDownCloseAnimationTexture
}
override func initPhysics() {
self.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.size.width, height: 2 * self.size.height))
self.physicsBody!.categoryBitMask = GameManager.sharedInstance.COLLIDER_TRAP
super.initPhysics()
}
}
| true
|
c4cfa7bac1fc181bab528915a9c6f9adf644d110
|
Swift
|
HeegeePark/DataStructure
|
/LeetCode/DP.playground/Pages/Longest Palindromic Substring.xcplaygroundpage/Contents.swift
|
UTF-8
| 889
| 3.875
| 4
|
[] |
no_license
|
// 리트코드 거꾸로 해도 똑같은 가장 긴 부분 문자열 찾기
class Solution {
// 부분 문자열 확장하는 함수
func expand(_ left: Int, _ right: Int, _ s: [String]) -> String {
var newLeft = left
var newRight = right
while newLeft >= 0 && newRight < s.count && s[newLeft] == s[newRight] {
newLeft -= 1
newRight += 1
}
return s[newLeft + 1..<newRight].joined()
}
func longestPalindrome(_ s: String) -> String {
let sArr = s.map { String($0) }
var answer = ""
if s.count < 2 || s == sArr.last! { return s }
for i in 0..<s.count-1 {
answer = [answer, expand(i, i, sArr), expand(i, i+1, sArr)].max { $0.count < $1.count }!
}
return answer
}
}
let s = Solution()
s.longestPalindrome("ibvjkmpyzsifuxcabqqpahjdeuzaybqsrsmbfplxycsafogotliyvhxjtkrbzqxlyfwujzhkdafhebvsdhkkdbhlhmaoxmbkqiwiusngkbdhlvxdyvnjrzvxmukvdfobzlmvnbnilnsyrgoygfdzjlymhprcpxsnxpcafctikxxybcusgjwmfklkffehbvlhvxfiddznwumxosomfbgxoruoqrhezgsgidgcfzbtdftjxeahriirqgxbhicoxavquhbkaomrroghdnfkknyigsluqebaqrtcwgmlnvmxoagisdmsokeznjsnwpxygjjptvyjjkbmkxvlivinmpnpxgmmorkasebngirckqcawgevljplkkgextudqaodwqmfljljhrujoerycoojwwgtklypicgkyaboqjfivbeqdlonxeidgxsyzugkntoevwfuxovazcyayvwbcqswzhytlmtmrtwpikgacnpkbwgfmpavzyjoxughwhvlsxsgttbcyrlkaarngeoaldsdtjncivhcfsaohmdhgbwkuemcembmlwbwquxfaiukoqvzmgoeppieztdacvwngbkcxknbytvztodbfnjhbtwpjlzuajnlzfmmujhcggpdcwdquutdiubgcvnxvgspmfumeqrofewynizvynavjzkbpkuxxvkjujectdyfwygnfsukvzflcuxxzvxzravzznpxttduajhbsyiywpqunnarabcroljwcbdydagachbobkcvudkoddldaucwruobfylfhyvjuynjrosxczgjwudpxaqwnboxgxybnngxxhibesiaxkicinikzzmonftqkcudlzfzutplbycejmkpxcygsafzkgudy")
| true
|
65d86490c06d85c103251e4a88a9466cd11c2e1b
|
Swift
|
AndriiPp/SimpleGame
|
/WarFly/GameScene.swift
|
UTF-8
| 1,951
| 2.8125
| 3
|
[] |
no_license
|
//
// GameScene.swift
// WarFly
//
// Created by Andrii Pyvovarov on 2019-11-28.
// Copyright © 2019 Andrii Pyvovarov. All rights reserved.
//
import SpriteKit
import GameplayKit
import CoreMotion
class GameScene: SKScene {
var player: SKSpriteNode!
let motionManager = CMMotionManager()
var xAcceleretion: CGFloat = 0
override func didMove(to view: SKView) {
let screenCenterPont = CGPoint(x: self.size.width/2, y: self.size.height/2)
let background = Background.populateBackgrounf(at: screenCenterPont)
background.size = self.size
self.addChild(background)
let screen = UIScreen.main.bounds
for _ in 1...5 {
let x: CGFloat = CGFloat(GKRandomSource.sharedRandom().nextInt(upperBound: Int(screen.size.width)))
let y: CGFloat = CGFloat(GKRandomSource.sharedRandom().nextInt(upperBound: Int(screen.size.height)))
let island = Island.populateSpriteAtPoint(at: CGPoint(x: x, y: y))
self.addChild(island)
let cloud = Cloud.populateSpriteAtPoint(at: CGPoint(x: x, y: y))
self.addChild(cloud)
}
player = PlayerPlane.populate(at: CGPoint(x: screen.size.width/2, y: 100))
self.addChild(player)
motionManager.accelerometerUpdateInterval = 0.2
motionManager.startAccelerometerUpdates(to: OperationQueue.current!) { (data, err) in
if let data = data {
let acceleration = data.acceleration
self.xAcceleretion = CGFloat(acceleration.x * 0.7) + self.xAcceleretion*0.3
}
}
}
override func didSimulatePhysics() {
super.didSimulatePhysics()
player.position.x += xAcceleretion + 50
if player.position.x < -70 {
player.position.x = self.size.width + 70
} else if player.position.x > self.size.width + 70 {
player.position.x = -70
}
}
}
| true
|
05c8bfccfcba8ae5e1e51639f7c52b7161e9aafd
|
Swift
|
jihokim94/IOS-STUDY
|
/xcode12+/View/ViewCatalog/ViewCatalog/SystemViews/Controls/Slider/SimpleSliderViewController.swift
|
UTF-8
| 626
| 2.90625
| 3
|
[] |
no_license
|
import UIKit
class SimpleSliderViewController: UIViewController {
@IBOutlet weak var redSlider: UISlider!
@IBOutlet weak var greenSlider: UISlider!
@IBOutlet weak var blueSlider: UISlider!
@IBAction func sliderChaged(_ sender: UISlider) {
let r = CGFloat(redSlider.value)
let g = CGFloat(greenSlider.value)
let b = CGFloat(blueSlider.value)
let color = UIColor(red: r, green: g, blue: b, alpha: 1.0)
view.backgroundColor = color
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
| true
|
9530a3644b7d38ba2687ecbc6906b5960d94760c
|
Swift
|
haoyithong/Swift-Learning
|
/MyLibrary/MyLibrary/RemoteReadFile/RemoteReadFile.swift
|
UTF-8
| 3,636
| 2.734375
| 3
|
[] |
no_license
|
//
// RemoteReadFile.swift
// ReadRemoteFile
//
// Created by Thong Hao Yi on 02/04/2016.
// Copyright © 2016 Thong Hao Yi. All rights reserved.
//
import UIKit
class RemoteReadFile: NSObject,NSURLSessionDownloadDelegate,UIDocumentInteractionControllerDelegate {
static let sharedInstance = RemoteReadFile()
var downloadTask: NSURLSessionDownloadTask!
var backgroundSession: NSURLSession!
var documentDirectoryPath: String!
let fileManager:NSFileManager! = NSFileManager()
var fileName: String!
var viewController: UIViewController!
// MARK: public method
func readUrl (urlStr: String, viewController: UIViewController){
var fullFilePathStr = urlStr
if urlStr.hasPrefix("http://") || urlStr.hasPrefix("https://"){
print("Prefix exists")
}
else
{
fullFilePathStr = "http://" + urlStr
}
self.initRemoteReadFile()
let url = NSURL(string: fullFilePathStr)
self.fileName = url!.lastPathComponent
self.viewController = viewController
downloadTask = backgroundSession.downloadTaskWithURL(url!)
downloadTask.resume()
}
// MARK: private method
func initRemoteReadFile() {
let backgroundSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("backgroundSession")
backgroundSession = NSURLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
self.documentDirectoryPath = path[0]
}
func showFileWithPath(path: String){
let isFileFound:Bool? = NSFileManager.defaultManager().fileExistsAtPath(path)
if isFileFound == true{
let viewer = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: path))
viewer.delegate = self
viewer.presentPreviewAnimated(true)
}
}
// MARK: NSURLSessionDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){
let destinationURLForFile = NSURL(fileURLWithPath: self.documentDirectoryPath.stringByAppendingString(self.fileName!))
if self.fileManager.fileExistsAtPath(destinationURLForFile.path!){
showFileWithPath(destinationURLForFile.path!)
}
else{
do {
try fileManager.moveItemAtURL(location, toURL: destinationURLForFile)
// show file
showFileWithPath(destinationURLForFile.path!)
}catch{
print("An error occurred while moving file to destination url")
}
}
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?){
downloadTask = nil
if (error != nil) {
print(error?.description)
}else{
print("The task finished transferring data successfully")
}
}
func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
if !session.configuration.identifier!.isEmpty {
}
}
// MARK: UIDocumentInteractionControllerDelegate
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController{
return self.viewController
}
}
| true
|
e678023a590fc434309f38b23c0ed8a1a5659475
|
Swift
|
virajpsimformsolutions/Swifty
|
/Source/UIKit/UICollectionView.swift
|
UTF-8
| 758
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// UICollectionView.swift
// Swifty
//
// Created by Vadym Pavlov on 12.05.17.
// Copyright © 2017 Vadym Pavlov. All rights reserved.
//
import UIKit
public extension UICollectionView {
func itemWidthThatFits(count: CGFloat) -> CGFloat {
let inset = contentInset.left + contentInset.right
let width: CGFloat
if let flow = collectionViewLayout as? UICollectionViewFlowLayout {
let sectionInset = flow.sectionInset.left + flow.sectionInset.right
let spacing = flow.minimumInteritemSpacing * (count - 1)
width = frame.width - inset - sectionInset - spacing
} else {
width = frame.width - inset
}
return floor(width / count)
}
}
| true
|
de1689ba7e2e578d119f9c035c909c33cc534024
|
Swift
|
jennychang-dev/iOS_Swift_1_Playground
|
/W4D1_Playground.playground/Pages/Functions and Closures.xcplaygroundpage/Contents.swift
|
UTF-8
| 6,730
| 4.6875
| 5
|
[] |
no_license
|
//: [Previous](@previous)
/*:
## Functions
A function is a set of statements grouped together to perform a task. Functions can take in zero or many parameters and the function can also return a value or return nothing. Below you can see the different structures of a function of how you can write them.
*/
/*:
- Callout(Structure): This function structure does not include any parameters and does not return anything
- Declare the `func` keyword
- The name of the function `'sayHello'`
- Open and close parentheses
- Open and close braces
*/
func sayHello(){
print("Hello")
}
/*:
- Callout(Structure): This function takes in a single parameter and does not return any values
- Declare the `func` keyword
- The name of the function `'sayHello'`
- **Open and close parentheses with a parameter called 'toPerson' of type `String`**
- Open and close braces
*/
func sayHello(toPerson: String){
print("Hello \(toPerson)")
}
/*:
- Callout(Structure): This function takes in a single parameter and returns a value of type `String`
- Declare the `func` keyword
- The name of the function `'sayHello'`
- Open and close parentheses with a parameter called 'toPerson' of type `String`
- A return value of type `String` represented by the `->`
- Open and close braces
*/
func sayHello(toPerson: String) -> String{
return "Hello \(toPerson)"
}
/*:
- Experiment:
Try calling all of the functions above. They all have the same function name, but the compiler doesn't complain. Can you think of why this might be?
*/
sayHello() // this returns nothing
//sayHello(toPerson: "Jenny") takes in string and returns nothing
//sayHello(toPerson: "Jenny") takes in string and returns a string
/*:
- Experiment:
Try creating your own function that accepts two parameters of any type you choose. Have the function print out the two parameters and test your function.
*/
func iWouldLikeABeer(type: String, quantity: String) {
print("Hi Danny, do I deserve a \(quantity) of \(type) right now? I managed to complete a function")
}
iWouldLikeABeer(type: "lager", quantity: "pint")
/*:
- Callout(Challenge):
Create four separate functions to add, subtract, multiple, and divide with two parameters given to it and returns a number result. Try testing each one afterwards.
*/
func add(first: Float, second: Float) -> Float {
return first + second
}
func subtract(first: Float, second: Float) -> Float {
return first - second
}
func divide(first: Float, second: Float) -> Float {
return first / second
}
func multipy(first: Float, second: Float) -> Float {
return first * second
}
add(first: 2, second: 4)
subtract(first: 40, second: 2)
divide(first: 40, second: 7)
multipy(first: 4, second: 5.6)
/*:
- Callout(Challenge):
Create your own 'reverse' function that takes in an array of Int, reverses the order of the array, and returns the newly reversed array of Int. The array class has its own 'reverse' method, but do not use it for this challenge.
*/
func reverse(array:[Int]) -> [Int] {
var reverse:[Int] = []
for i in 0..<array.count {
reverse.append(array[array.count-1-i])
}
return reverse
}
let moreNumbers = [5,10,15,20,50]
reverse(array: moreNumbers)
/*
Closures are also a set of statements grouped together but the closure can be stored and passed around and executed somewhere else.
- Note:
A closure in Swift is similar to blocks in Objective-C
*/
/*:
For example, the UIViewController has a 'dismiss' method.
`func dismiss(animated flag: Bool, completion: (() -> Void)? = nil)`
The 'completion' part of it is the completion handler which is a closure. It will execute that block of code when the dismiss action has completed.
*/
/*:
- Callout(Structure): This is storing a closure into a variable called 'sayHelloClosure'.
- Start with the open braces
- The first '()' indicates it takes no parameters
- The -> represents what a type it will return
- The second '()' indicates it does not return any value
- The 'in' keyword separates the type declaration from the body
- Close braces
*/
var sayHelloClosure = { () -> () in
print("Hello from closure")
}
/*:
- Callout(Structure): This is storing a closure into a variable called 'sayHelloClosureToPerson'.
- Start with the open braces
- The first '()' indicates it takes one parameter 'name'
- The -> represents what a type it will return
- The second '()' indicates it does not return any value
- The 'in' keyword separates the type declaration from the body
- Close braces
*/
var sayHelloClosureToPerson = { (name: String) -> () in
print("Hello \(name)")
}
/*:
- Callout(Structure): This is storing a closure into a variable called 'sayHelloClosureWithReturn'.
- Start with the open braces
- The first '()' indicates it takes one parameter 'name'
- The -> represents what a type it will return
- The `'String'` after the arrow indicates it returns a `String` type
- The 'in' keyword separates the type declaration from the body
- Close braces
*/
var sayHelloClosureWithReturn = { (name: String) -> String in
return "Hello \(name)"
}
/*:
- Experiment:
Try calling all of the closures above. What do you notice that is different from calling a function?
*/
sayHelloClosure() // we need to call for it to happen
sayHelloClosureToPerson("Jenny")
sayHelloClosureWithReturn("Jenny")
/*:
- Experiment:
Try creating your own closure that accepts two parameters of any type you choose. Have the closure print out the two parameters and test your closure.
*/
var imNotFeelingCreativeRightNow = { (city: String, weather: String) -> () in
print("in \(city) there is a lot of \(weather)")
}
imNotFeelingCreativeRightNow("Vancouver","rain")
/*:
- Experiment:
Declare a variable with an explicit closure type: `(String) -> (String)`. This closure type says it takes one parameter of type String and returns a variable of type String.
*/
var explicitClosureMethod = { (city: String) -> String in
return "in \(city) there are mountains"
}
explicitClosureMethod("Vancouver")
/*:
- Callout(Challenge):
Create a closure with at least two parameters of your choice and decide whether or not it returns anything. Then create a function that takes in your closure as a parameter and one additional parameter of your choice.
*/
import Foundation
var velocity = { (horizontal: Float, vertical: Float) -> Float in
return (pow(horizontal,2) + pow(vertical,2)).squareRoot()
}
//velocity(12,5)
func calcKineticEnergy(velocity: (Float,Float) -> Float, metre:Float) -> Float {
return Float(0.5) * pow(velocity(5,8),2) * metre
}
calcKineticEnergy(velocity: velocity, metre: 7.8)
// we can pass the idea of a closure
| true
|
7f4595fec032ea04e892c96a8abe3509aea379d6
|
Swift
|
jared854/RestaurantOfFate
|
/Restaurant of Fate/TableViewController.swift
|
UTF-8
| 1,500
| 2.75
| 3
|
[] |
no_license
|
//
// TableViewController.swift
// Restaurant of Fate
//
// Created by Christopher Gerencser and Jared Schwartz on 12/13/17.
// Copyright © 2017 Jared Schwartz. All rights reserved.
//
import UIKit
class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(restaurantIndexWithinRadius.count)
return(restaurantIndexWithinRadius.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
row.textLabel?.text = rating[restaurantIndexWithinRadius[indexPath.row]] + ": " + restaurantNames[restaurantIndexWithinRadius[indexPath.row]]
return(row)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
a5ada31bd4d85d37bf335b3d542195e860e8fd57
|
Swift
|
MangDic/TodayMood
|
/Today'sMood/ViewController/ChartViewController.swift
|
UTF-8
| 3,995
| 2.96875
| 3
|
[] |
no_license
|
//
// ChartViewController.swift
// TodaysMood
//
// Created by 이명직 on 2021/08/25.
//
import UIKit
import Charts
class ChartViewController: UIViewController {
@IBOutlet weak var chartContainerView: BarChartView!
var diary = [String:[Diary]]()
var emptyLabel = UILabel()
var moodValues = [String:Double]()
override func viewDidLoad() {
super.viewDidLoad()
chartContainerView.noDataText = "데이터가 없습니다 ㅠㅠ"
chartContainerView.noDataFont = UIFont(name: "THEHappyfruit", size: 24)!
chartContainerView.noDataTextColor = #colorLiteral(red: 0.9891662002, green: 1, blue: 0.8718685508, alpha: 1)
setValues() {
if self.diary.count == 0 {
self.setEmptyLabel()
}
else {
self.customizeChart(data: self.moodValues)
}
}
chartContainerView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
}
@IBAction func didTabCancel(_ sender: Any) {
self.dismiss(animated: true)
}
fileprivate func setEmptyLabel() {
emptyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.chartContainerView.bounds.size.width, height: self.chartContainerView.bounds.size.height))
emptyLabel.textAlignment = NSTextAlignment.center
}
fileprivate func setValues(completion: @escaping () -> Void ) {
if diary != nil {
var happyCnt = 0
var sadCnt = 0
var angryCnt = 0
for key in diary.keys {
for item in diary[key]! {
switch item.mood {
case "happy":
happyCnt += 1
case "sad":
sadCnt += 1
default :
angryCnt += 1
}
}
}
moodValues["신나요"] = Double(happyCnt)
moodValues["슬퍼요"] = Double(sadCnt)
moodValues["화나요"] = Double(angryCnt)
}
completion()
}
//dataPoints: [String], values: [Double]
func customizeChart(data: [String:Double]) {
var index = 0
// 1. Set ChartDataEntry
var dataEntries: [ChartDataEntry] = []
for i in data.keys {
if data[i] == 0 {
continue
}
index += 1
let dataEntry = PieChartDataEntry(value: data[i]!, label: i, data: i as AnyObject)
dataEntries.append(dataEntry)
}
// 2. Set ChartDataSet
let pieChartDataSet = PieChartDataSet(entries: dataEntries, label: nil)
pieChartDataSet.colors = colorsOfCharts(numbersOfColor: index)
pieChartDataSet.entryLabelFont = UIFont(name: "THEHappyfruit", size: 10)
pieChartDataSet.entryLabelColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
pieChartDataSet.selectionShift = CGFloat(10)
// 3. Set ChartData
let pieChartData = PieChartData(dataSet: pieChartDataSet)
let format = NumberFormatter()
format.numberStyle = .none
let formatter = DefaultValueFormatter(formatter: format)
pieChartData.setValueFormatter(formatter)
chartContainerView.data = pieChartData
}
private func colorsOfCharts(numbersOfColor: Int) -> [UIColor] {
var colors: [UIColor] = []
colors.append(#colorLiteral(red: 0.8549019694, green: 0.250980407, blue: 0.4784313738, alpha: 1))
colors.append(#colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1))
colors.append(#colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1))
return colors
}
fileprivate func setContainerView() {
chartContainerView.layer.borderWidth = 1
chartContainerView.layer.borderColor = #colorLiteral(red: 0.4344803691, green: 0.5318876505, blue: 1, alpha: 1)
}
}
| true
|
53262ab0c68117680bf3b4886ad5dd2d7e3d96ff
|
Swift
|
ekurutepe/Iguazu
|
/Sources/Iguazu/AirSpace/AirspaceMapDelegate.swift
|
UTF-8
| 2,473
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// AirspaceMapDelegate.swift
// Iguazu
//
// Created by Engin Kurutepe on 10/12/2016.
// Copyright © 2016 Fifteen Jugglers Software. All rights reserved.
//
#if !os(watchOS)
import MapKit
public class AirspaceMapDelegate: NSObject, MKMapViewDelegate {
private var _airspaceTable = [MKPolygon: Airspace]()
public var airspaceTable: [MKPolygon: Airspace] {
return _airspaceTable
}
public var polygons = [MKPolygon]()
public required init(airspaces: [Airspace]) {
super.init()
polygons = airspaces.map {
let coords = $0.polygonCoordinates
let polygon = MKPolygon(coordinates: coords, count: coords.count)
self._airspaceTable[polygon] = $0
return polygon
}
}
// MARK: MapView Delegate
public func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let polygon = overlay as? MKPolygon {
let airSpace = self.airspaceTable[polygon]
let renderer = MKPolygonRenderer(polygon: polygon)
let airspaceColor = airSpace?.airspaceClass.color ?? .blue
renderer.strokeColor = airspaceColor.withAlphaComponent(0.7)
renderer.fillColor = airspaceColor.withAlphaComponent(0.1)
renderer.lineWidth = 1.0
return renderer
}
return MKOverlayRenderer(overlay: overlay)
}
}
public extension AirspaceClass {
#if os(OSX)
var color: NSColor {
switch self {
case .Danger:
return .black
case .CTR, .GliderProhibited, .Prohibited, .Restricted:
return .red
case .Delta:
return .green
case .Bravo, .Charlie, .RadioMandatoryZone:
return NSColor(red: 0.0, green: 0.6, blue: 1.0, alpha: 1.0)
case .TransponderMandatoryZone:
return .gray
default:
return .purple
}
}
#elseif os(iOS)
var color: UIColor {
switch self {
case .Danger, .GliderProhibited, .Prohibited, .Restricted:
return .red
case .Delta, .CTR, .Bravo, .Charlie, .RadioMandatoryZone:
return UIColor(red: 0.0, green: 0.12, blue: 0.67, alpha: 1.0)
case .TransponderMandatoryZone:
return .darkGray
case .WaveWindow:
return .green
default:
return .purple
}
}
#endif
}
#endif
| true
|
dd88574b3e679d26351d00e3f234e84f662dc43c
|
Swift
|
liushigit/Deferred
|
/Sources/FutureFlatMap.swift
|
UTF-8
| 3,089
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
//
// FutureFlatMap.swift
// Deferred
//
// Created by Zachary Waldowski on 4/2/16.
// Copyright © 2014-2016 Big Nerd Ranch. Licensed under MIT.
//
extension FutureType {
/// Begins another asynchronous operation by passing the deferred value to
/// `requestNextValue` once it becomes determined.
///
/// `flatMap` is similar to `map`, but `transform` returns another
/// `FutureType` instead of an immediate value. Use `flatMap` when you want
/// this future to feed into another asynchronous operation. You might hear
/// this referred to as "chaining" or "binding"; it is the operation of
/// "flattening" a future that would otherwise contain another future.
///
/// - note: It is important to keep in mind the thread safety of the
/// `requestNextValue` closure. Creating a new asynchronous task typically
/// involves stored state. Ensure the `body` is designed for use with the
/// `executor`.
///
/// - parameter executor: Context to execute the transformation on.
/// - parameter requestNextValue: Start a new operation with the future value.
/// - returns: The new deferred value returned by the `transform`.
public func flatMap<NewFuture: FutureType>(upon executor: ExecutorType, _ requestNextValue: Value -> NewFuture) -> Future<NewFuture.Value> {
let d = Deferred<NewFuture.Value>()
upon(executor) {
requestNextValue($0).upon(executor) {
d.fill($0)
}
}
return Future(d)
}
}
import Dispatch
extension FutureType {
/// Begins another asynchronous operation by passing the deferred value to
/// `requestNextValue` once it becomes determined.
///
/// - parameter queue: Dispatch queue for starting the new operation from.
/// - parameter requestNextValue: Start a new operation with the future value.
/// - returns: The new deferred value returned by the `transform`.
/// - seealso: FutureType.flatMap(upon:_:)
public func flatMap<NewFuture: FutureType>(upon queue: dispatch_queue_t, _ requestNextValue: Value -> NewFuture) -> Future<NewFuture.Value> {
let d = Deferred<NewFuture.Value>()
upon(queue) {
requestNextValue($0).upon(queue) {
d.fill($0)
}
}
return Future(d)
}
/// Begins another asynchronous operation with the deferred value once it
/// becomes determined.
///
/// The `requestNextValue` transform is executed on a global queue matching
/// the current quality-of-service value.
///
/// - parameter requestNextValue: Start a new operation with the future value.
/// - returns: The new deferred value returned by the `transform`.
/// - seealso: qos_class_t
/// - seealso: FutureType.flatMap(upon:_:)
public func flatMap<NewFuture: FutureType>(requestNextValue: Value -> NewFuture) -> Future<NewFuture.Value> {
if let value = peek() {
return Future(requestNextValue(value))
}
return flatMap(upon: Self.genericQueue, requestNextValue)
}
}
| true
|
feef6dd70f51cb0d97b071322272a63656d9e38e
|
Swift
|
ram4ik/SwiftUIDragGesture2
|
/SwiftUIDragGesture/ContentView.swift
|
UTF-8
| 731
| 3.03125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// SwiftUIDragGesture
//
// Created by ramil on 26.03.2020.
// Copyright © 2020 com.ri. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State private var isDragging = false
var drag: some Gesture {
DragGesture()
.onChanged { _ in self.isDragging = true }
.onEnded { _ in self.isDragging = false }
}
var body: some View {
Circle()
.fill(isDragging ? Color.red : Color.green)
.animation(.easeInOut(duration: 2))
.frame(width: 200)
.gesture(drag)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
2e3d944f42b73e86637ef46948fa229ebda71d28
|
Swift
|
JakMobius/EasyHTML
|
/EasyHTML/src/preferences/menus/ExpanderMenuPreferencesMenuCell.swift
|
UTF-8
| 2,394
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// ExpanderMenuPreferencesMenuCell.swift
// EasyHTML
//
// Created by Артем on 25/05/2019.
// Copyright © 2019 Артем. All rights reserved.
//
import UIKit
class AlwaysOpaqueView: UIView {
override var backgroundColor: UIColor? {
didSet {
if backgroundColor?.cgColor.alpha == 0 {
backgroundColor = oldValue
}
}
}
}
class ExpanderMenuPreferencesMenuCell: BasicCell {
static var textColor = UIColor.white
var imageContainer = UIImageView()
var imageBackgroundView = AlwaysOpaqueView()
override func standardInitialise() {
imageBackgroundView.translatesAutoresizingMaskIntoConstraints = false
imageContainer.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(imageBackgroundView)
imageBackgroundView.addSubview(imageContainer)
imageBackgroundView.heightAnchor.constraint(equalToConstant: 30).isActive = true
imageBackgroundView.widthAnchor.constraint(equalToConstant: 30).isActive = true
imageBackgroundView.cornerRadius = 5
imageBackgroundView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
imageBackgroundView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10).isActive = true
imageBackgroundView.isOpaque = true
imageContainer.heightAnchor.constraint(equalToConstant: 22).isActive = true
imageContainer.widthAnchor.constraint(equalToConstant: 22).isActive = true
imageContainer.centerXAnchor.constraint(equalTo: imageBackgroundView.centerXAnchor).isActive = true
imageContainer.centerYAnchor.constraint(equalTo: imageBackgroundView.centerYAnchor).isActive = true
imageContainer.contentMode = .scaleAspectFit
imageContainer.tintColor = ExpanderMenuPreferencesMenuCell.textColor
label.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 50).isActive = true
label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
label.heightAnchor.constraint(equalToConstant: 40).isActive = true
label.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -5).isActive = true
label.minimumScaleFactor = 0.8
label.adjustsFontSizeToFitWidth = true
label.font = UIFont.systemFont(ofSize: 14)
}
}
| true
|
f150377c4135117ce3f97bf64bec54f6e0b47b9d
|
Swift
|
maxibystro/CoordinatorDemo
|
/CoordinatorDemo/Login/LoginViewController.swift
|
UTF-8
| 494
| 2.59375
| 3
|
[] |
no_license
|
import UIKit
class LoginViewController: UIViewController {
private let loginModel = LoginModel.instance
@IBOutlet private weak var loginWithNameButton: UIButton!
@IBOutlet private weak var nameTextField: UITextField!
@IBAction func onLoginWithNameTap(_ sender: Any) {
guard let name = nameTextField.text else { return }
loginModel.login(name: name)
}
@IBAction func onLoginAsGuest(_ sender: Any) {
loginModel.login()
}
}
| true
|
4379e52016689c047ab5719e6670e141b1b68a83
|
Swift
|
tansengming/tableSegue
|
/PartyCell.swift
|
UTF-8
| 816
| 2.609375
| 3
|
[] |
no_license
|
//
// PartyCell.swift
// tableSegue
//
// Created by better on 12/27/16.
// Copyright © 2016 sane men. All rights reserved.
//
import UIKit
class PartyCell: UITableViewCell {
@IBOutlet weak var thumbImage: UIImageView!
@IBOutlet weak var videoLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func updateUI(imageURL: String, title: String) {
self.videoLabel.text = title
DispatchQueue.global().async {
let url = URL(string: imageURL)
do {
let data = try Data(contentsOf: url!)
DispatchQueue.global().sync {
self.thumbImage.image = UIImage(data: data)
}
} catch {
}
}
}
}
| true
|
e5c6968f4e4320dc3168c724553daead95d553e0
|
Swift
|
dionyysus/VideoEgitim
|
/10-Sets/10-Sets/ViewController.swift
|
UTF-8
| 3,293
| 3.71875
| 4
|
[] |
no_license
|
//
// ViewController.swift
// 10-Sets
//
// Created by MAC on 21.02.2020.
// Copyright © 2020 cagdaseksi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Sets Boş Oluşturma
var meyveler = Set<String>()
//var meyveler:Set<String> = Set<String>()
// Boş Kontrolü
if meyveler.isEmpty {
print("meyve bulunamadı.")
}
// Sets Eleman Ekleme
meyveler.insert("Elma")
meyveler.insert("Armut")
meyveler.insert("Kayısı")
// Sets Eleman sayısı Bulma
print(meyveler.count)
// Set Eleman silme
meyveler.remove("Elma")
print(meyveler)
// Sets contains true veya false
if meyveler.contains("Elma") {
print("Evet elma var.")
}else {
meyveler.insert("Elma")
}
print(meyveler)
// for döngüsü kullanma
for meyve in meyveler {
print(meyve)
}
// 4 temel işlem var
// 1. intersection -> kesişim
// 2. symmetricDiffirence -> simetrik farkı
// 3. union -> birleşim
// 4. subtracting - farkını almak
// intersection
let oddDigits:Set = [1,3,5,7,9, 100] // tek sayılar kümesi
let evenDigits:Set = [0,2,4,6,8, 100] // çift sayılar kümesi
print(oddDigits.intersection(evenDigits))
// symmetricDiffirence
print(oddDigits.symmetricDifference(evenDigits))
//union
print(oddDigits.union(evenDigits))
// subtracting
print(oddDigits.subtracting(evenDigits))
// Set Membership ve Equality // Kümelerde Üyelik ve eşitlik durumları
// 1. isSubset : bir kümedeki tüm değerlerin bir başka kümede olup olmadığını gösterir.
// 2. isSuperset : kapsayıp kapsamadığını gösterir.
// 3. isDisjoint : iki kümünin ortak elemanları var mı
let houseAnimals: Set = ["🐶", "🐱"] // ev hayvanları
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"] // çiftlik hayvanları
let cityAnimals: Set = ["🐦", "🐭"]
// Örnek 1
// Ev hayvanları çiftlik hayvanlarının bir alt kümesimi?
if houseAnimals.isSubset(of: farmAnimals) {
print("Ev hayvanları, çiftlik hayvanlarının bir alt kümesidir.")
}
// Örnek 2
// Çiftlik hayvanları ev hayvanlarını kapsıyor mu?
if farmAnimals.isSuperset(of: houseAnimals) {
print("Çiftlik hayvanları ev hayvanlarını kapsıyor.")
}
// Örnek 3
// 2 kümenin birbirinden farklı değerleri var mı?
if cityAnimals.isDisjoint(with: houseAnimals) {
print("Ortak elemanları bulunmuyor.")
}
}
}
| true
|
d9a56a12ab70f71e00e53ba57d59bf97e2b3b85e
|
Swift
|
prxthxm09/iOS-Swift-The-Complete-iOS-App-Development-Bootcamp
|
/src/15_h2__AppLifecycle/AppLifecycle/ViewController2.swift
|
UTF-8
| 1,109
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController2.swift
// ViewControllerLifecycle
//
// Milovan Tomašević on 01/10/2020.
// Copyright © 2020 Milovan Tomašević. All rights reserved.
//
import UIKit
class ViewController2: UIViewController {
@IBOutlet weak var label: UILabel!
@IBAction func goBack(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
label.text = "hello"
print("VC2 viewDidLoad Called")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("VC2 viewWillAppear Called")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("VC2 viewDidAppear Called")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("VC2 viewWillDisappear Called")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("VC2 viewDidDisappear Called")
}
}
| true
|
b98fd2dc929eef099bc98800cba6367e6ec6f23a
|
Swift
|
herndonj/Swift_In_Practice
|
/emacs_swift_mode/interactive_command_line.swift
|
UTF-8
| 314
| 3.25
| 3
|
[] |
no_license
|
// Learn how to use swift-mode at: https://www.hiroom2.com/2016/10/31/emacs-swift-mode-package/
// C-c C-c Run Swift in Buffer
// C-c C-r run selection
// q to quit the mode
print("Please enter your name:")
if let name = readLine() {
print("Hello, \(name)!")
}else {
print("Sorry, I didn't get that?")
}
| true
|
3d7d9ee6f3a3aa3a45548f6bcd71322ec5ea34fd
|
Swift
|
pasp94/o_pokedekk
|
/o_pokedekk/Network/Protocols/APIProvider.swift
|
UTF-8
| 1,002
| 2.953125
| 3
|
[] |
no_license
|
//
// APIProvider.swift
// o_pokedekk
//
// Created by Pasquale Spisto on 20/11/20.
//
import Foundation
import UIKit
protocol APIProvider: class {
/// It will use to make dataTasks
var session: URLSession { get }
/// Return a parsed Object for the given type that is conforme to Codable Protocol
/// - Parameters:
/// - `urlString`: the string rappresenting the resource absolute path
func get<T: Codable>(urlString: String?, decodingType: T.Type, completion:@escaping (Result<T, Error>) -> Void)
/// Returns an image for the given url resource
/// - Parameters:
/// - `urlString`: the string rappresenting the resource absolute path
func downloadImage(urlString: String?, completion:@escaping (Result<UIImage, Error>)-> Void)
/// An helper method that check the response status code
/// - Parameters:
/// - `response`: the HTTPURLResponse on which is checked the status code
func validate(_ response: HTTPURLResponse) -> Result<Void, Error>
}
| true
|
357f077972d73507a41fd101bc90b314b60c7e8f
|
Swift
|
kgenoe/refrain-ios
|
/Refrain/Model/BlockingSchedule.swift
|
UTF-8
| 2,195
| 2.78125
| 3
|
[] |
no_license
|
//
// BlockingSchedule.swift
// Refrain
//
// Created by Kyle Genoe on 2018-02-01.
// Copyright © 2018 Kyle. All rights reserved.
//
import Foundation
class BlockingSchedule: NSObject, NSCoding {
var id: String
var startTime: Date
var endTime: Date
var enabled: Bool
var collectionIds: [String]
var createdDate: Date
var updatedDate: Date
init(startTime: Date, endTime: Date, enabled: Bool = true) {
self.id = UUID().uuidString
self.startTime = startTime
self.endTime = endTime
self.enabled = enabled
self.collectionIds = []
let now = Date()
self.createdDate = now
self.updatedDate = now
}
required init?(coder: NSCoder) {
guard let id = coder.decodeObject(forKey: "uuid") as? String,
let startTime = coder.decodeObject(forKey: "startTime") as? Date,
let endTime = coder.decodeObject(forKey: "endTime") as? Date,
let collectionIds = coder.decodeObject(forKey: "collectionIds") as? [String],
let createdDate = coder.decodeObject(forKey: "createdDate") as? Date,
let updatedDate = coder.decodeObject(forKey: "updatedDate") as? Date else {
return nil
}
self.id = id
self.startTime = startTime
self.endTime = endTime
self.enabled = coder.decodeBool(forKey: "enabled")
self.collectionIds = collectionIds
self.createdDate = createdDate
self.updatedDate = updatedDate
}
func encode(with coder: NSCoder) {
coder.encode(id, forKey: "uuid")
coder.encode(startTime, forKey: "startTime")
coder.encode(endTime, forKey: "endTime")
coder.encode(enabled, forKey: "enabled")
coder.encode(collectionIds, forKey: "collectionIds")
coder.encode(createdDate, forKey: "createdDate")
coder.encode(updatedDate, forKey: "updatedDate")
}
func toDictionary() -> [String: Any] {
return [
"id" : id,
"startTime" : startTime.toTimeInteger(),
"stopTime" : endTime.toTimeInteger(),
]
}
}
| true
|
541daef75b9ae84a8d8ec60d0ab5908817af1747
|
Swift
|
SerovAlexander/Who-Wants-to-Be-a-Millionaire
|
/Who Wants to Be a Millionaire?/Controllers/ResultsTableVC.swift
|
UTF-8
| 953
| 2.578125
| 3
|
[] |
no_license
|
//
// ResultsTableVC.swift
// Who Wants to Be a Millionaire?
//
// Created by Aleksandr Serov on 15.04.2020.
// Copyright © 2020 mac. All rights reserved.
//
import UIKit
class ResultsTableVC: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Game.Shared.results.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell", for: indexPath)
let result = Game.Shared.results[indexPath.row]
let date = DateFormatter()
date.dateStyle = .short
cell.textLabel?.text = "Дата: \(date.string(from: result.date)) - \(result.gamePoint)"
return cell
}
}
| true
|
c56c6163773f956c6d42426aad2e312faf566bed
|
Swift
|
apeksha989/Test
|
/The_Travel_App/Model/DataModelItem.swift
|
UTF-8
| 1,088
| 3.03125
| 3
|
[] |
no_license
|
//
// DataModelIten.swift
// Haggle
//
// Created by Anil Kumar on 19/03/19.
// Copyright © 2019 AIT. All rights reserved.
//
import Foundation
struct DataModelItem: Codable{
let alpha2 : String?
let alpha3 : String?
let currencyCode : String?
let id : Int?
let name : String?
let currencyName : String?
enum CodingKeys: String, CodingKey {
case alpha2 = "alpha2"
case alpha3 = "alpha3"
case currencyCode = "currencyCode"
case id = "id"
case name = "name"
case currencyName = "currencyName"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
alpha2 = try values.decodeIfPresent(String.self, forKey: .alpha2)
alpha3 = try values.decodeIfPresent(String.self, forKey: .alpha3)
currencyCode = try values.decodeIfPresent(String.self, forKey: .currencyCode)
id = try values.decodeIfPresent(Int.self, forKey: .id)
name = try values.decodeIfPresent(String.self, forKey: .name)
currencyName = try values.decodeIfPresent(String.self, forKey: .currencyName)
}
}
| true
|
7387b88f0e94587414f5153ce2edbbb5e12b5a8e
|
Swift
|
kiiich/Animations
|
/Animations/Controllers/ViewController.swift
|
UTF-8
| 1,637
| 2.859375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Animations
//
// Created by Николай on 22.09.2021.
//
import Spring
class ViewController: UIViewController {
@IBOutlet weak var mainView: SpringView!
@IBOutlet weak var mainLabel: UILabel!
@IBOutlet weak var mainButton: UIButton!
private var currentIndex = 0
private let animations = Animation.getAnimations(animationCount: 30).shuffled()
private var currentAnimation: Animation {
animations[currentIndex]
}
override func viewDidLoad() {
super.viewDidLoad()
runAnimationSetValues()
}
@IBAction func nextAnimationPressed(_ sender: Any) {
runAnimationSetValues()
}
private func changeIndex() {
currentIndex = (currentIndex == animations.count - 1) ? 0 : currentIndex + 1
}
private func runAnimation() {
mainView.duration = CGFloat(currentAnimation.duration)
mainView.delay = CGFloat(currentAnimation.delay)
mainView.force = CGFloat(currentAnimation.force)
mainView.animation = currentAnimation.preset
mainView.curve = currentAnimation.curve
mainView.animate()
}
private func setLabelTitle() {
mainLabel.text = currentAnimation.description
}
private func setButtonTitle() {
let title = "Next animation: \(currentAnimation.preset)"
mainButton.setTitle(title, for: .normal)
}
private func runAnimationSetValues() {
setLabelTitle()
runAnimation()
changeIndex()
setButtonTitle()
}
}
| true
|
babf405874330dc3ef86b64f3a29fa82beaf713e
|
Swift
|
LucianoPAlmeida/coordinator-ios
|
/Coordinator/Coordinator/Coordinator.swift
|
UTF-8
| 2,070
| 3.015625
| 3
|
[] |
no_license
|
//
// Coordinator.swift
// Coordinator
//
// Created by Luciano Almeida on 18/03/18.
// Copyright © 2018 Luciano Almeida. All rights reserved.
//
import UIKit
protocol Startable {
func start()
}
protocol CoordinatorDelegate: AnyObject {
func coordinatorDidFinish(_ coordinator: Coordinator,
on controller: UIViewController?,
with context: CoordinatorContext?)
}
enum CoordinatorState {
case finished
case cancelled
}
protocol CoordinatorContext {
var state: CoordinatorState { get set }
}
public struct AbstractCoordinatorContext: CoordinatorContext {
var state: CoordinatorState
static var cancelled: CoordinatorContext { return AbstractCoordinatorContext(state: .cancelled) }
static var finished: CoordinatorContext { return AbstractCoordinatorContext(state: .finished) }
}
protocol Coordinator: AnyObject, Startable {
var parentCoordinador: Coordinator? { get set }
var rootViewController: UIViewController! { get set }
var childCoordinators: [Coordinator] { get set }
var delegate: CoordinatorDelegate? { get set }
func addChildCoordinator(_ coordinator: Coordinator)
func removeChildCoordinator(_ coordinator: Coordinator)
func removeFromParent()
func finish(in controller: UIViewController?, with context: CoordinatorContext?)
}
extension Coordinator {
func addChildCoordinator(_ coordinator: Coordinator) {
childCoordinators.append(coordinator)
coordinator.parentCoordinador = self
}
func removeChildCoordinator(_ coordinator: Coordinator) {
childCoordinators = childCoordinators.filter({ $0 !== coordinator })
}
func removeFromParent() {
parentCoordinador?.removeChildCoordinator(self)
parentCoordinador = nil
}
func finish(in controller: UIViewController?, with context: CoordinatorContext?) {
removeFromParent()
childCoordinators.removeAll()
delegate?.coordinatorDidFinish(self, on: controller, with: context)
}
}
| true
|
98ad74c1e40ed084bc2b579f9b7a4f527b940486
|
Swift
|
dinneo/Swift_Coding_Practice_playground
|
/Swift Coding Practice.playground/Sources/SimulatedAnnealing3D.swift
|
UTF-8
| 3,746
| 3.734375
| 4
|
[] |
no_license
|
import Foundation
public struct Point3D {
private var x: Double
private var y: Double
private var z: Double
public var point: (x: Double, y: Double, z: Double) {
get {
return (x,y,z)
}
set {
x = newValue.x
y = newValue.y
z = newValue.z
}
}
public init(point: (x: Double, y: Double, z: Double)) {
self.x = point.x
self.y = point.y
self.z = point.z
}
public init() {
x = 0.0
y = 0.0
z = 0.0
}
public init(_ x: Double, _ y: Double, _ z: Double) {
self.x = x
self.y = y
self.z = z
}
public var description: String {
return "( \(x), \(y), \(z) )"
}
}
public struct Function3D {
private var f: (Point3D) -> Double
private var p: Point3D
private var energy: Double {
return f(p)
}
public init(equation: (Point3D) -> Double, point: Point3D) {
self.f = equation
self.p = point
}
public mutating func update(newPoint: Point3D) {
p = newPoint
}
public func getPoint() -> Point3D{
return p
}
public func getEnergy(point: Point3D) -> Double {
return f(point)
}
public func neighbor(step: Double) -> Point3D {
var neighbors = [Point3D]()
for i in -1...1 {
for j in -1...1 {
for k in -1...1 {
let newPoint = Point3D(p.x + step * i.toDouble(), p.y + step * j.toDouble(), p.z + step * k.toDouble())
if i != 0 && j != 0 && k != 0 { neighbors.append(newPoint) }
}
}
}
let deltas = neighbors.map{ getEnergy($0) - energy }
for i in 0..<neighbors.count {
if deltas[i] == deltas.minElement() {
return neighbors[i]
}
}
return p
}
public var description: String {
return "f\(p.description) = \(energy)"
}
}
public struct SimulatedAnnealing3D {
private var function3D: Function3D
private var temp: Double = 100.0
private var coolingRate = 0.003
private var step = 0.1
private var bestSolution: Point3D?
private var randomThreshold: Bool = true
private var fixedThreshold = 0.5
public init(equation: (Point3D) -> Double, initial: Point3D, temp: Double = 100.0, coolingRate: Double = 0.003, step: Double = 0.1, randomThreshold: Bool = true, fixedThreshold: Double = 0.5) {
self.function3D = Function3D(equation: equation, point: initial)
// self.initialSolution = initial
self.temp = temp
self.coolingRate = coolingRate
self.step = step
self.randomThreshold = randomThreshold
self.fixedThreshold = fixedThreshold
self.bestSolution = initial
}
public func acceptanceProbability(energy: Double, newEnergy: Double, temperature: Double) -> Double {
if (newEnergy < energy) {
return 1.0
}
return exp((energy - newEnergy).toDouble() / temperature)
}
public mutating func run() {
var t = temp
let coolingScale = 1 - coolingRate
var currentSolution: Point3D {
get {
return function3D.p
}
set {
function3D.update(newValue)
}
}
print("Initial solution energy: " + function3D.description)
while (t > 1) {
let currentEnergy = function3D.getEnergy(currentSolution)
let neighbor = function3D.neighbor(step)
let neighbourEnergy = function3D.getEnergy(neighbor)
let bestEnergy = function3D.getEnergy(bestSolution!)
let threshold: Double = randomThreshold ? arc4random().toDouble() / UInt32.max.toDouble() : 0.5
if (acceptanceProbability(currentEnergy, newEnergy: neighbourEnergy, temperature: t) > threshold) {
currentSolution = neighbor
}
if (neighbourEnergy < bestEnergy) {
bestSolution = neighbor
}
t *= coolingScale
}
function3D.update(bestSolution!)
print("Final solution energy: \(function3D.getEnergy(bestSolution!))")
print("Best Solution: " + bestSolution!.description)
}
public var description: String {
return function3D.description + "current @\(function3D.p.description)" + "best sol: \(bestSolution?.description)"
}
}
| true
|
602dba782d9a23aeb2deb6def26439d2b2e674de
|
Swift
|
peihsendoyle/Swift-2-design-pattern
|
/TheFactoryMethodPattern.playground/Contents.swift
|
UTF-8
| 3,077
| 4.25
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
import Foundation
// Define what a card is
protocol Card {
var name: String? { get set }
var attack: Int? { get set }
var mana: Int? { get set }
var defense: Int? { get set }
func clone() -> Card
func toString() -> String
}
// Abstract Card - implements the signature and some properties
class AbstractCard: NSObject, Card {
private var _name: String?
private var _attack: Int?
private var _mana: Int?
private var _defense: Int?
init(name: String?, attack: Int?, mana: Int?, defense: Int?) {
self._name = name
self._attack = attack
self._mana = mana
self._defense = defense
}
override init() {
super.init()
}
// property name
var name: String? {
get { return _name }
set { _name = newValue }
}
// property attack
var attack: Int? {
get { return _attack }
set { _attack = newValue }
}
// property mana
var mana: Int? {
get { return _mana }
set { _mana = newValue }
}
// property defense
var defense: Int? {
get { return _defense }
set { _defense = newValue }
}
func clone() -> Card {
return AbstractCard(name: self.name, attack: self.attack, mana: self.mana, defense: self.defense)
}
func toString() -> String {
return ("\(self.name, self.mana, self.attack, self.defense)")
}
}
enum CardType {
case CopyCat, RaidRaider
}
// Our Factory class
// Depending what we need, this class return an instance of the appropriate object.
class CardFactory {
class func createCard(cardType: CardType) -> Card? {
switch cardType {
case .CopyCat:
return CopyCat()
case .RaidRaider:
return RaidRaider()
default:
return nil
}
}
}
// Concrete card "Raid Raider"
// This is full definition of the Raid Raider Card
class RaidRaider: AbstractCard {
override init() {
super.init()
self._mana = 3
self._attack = 2
self._defense = 2
self._name = "Raid Raider"
}
}
// Concrete card "Copy Cat"
// This is full definition of the Copy Cat Card
class CopyCat: AbstractCard {
override init() {
super.init()
self._mana = 5
self._attack = 3
self._defense = 3
self._name = "Copy Cat"
}
}
// Simulate our client
var c = CardFactory.createCard(.CopyCat)
let string = c?.toString()
print(string)
let d = c?.clone()
print(d?.toString())
| true
|
d7988d3fefe748b9e4f1e843c4e939d859c349b2
|
Swift
|
sokonishi/SwiftUIImageCreator
|
/SwiftUIImageCreator/Model/Database.swift
|
UTF-8
| 3,565
| 3.09375
| 3
|
[] |
no_license
|
//
// Database.swift
// SwiftUIImageCreator
//
// Created by 小西壮 on 2021/03/19.
//
import Foundation
import RealmSwift
class ReportDatebase:Object{
@objc dynamic var id = Int()
@objc dynamic var placeName = String()
@objc dynamic var purposeText = String()
@objc dynamic var todoText = String()
@objc dynamic var detailText = String()
@objc dynamic var date = String()
var database = [NSDictionary]()
//新規登録
func create(placeName: String,purposeText: String,todoText: String,detailText:String) {
//データベース接続
let realm = try! Realm()
//データの書き込み
try! realm.write{
let reportDatabase = ReportDatebase()
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
reportDatabase.id = (realm.objects(ReportDatebase.self).max(ofProperty: "id") as Int? ?? 0)+1
reportDatabase.placeName = placeName
reportDatabase.purposeText = purposeText
reportDatabase.todoText = todoText
reportDatabase.detailText = detailText
reportDatabase.date = formatter.string(from: now as Date)
realm.add(reportDatabase)
}
}
//取得
func getAll() {
let realm = try! Realm()
//データベースから情報取得
let database = realm.objects(ReportDatebase.self)
//配列に入れる
for value in database {
let data = ["id": value.id, "placeName": value.placeName,"purposeText":value.purposeText,"todoText":value.todoText,"detailText":value.detailText, "date": value.date] as NSDictionary
self.database.append(data)
}
print(database)
}
//削除
func deleteAll(){
let realm = try! Realm()
let database = realm.objects(ReportDatebase.self)
try! realm.write{
realm.delete(database)
}
}
//特定のデータのみ取得
//-> Todoみたいな戻り値がある時は受け取る側でletで定義してあげる
func getDate(id: Int) -> ReportDatebase {
//DB接続
let realm = try! Realm()
//データを取得
let database = realm.objects(ReportDatebase.self).filter("id = \(id)").first
print(database)
//取得したデータを返す
return database!
}
//更新
func update(id: Int,placeName: String,purposeText: String,todoText: String,detailText:String) {
let realm = try! Realm()
let database = realm.objects(ReportDatebase.self).filter("id = \(id)").first
//更新する時
try! realm.write {
database!.placeName = placeName
database!.purposeText = purposeText
database!.todoText = todoText
database!.detailText = detailText
}
}
//削除
func delete(id: Int) {
//DBに接続
let realm = try! Realm()
//削除するデータを取得
//.filter("id = 1").firstで条件を絞る.firstは1こ目を取ってくる、実際は無くていい
let databaseElement = realm.objects(ReportDatebase.self).filter("id = \(id)").first
//取得したデータを削除する
try! realm.write {
realm.delete(databaseElement!)
}
}
}
| true
|
055468d527ba3e8496f4d4fe266f96deda6c2c05
|
Swift
|
yokoboko/TheMovieFinder-iOS
|
/MovieFinder/GenrePickerVC.swift
|
UTF-8
| 2,877
| 2.828125
| 3
|
[] |
no_license
|
//
// GenrePickerVC.swift
// MovieFinder
//
// Created by Yosif Iliev on 5.09.19.
// Copyright © 2019 Yosif Iliev. All rights reserved.
//
import UIKit
class GenrePickerVC: UIViewController {
private var genreType: GenreType = .movie
private var completion: ((_ selected: [Genre]) -> Void)
private var selectedGenres = [Int: Genre]()
private var genres: [Genre] = []
private let genreView = GenrePickerView()
private var didChangeSelection = false
init(genreType: GenreType, completion: @escaping (_ selected: [Genre]) -> Void, selected: [Genre]?) {
self.genreType = genreType
self.completion = completion
if let selected = selected {
for genre in selected {
selectedGenres[genre.id] = genre
}
}
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func loadView() {
view = genreView
}
override func viewDidLoad() {
super.viewDidLoad()
genres = genreType == .movie ? GenresData.getMovieGenres() : GenresData.getTVShowGenres()
let tableView = genreView.tableView!
tableView.register(GenreCell.self, forCellReuseIdentifier: GenreCell.reuseIdentifier)
tableView.dataSource = self
tableView.delegate = self
genreView.doneBtn.addTarget(self, action: #selector(doneAction(_:)), for: .touchUpInside)
}
@objc func doneAction(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
if didChangeSelection {
var selected = [Genre]()
for genre in selectedGenres.values {
selected.append(genre)
}
completion(selected)
}
}
}
// MARK: - TableView DataSource & Delegate
extension GenrePickerVC: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let genre = genres[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: GenreCell.reuseIdentifier, for: indexPath) as! GenreCell
cell.set(name: genre.name, selected: selectedGenres[genre.id] != nil)
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return genres.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
didChangeSelection = true
let genre = genres[indexPath.row]
if let _ = selectedGenres[genre.id] {
selectedGenres[genre.id] = nil
} else {
selectedGenres[genre.id] = genre
}
tableView.reloadRows(at: [indexPath], with: .fade)
}
}
| true
|
89be548a856a29cef7a104f782f285d4318857a2
|
Swift
|
boogoogle/ChatWithSwiftUI
|
/SwiftUIBilibili/Home.swift
|
UTF-8
| 2,850
| 2.578125
| 3
|
[] |
no_license
|
//
// Home.swift
// Ipadyou
//
// Created by boo on 5/11/20.
// Copyright © 2020 boo. All rights reserved.
//
import SwiftUI
import LeanCloud
struct Home: View {
@State var show = false // 当前组件的状态
@State var showProfile = false // 是否显示DanceGround
@EnvironmentObject var globalData: GlobalData
var body: some View {
NavigationView{
ZStack() {
VStack {
DanceGround()
.background(Color(UIColor(named: "BgColor")!))
.animation(.spring())
.environmentObject(globalData)
}
}
.navigationBarTitle("广场", displayMode: .inline)
.navigationBarItems(
leading: MenuRight()
)
}
}
}
struct Home_Previews: PreviewProvider {
static var previews: some View {
Home().environmentObject(GlobalData())
}
}
struct Menu: Identifiable {
var id = UUID()
var title: String
var icon: String
}
struct CircleButton: View {
var icon = ""
var body: some View {
HStack {
Image(systemName: icon)
.foregroundColor(.black)
}
.frame(width: 40, height: 40)
.background(Color.white)
.cornerRadius(20)
.shadow(radius: 10, x: 0, y: 10)
}
}
struct MenuRight: View {
@State var show: Bool = false
@EnvironmentObject var globalData: GlobalData
let lc_user_email: String = LCApplication.default.currentUser?.email!.rawValue as? String ?? "No Email"
var body: some View {
VStack{
HStack(alignment: .center) {
if globalData.isLogged {
Button(action: {
self.show.toggle()
}){
// CircleButton(icon: "person.crop.circle")
Image(systemName: "person.crop.circle")
}
Text(lc_user_email)
} else {
Button(action: {self.globalData.showLogin = true}){
Image(systemName: "person.crop.circle.badge.exclam")
}
Text("未登录").foregroundColor(Color.red)
}
}
Spacer()
.frame(minWidth:0,maxHeight: .infinity)
}.actionSheet(isPresented: $show){
ActionSheet(title:Text("操作"),buttons: [
.destructive(Text("退出登录")){
LCUser.logOut()
UserDefaults.standard.set(false, forKey: "isLogged")
self.globalData.isLogged = false
self.show = false
},
.cancel()
])
}
}
}
| true
|
12029fd62c210e357759d8ed8ae1915a377a5ed1
|
Swift
|
urjhams/Rk9PTE9HUkFQSFlURVNU
|
/SwiftUI/AssignmentSwiftUI/AssignmentSwiftUIApp.swift
|
UTF-8
| 1,047
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// AssignmentSwiftUIApp.swift
// AssignmentSwiftUI
//
// Created by Quân Đinh on 09.11.20.
//
import SwiftUI
@main
struct AssignmentSwiftUIApp: App {
var body: some Scene {
WindowGroup {
CityListView()
.onAppear(perform: UIApplication.shared.addTapGestureRecognizer)
}
}
}
extension UIApplication: UIGestureRecognizerDelegate {
public func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
) -> Bool {
return true
}
func addTapGestureRecognizer() {
guard let window = windows.first else { return }
let tapGesture = UITapGestureRecognizer(target: window,
action: #selector(UIView.endEditing))
tapGesture.requiresExclusiveTouchType = false
tapGesture.cancelsTouchesInView = false
tapGesture.delegate = self
window.addGestureRecognizer(tapGesture)
}
}
| true
|
8148e2b01de783b6637630e8b457c3a80d8f9435
|
Swift
|
designerGenes/RainCaster_ios
|
/RainCaster/CellData.swift
|
UTF-8
| 1,008
| 3.078125
| 3
|
[] |
no_license
|
//
// CellData.swift
// RainCaster
//
// Created by Jaden Nation on 5/1/17.
// Copyright © 2017 Jaden Nation. All rights reserved.
//
import Foundation
import UIKit
enum CellDataType: String {
case ambientTrack, alert
}
protocol AdoptiveCell {
func adopt(data: CellData)
}
class CellData: NSObject {
var title: String?
var cellDataType: CellDataType?
var assocColor: UIColor?
func asCell() -> UICollectionViewCell {
if let cellDataType = cellDataType {
switch cellDataType {
case .ambientTrack:
if let ambientTrackCell = Bundle.main.loadNibNamed("AmbientTrackCollectionViewCell", owner: nil, options: nil)?.first as? AmbientTrackCollectionViewCell {
ambientTrackCell.adopt(data: self)
return ambientTrackCell
}
case .alert:
break
}
}
return UICollectionViewCell()
}
class func alertCell(withTitle title: String, color: UIColor?) -> CellData {
let out = CellData()
out.cellDataType = .alert
out.title = title
out.assocColor = color
return out
}
}
| true
|
6ce9ac23534d6fe777a76a1779abf0fbea2358df
|
Swift
|
alyEssam/onTheMap
|
/onTheMap/Network/Udacity Responses/currentUserResponse.swift
|
UTF-8
| 434
| 2.75
| 3
|
[] |
no_license
|
//
// currentUserResponse.swift
// onTheMap
//
// Created by Aly Essam on 9/11/19.
// Copyright © 2019 Aly Essam. All rights reserved.
//
import Foundation
struct currentUserResponse: Codable{
var lastName: String?
var firstName: String?
var nickName:String?
enum CodingKeys: String, CodingKey{
case lastName = "last_name"
case firstName = "first_name"
case nickName = "nickname"
}
}
| true
|
a578dff2462f8ff363e9954bb9f1205b12556d6f
|
Swift
|
jatinverma007/Circular-Animation
|
/CircularAnimation/Extension/UIColor+Extension.swift
|
UTF-8
| 338
| 2.609375
| 3
|
[] |
no_license
|
//
// UIColor+Extension.swift
// CircularAnimation
//
// Created by jatin verma on 07/05/21.
//
import Foundation
import UIKit
extension UIColor {
static func random() -> UIColor {
return UIColor(
red: .random(),
green: .random(),
blue: .random(),
alpha: 1.0
)
}
}
| true
|
8d866fa17a309073d24eac6ffc30c9da9df1b0f1
|
Swift
|
blkbrds/intern16_final_project_TrungLeD
|
/FinalProject/Library/Ext/ArrayExt.swift
|
UTF-8
| 359
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// ArrayExt.swift
// FinalProject
//
// Created by MBA0283F on 5/25/20.
// Copyright © 2020 Asian Tech Co., Ltd. All rights reserved.
//
import Foundation
extension Array {
public subscript(safeIndex index: Int) -> Element? {
guard index >= 0, index < endIndex else {
return nil
}
return self[index]
}
}
| true
|
87b267fa1c32c9e7c463cfd046b2ea967ae643a0
|
Swift
|
RoyalIcing/Chassis
|
/Chassis/ExampleContent.swift
|
UTF-8
| 1,291
| 2.9375
| 3
|
[] |
no_license
|
//
// ExampleContent.swift
// Chassis
//
// Created by Patrick Smith on 14/07/2015.
// Copyright (c) 2015 Burnt Caramel. All rights reserved.
//
import Foundation
let exampleStateSpec = { () -> StateSpec in
var spec = StateSpec()
spec.keys = [
AnyPropertyKey(identifier: "flag", kind: .boolean),
AnyPropertyKey(identifier: "dimension", kind: .dimension),
AnyPropertyKey(identifier: "name", kind: .text),
AnyPropertyKey(identifier: "drink", kind: .text)
]
return spec
}()
let exampleStateChoice1 = { () -> StateChoice in
let stateChoice = StateChoice(identifier: "Example 1", spec: exampleStateSpec, baseChoice: nil)
stateChoice.state.properties[AnyPropertyKey(identifier: "name", kind: .text)] = PropertyValue.text("John Doe")
return stateChoice
}()
let exampleStateChoice2 = { () -> StateChoice in
let stateChoice = StateChoice(identifier: "Example 2", spec: exampleStateSpec, baseChoice: exampleStateChoice1)
stateChoice.state.properties[AnyPropertyKey(identifier: "flag", kind: .boolean)] = PropertyValue.boolean(true)
stateChoice.state.properties[AnyPropertyKey(identifier: "dimension", kind: .dimension)] = PropertyValue.dimensionOf(5.4)
stateChoice.state.properties[AnyPropertyKey(identifier: "drink", kind: .text)] = PropertyValue.text("Water")
return stateChoice
}()
| true
|
0b3d2fafa1680c4eac9a59fdeaa5f78687a9dbe6
|
Swift
|
EricADockery/Pokemon
|
/MyDex/UI/AllPokemon/PokemonCollectionCell.swift
|
UTF-8
| 838
| 2.8125
| 3
|
[] |
no_license
|
//
// PokemonCollectionCell.swift
// MyDex
//
// Created by Eric Dockery on 9/8/20.
// Copyright © 2020 Eric Dockery. All rights reserved.
//
import UIKit
class PokemonCollectionCell: BaseReuseCollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var pokemonName: UILabel!
var pokemon: PokemonCharacter?
func update(with pokemon: PokemonCharacter) {
self.pokemon = pokemon
pokemonName.text = pokemon.name
if let spriteLocation = pokemon.sprites.frontDefault ?? pokemon.sprites.frontShiny,
let url = URL(string: spriteLocation)
{
imageView.loadImage(at: url)
}
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
imageView.cancelImageLoad()
}
}
| true
|
f2da78d21b6ed4c6baf3458b3cfcc06ead473dd5
|
Swift
|
MarioArmini/ADA-VenetianWars
|
/PlaygroundNumber2.playground/Contents.swift
|
UTF-8
| 8,700
| 2.703125
| 3
|
[] |
no_license
|
import SpriteKit
import GameplayKit
import PlaygroundSupport
import CoreMotion
let fontUrl = Bundle.main.url(forResource: "myFont", withExtension: "ttf")
CTFontManagerRegisterFontsForURL(fontUrl! as CFURL, CTFontManagerScope.process, nil)
let font = UIFont(name: "PressStart2P-Regular", size: 13)
class GameScene: SKScene, SKPhysicsContactDelegate {
let scoreToWin = 60
var wallNode : SKSpriteNode!
var spritzNode : SKSpriteNode!
var scoreLabel : SKLabelNode!
var score : Int = 0 {
didSet { // Computed property so that it refresh scoreLabel every time this property is updated
scoreLabel.text = "Score:\(score)"
}
}
var gameTimer : Timer!
var inGameTimer: Timer!
var seconds = 20
var timeLabel : SKLabelNode!
var backgroundMusic: SKAudioNode!
var resultLabel : SKLabelNode!
var possibleIngredients = ["ice", "prosecco", "redPotion"]
let ingredientCategory : UInt32 = 0x1 << 1 // 2
let spritzCategory : UInt32 = 0x1 << 0 // 1
override func didMove(to view: SKView) {
self.size = CGSize(width: 375, height: 667)
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
// Starfield node
wallNode = SKSpriteNode(imageNamed: "gameBackground")
wallNode.position = CGPoint(x: wallNode.frame.width / 2, y: wallNode.frame.height / 2) // Make it start from the upper left corner on an iPhone 8 Plus
self.addChild(wallNode)
wallNode.zPosition = -1 // Starfield stays on the back of other nodes
// Player node
spritzNode = SKSpriteNode(imageNamed: "SpritzGood")
spritzNode.position = CGPoint(x: self.frame.size.width / 2, y: 60)
spritzNode.size = CGSize(width: 110, height: 120)
spritzNode.physicsBody = SKPhysicsBody(rectangleOf: spritzNode.size)
spritzNode.physicsBody?.restitution = 0.0
spritzNode.physicsBody?.isDynamic = false
spritzNode.physicsBody?.categoryBitMask = spritzCategory
spritzNode.physicsBody?.contactTestBitMask = ingredientCategory
self.addChild(spritzNode)
// Physics world property - no gravity and initialize contactDelegate for collision detection
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0) // No gravity pulling us down or horizontally
self.physicsWorld.contactDelegate = self // Allow us to implement contact between nodes
// Score label node
scoreLabel = SKLabelNode(text: "Score: 0")
scoreLabel.position = CGPoint(x: 100, y: self.frame.size.height - 60) // Upper left corner
scoreLabel.fontName = "PressStart2P-Regular"
scoreLabel.fontSize = 20
score = 0
self.addChild(scoreLabel)
// Time label node
timeLabel = SKLabelNode(text: "Time: \(seconds)")
timeLabel.position = CGPoint(x: 270, y: self.frame.size.height - 60) // Upper left corner
timeLabel.fontName = "PressStart2P-Regular"
timeLabel.fontSize = 20
self.addChild(timeLabel)
// Setting background sound
if let musicURL = Bundle.main.url(forResource: "gameSong", withExtension: "mp3") {
backgroundMusic = SKAudioNode(url: musicURL)
self.addChild(backgroundMusic)
}
//Setting In game Timer
inGameTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)
// Setting gameTimer
gameTimer = Timer.scheduledTimer(timeInterval: 1.3, target: self, selector: #selector(addIngredient), userInfo: nil, repeats: true)
// Allow user to move the player
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(moveSpritz))
self.view?.addGestureRecognizer(panGestureRecognizer)
}
@objc func moveSpritz(_ recognizer: UIPanGestureRecognizer) {
let lastPosition = recognizer.location(in: self.view)
let moveAction = SKAction.move(to: CGPoint(x: lastPosition.x, y: spritzNode.position.y), duration: 0.01)
spritzNode.run(moveAction)
}
@objc func addIngredient() {
possibleIngredients = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: possibleIngredients) as! [String]
let ingredient = SKSpriteNode(imageNamed: possibleIngredients[0])
ingredient.size = CGSize(width: 50, height: 50)
let randomIngredientPosition = GKRandomDistribution(lowestValue: 0, highestValue: 414)
let position = CGFloat(randomIngredientPosition.nextInt())
// Set position and property on physics body
ingredient.position = CGPoint(x: position, y: self.frame.size.height + ingredient.size.height)
ingredient.physicsBody = SKPhysicsBody(rectangleOf: ingredient.size)
ingredient.physicsBody?.isDynamic = true
ingredient.physicsBody?.restitution = 0.0
ingredient.physicsBody?.categoryBitMask = ingredientCategory
ingredient.physicsBody?.contactTestBitMask = spritzCategory
ingredient.physicsBody?.usesPreciseCollisionDetection = true
ingredient.physicsBody?.collisionBitMask = 0
self.addChild(ingredient)
let animationDuration : TimeInterval = 6
// Create a series of SKActiona nd execute them
var actionArray = [SKAction]()
// Move the alien previously generated from up to down
actionArray.append(SKAction.move(to: CGPoint(x: position, y: -ingredient.size.height), duration: animationDuration))
// Remove the alien from parent when done
actionArray.append(SKAction.removeFromParent())
ingredient.run(SKAction.sequence(actionArray))
}
func didBegin(_ contact: SKPhysicsContact) {
var firstBody : SKPhysicsBody
var secondBody : SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if (firstBody.categoryBitMask & spritzCategory) != 0 && (secondBody.categoryBitMask & ingredientCategory) != 0 {
ingredientCollide(spritzNode: firstBody.node as! SKSpriteNode, ingredientNode: secondBody.node as! SKSpriteNode)
}
}
func ingredientCollide(spritzNode : SKSpriteNode, ingredientNode : SKSpriteNode) {
ingredientNode.removeFromParent()
score += 5
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
@objc func updateTimer() {
if (seconds <= 1) {
// Invalidate timers - no more ingredients spawned
gameTimer.invalidate()
inGameTimer.invalidate()
backgroundMusic.run(SKAction.removeFromParent())
self.endGame()
}
seconds -= 1
timeLabel.text = "Time:\(seconds)"
}
func endGame() {
// TODO: Move score label in center
var arrayActions = [SKAction]()
arrayActions.append(SKAction.run {
self.timeLabel.run(SKAction.fadeOut(withDuration: 2))
})
// TODO: Add a label that says you win or not
timeLabel.run(SKAction.sequence(arrayActions))
arrayActions = [SKAction]()
arrayActions.append(SKAction.run {
if let view = self.view {
self.scoreLabel.run(SKAction.move(to: CGPoint(x: view.center.x - 20, y: view.center.y), duration: 2))
self.scoreLabel.run(SKAction.scale(by: 1.4, duration: 2))
}
})
scoreLabel.run(SKAction.sequence(arrayActions)) {
let resultText = self.score >= self.scoreToWin ? " YOU WIN" : "YOU LOSE"
self.resultLabel = SKLabelNode(text: resultText)
self.resultLabel.fontName = "PressStart2P-Regular"
self.resultLabel.fontSize = 30
self.resultLabel.position = CGPoint(x: self.anchorPoint.x + 178, y: self.anchorPoint.y + 270)
self.addChild(self.resultLabel)
}
}
}
class ViewController : UIViewController {
override func loadView() {
let view = SKView()
view.presentScene(GameScene())
self.view = view
}
}
PlaygroundPage.current.liveView = ViewController()
| true
|
db17b183f825d96445f7b4bd6d1d2071ddda5f2f
|
Swift
|
zzheads/AlarTest
|
/AlarTest/UILayer/ScreenFactory.swift
|
UTF-8
| 1,586
| 2.6875
| 3
|
[] |
no_license
|
//
// ScreenFactory.swift
// AlarTest
//
// Created by Алексей Папин on 01.10.2020.
//
import UIKit
// MARK: - ScreenFactory
class ScreenFactory {
private struct Constants {
static let barTintColor: UIColor = .lightGray
}
static let shared: ScreenFactory = .init()
private init() {
let states: [UIControl.State] = [.normal, .highlighted, .selected]
states.forEach({ UIBarButtonItem.appearance().setTitleTextAttributes([.font: UIFont.systemFont(ofSize: 13, weight: .regular), .foregroundColor: Constants.barTintColor], for: $0) })
}
func mainScreen() -> UINavigationController {
let controller = UINavigationController(rootViewController: loginViewController())
controller.navigationBar.barStyle = .black
controller.navigationBar.barTintColor = Color.primary
controller.navigationBar.isTranslucent = true
controller.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 15, weight: .medium)]
controller.navigationBar.tintColor = Constants.barTintColor
return controller
}
func loginViewController() -> LoginViewController {
return LoginViewController(viewModel: LoginViewModel())
}
func pointsViewController(code: String) -> PointsViewController {
return PointsViewController(viewModel: PointsViewModel(code: code))
}
func pointViewController(point: Point) -> PointViewController {
return PointViewController(viewModel: PointViewModel(point: point))
}
}
| true
|
d7d614609526710c6b21e73549b16ee63a18e02c
|
Swift
|
charlesmartinreed/Seafood
|
/Seafood/ViewController.swift
|
UTF-8
| 3,725
| 3.140625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Seafood
//
// Created by Charles Martin Reed on 8/9/18.
// Copyright © 2018 Charles Martin Reed. All rights reserved.
//
import UIKit
import CoreML
import Vision
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
//create image picker object
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
//setting current View Controller as delegate for the imagePicker object
imagePicker.delegate = self
//allows user to take an image using the device camera
imagePicker.sourceType = .photoLibrary
//imagePicker.sourceType = .photoLibrary
//editing currently not allowed, could be allowed to control how much of an image the model uses to determine the nature of the taken image
imagePicker.allowsEditing = false
}
//tells the delegate the user has finished picking an image
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//check that the image has chosen an image
if let userPickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
//the original type from the info dictionary is Any?, so we need to downcast it
imageView.image = userPickedImage
//convert UI image to Core Image image in order to get interpretation fro it
//if unable to convert, trigger fatal error
//guard seems to be the new do-try-catch
guard let ciimage = CIImage(image: userPickedImage) else {
fatalError("Could not convert UIimage to CIImage")
}
//call our detect function to make the request to our Inception v3 model for classification of the passed image
detect(image: ciimage)
}
imagePicker.dismiss(animated: true, completion: nil)
}
func detect(image: CIImage) {
//use the Inception v3 model
//if can't load the model, present fatal error
guard let model = try? VNCoreMLModel(for: Inceptionv3().model) else {
fatalError("Loading CoreML Model failed")
}
let request = VNCoreMLRequest(model: model) { (request, error) in
//process the results of the result
guard let results = request.results as? [VNClassificationObservation] else {
fatalError("Model failed to process image")
}
//check the first result classification, check the identifier and see whether or not the predication is of a "hotdog".
if let firstResult = results.first {
if firstResult.identifier.contains("hotdog") {
self.navigationItem.title = "Hotdog!"
} else {
self.navigationItem.title = "Not hotdog! :("
}
}
}
//perform the request by creating handler to specify the image we want to classifiy
let handler = VNImageRequestHandler(ciImage: image)
do {
try handler.perform([request])
} catch {
print(error)
}
}
@IBAction func barButtonClicked(_ sender: UIBarButtonItem) {
//present the
present(imagePicker, animated: true, completion: nil)
}
}
| true
|
befdc20a40f7d1263dda2b57952c9868ca12a6a2
|
Swift
|
elegion/ios-Flamingo
|
/Framework/FlamingoTests/ValidationTests.swift
|
UTF-8
| 4,163
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// FlamingoTests.swift
// FlamingoTests
//
// Created by Nikolay Ischuk on 25.09.17.
// Copyright © 2017 ELN. All rights reserved.
//
import XCTest
@testable import Flamingo
class RealFailedTestRequest: NetworkRequest {
var URL: URLConvertible {
return "v2/59c956433f0000910183f797"
}
var method: HTTPMethod {
return .put
}
var parameters: [String: Any]? {
return ["some_param": 12]
}
var parametersEncoder: ParametersEncoder {
return JSONParametersEncoder()
}
typealias ResponseSerializer = StringResponseSerializer
var responseSerializer: ResponseSerializer {
return ResponseSerializer()
}
}
class ValidationTests: XCTestCase {
var client: NetworkClient!
override func setUp() {
super.setUp()
let configuration = NetworkDefaultConfiguration(baseURL: "http://www.mocky.io/")
client = NetworkDefaultClient(configuration: configuration, session: .shared)
}
override func tearDown() {
client = nil
super.tearDown()
}
func testResponseStatusCode() {
let asyncExpectation = expectation(description: "Async")
let request = RealFailedTestRequest()
client.sendRequest(request) {
result, context in
switch result {
case .success:
XCTFail("Should be error")
case .failure(let error):
if let statusCode = context?.response?.statusCode {
XCTAssertEqual(statusCode, 301, "Not correct status code")
} else {
XCTFail("Should be another error, \(error)")
}
}
asyncExpectation.fulfill()
}
waitForExpectations(timeout: 10) { _ in }
}
func testValidationByMimeType() {
guard let url = URL(string: "https://e-legion.com") else {
XCTFail(" ")
return
}
guard let response = MockResponse(url: url, mimeType: "mimeType") else {
XCTFail(" ")
return
}
guard let data = response.responseData else {
XCTFail(" ")
return
}
var request = URLRequest(url: url)
request.addValue("mime/type", forHTTPHeaderField: "Accept")
let errors = Validator(request: request, response: response, data: data)
.validate()
.validationErrors
XCTAssertTrue(errors.count > 0)
}
func testValidationWhenResponseMimeIsNil() {
guard let url = URL(string: "https://e-legion.com") else {
XCTFail(" ")
return
}
guard let response = MockResponse(url: url, mimeType: nil) else {
XCTFail(" ")
return
}
guard let data = response.responseData else {
XCTFail(" ")
return
}
response.forceMimeType = true
response.forcedMimeType = nil
var request = URLRequest(url: url)
request.addValue("mime/type", forHTTPHeaderField: "Accept")
let errors = Validator(request: request, response: response, data: data)
.validate()
.validationErrors
XCTAssertTrue(errors.count > 0)
}
}
private class MockResponse: HTTPURLResponse {
private struct Consts {
static let jsonData = "[1,2,3]"
static var data: Data? {
return Consts.jsonData.data(using: .utf8)
}
}
override var statusCode: Int {
return 200
}
var forceMimeType: Bool = false
var forcedMimeType: String?
override var mimeType: String? {
return forceMimeType == false
? super.mimeType
: forcedMimeType
}
var responseData: Data? {
return Consts.data
}
convenience init?(url: URL, mimeType: String?) {
guard let unwrappedData = Consts.data else {
return nil
}
self.init(
url: url,
mimeType: mimeType,
expectedContentLength: unwrappedData.count,
textEncodingName: "UTF-8"
)
}
}
| true
|
b2f73942dce79eb3a194a666ac3f9bb45f0857ce
|
Swift
|
kadenhendrickson/SoloProject
|
/Kaden_SoloProject/ViewControllers/User ViewControllers/CreateRequestViewController.swift
|
UTF-8
| 4,395
| 2.5625
| 3
|
[] |
no_license
|
//
// CreateRequestViewController.swift
// Kaden_SoloProject
//
// Created by Kaden Hendrickson on 7/9/19.
// Copyright © 2019 DevMountain. All rights reserved.
//
import UIKit
class CreateRequestViewController: UIViewController {
lazy var datePicker: UIDatePicker = {
let picker: UIDatePicker = UIDatePicker()
picker.datePickerMode = .dateAndTime
picker.addTarget(self, action: #selector(dateChanged(sender:)), for: .valueChanged)
picker.backgroundColor = .white
picker.minimumDate = Date()
return picker
}()
lazy var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
return dateFormatter
}()
var dateOne: Date?
var dateTwo: Date?
var dateThree: Date?
@IBOutlet weak var projectNameTextField: UITextField!
@IBOutlet weak var projectAddressTextField: UITextField!
@IBOutlet weak var projectSquareFootageTextField: UITextField!
@IBOutlet weak var firstDateTextField: UITextField!
@IBOutlet weak var secondDateTextField: UITextField!
@IBOutlet weak var thirdDateTextField: UITextField!
@IBOutlet weak var projectCommentsTextView: UITextView!
@IBOutlet weak var submitRequestButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
firstDateTextField.inputView = datePicker
secondDateTextField.inputView = datePicker
thirdDateTextField.inputView = datePicker
}
@IBAction func submitRequestButtonTapped(_ sender: Any) {
guard projectNameTextField.text != "", let projectName = projectNameTextField.text else {presentAlert(withMessage: "Please give the project a name!"); return}
guard projectAddressTextField.text != "", let address = projectAddressTextField.text else {presentAlert(withMessage: "Please enter an address, so I don't get lost!"); return}
guard projectSquareFootageTextField.text != "", let squareFootage = projectSquareFootageTextField.text else {presentAlert(withMessage: "Please tell me how big the property is! (If you don't know type '0'"); return}
guard let dateOne = dateOne else {presentAlert(withMessage: "Please make sure you gave me three date options!"); return}
guard let dateTwo = dateTwo else {presentAlert(withMessage: "Please make sure you gave me three date options!"); return}
guard let dateThree = dateThree else {presentAlert(withMessage: "Please make sure you gave me three date options!"); return}
let comments = projectCommentsTextView.text ?? ""
RequestController.shared.UserCreateRequest(projectName: projectName, address: address, squareFootage: squareFootage, comments: comments, userDateOne: dateOne, userDateTwo: dateTwo, userDateThree: dateThree)
navigationController?.popViewController(animated: true)
}
//MARK: - Helper Functions
@objc func dateChanged(sender: UIDatePicker) {
if firstDateTextField.isEditing == true {
self.firstDateTextField.text = dateFormatter.string(from: sender.date)
dateOne = sender.date
} else if secondDateTextField.isEditing == true {
self.secondDateTextField.text = dateFormatter.string(from: sender.date)
dateTwo = sender.date
} else {
self.thirdDateTextField.text = dateFormatter.string(from: sender.date)
dateThree = sender.date
}
}
func presentAlert(withMessage: String) {
let alertController = UIAlertController(title: nil, message: withMessage, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
self.present(alertController, animated: true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
6ccfee990784f2ce2c94e0b3e09e9c317b0a14c7
|
Swift
|
EvgeniyFes/DTC_test
|
/DTC_test/Models/Points/PointModel.swift
|
UTF-8
| 304
| 2.578125
| 3
|
[] |
no_license
|
//
// PointModel.swift
// DTC_test
//
// Created by Evgeniy Fes on 26/01/2019.
// Copyright © 2019 Test. All rights reserved.
//
protocol PointModelProtocol {
var x: Double { get }
var y: Double { get }
}
struct PointModel: PointModelProtocol, Decodable {
var x: Double
var y: Double
}
| true
|
0220b627cfbd8535210ab22482f8bcbdab9f8dca
|
Swift
|
davidiad/VirtualTourist
|
/Search.swift
|
UTF-8
| 900
| 2.5625
| 3
|
[] |
no_license
|
//
// Search.swift
// VirtualTourist
//
// Created by David Fierstein on 1/8/16.
// Copyright © 2016 David Fierstein. All rights reserved.
//
import Foundation
import CoreData
class Search: NSManagedObject {
@NSManaged var searchString: String?
@NSManaged var accuracy: NSNumber?
@NSManaged var pin: Pin?
// standard Core Data init method.
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
init(dictionary: [String : AnyObject], context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName("Search", inManagedObjectContext: context)!
super.init(entity: entity,insertIntoManagedObjectContext: context)
searchString = dictionary[searchString!] as? String
}
}
| true
|
279b9650e1d77b33b886b2d47e4c478f88a067a5
|
Swift
|
phrz/Reggie
|
/Sources/Reggie/Group.swift
|
UTF-8
| 919
| 3.015625
| 3
|
[] |
no_license
|
//
// Group.swift
// Reggie
//
// Created by Paul Herz on 2018-04-17.
// Copyright © 2018 Paul Herz. All rights reserved.
//
import Foundation
public class Group {
public enum GroupType: String {
case
capturing = "",
nonCapturing = "?:",
negativeLookahead = "?!"
}
internal let type: GroupType
internal let sequence: RegularExpressionSequence
init(type t: GroupType = .nonCapturing, sequence s: RegularExpressionSequence) {
self.type = t
self.sequence = s
}
func having(type t: GroupType) -> Group {
return Group(type: t, sequence: sequence)
}
}
extension Group: RegularExpressionRepresentable {
public func regularExpressionRepresentation() -> () -> String? {
let result = self.sequence.regularExpressionRepresentation()().map {
return "(\(self.type.rawValue)\($0))"
}
// we get problems with deallocated "self" if we don't predetermine
// the result
return { result }
}
}
| true
|
e79486a55e9e8cd23af95406ff048063d398990a
|
Swift
|
freebz/SWIFT-3
|
/ch16/ex16-6.swift
|
UTF-8
| 226
| 3.09375
| 3
|
[] |
no_license
|
// 코드 16-6 옵셔널의 map 메서드 구현
extension Optional {
func map<U>(f: (Wrapped) -> U) -> U? {
switch self {
case .some(let x): return f(x)
case .none: return .none
}
}
}
| true
|
6c1d663b9590ebb3776af8695848e71406c7decc
|
Swift
|
nubbel/swift-tensorflow
|
/Xcode/Test/EchoProvider.swift
|
UTF-8
| 3,494
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
/*
*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
import Foundation
class EchoProvider : Echo_EchoProvider {
// get returns requests as they were received.
func get(request : Echo_EchoRequest, session : Echo_EchoGetSession) throws -> Echo_EchoResponse {
var response = Echo_EchoResponse()
response.text = "Swift echo get: " + request.text
return response
}
// expand splits a request into words and returns each word in a separate message.
func expand(request : Echo_EchoRequest, session : Echo_EchoExpandSession) throws -> Void {
let parts = request.text.components(separatedBy: " ")
var i = 0
for part in parts {
var response = Echo_EchoResponse()
response.text = "Swift echo expand (\(i)): \(part)"
try session.send(response)
i += 1
sleep(1)
}
}
// collect collects a sequence of messages and returns them concatenated when the caller closes.
func collect(session : Echo_EchoCollectSession) throws -> Void {
var parts : [String] = []
while true {
do {
let request = try session.receive()
parts.append(request.text)
} catch Echo_EchoServerError.endOfStream {
break
} catch (let error) {
print("\(error)")
}
}
var response = Echo_EchoResponse()
response.text = "Swift echo collect: " + parts.joined(separator: " ")
try session.sendAndClose(response)
}
// update streams back messages as they are received in an input stream.
func update(session : Echo_EchoUpdateSession) throws -> Void {
var count = 0
while true {
do {
let request = try session.receive()
count += 1
var response = Echo_EchoResponse()
response.text = "Swift echo update (\(count)): \(request.text)"
try session.send(response)
} catch Echo_EchoServerError.endOfStream {
break
} catch (let error) {
print("\(error)")
}
}
try session.close()
}
}
| true
|
fc592a5c2fb02c752826faf61ef0cb7b4c482c37
|
Swift
|
EvgeniiaKir/MovieDBTestApp
|
/MovieDBTestApp/Controller/ApiManager.swift
|
UTF-8
| 1,132
| 2.984375
| 3
|
[] |
no_license
|
//
// ApiManager.swift
// MovieDBTestApp
//
// Created by Евгения Колдышева on 13.03.2021.
//
import Foundation
import UIKit
final class ApiManager {
var urlArray: [String] = []
func fillURLArray(voteAverage: Double, voteCount: Int, page: Int) -> String {
var url = "https://api.themoviedb.org/3/discover/movie?"
let api_key = "274f828ad283bd634ef4fc1ee4af255f"
url.append("&vote_average.gte=\(voteAverage)&vote_count.gte=\(voteCount)&api_key=\(api_key)&page=\(page)")
return url
}
func getJson(url: String, completion: @escaping (Movies) -> ()){
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request){ data, res, err in
if let data = data {
let decoder = JSONDecoder()
do {
let json = try decoder.decode(Movies.self, from: data)
completion(json)
} catch {
print(error.localizedDescription)
}
}
}.resume()
}
}
| true
|
8b28e04f75487823c0553e2b9079dbf16a4cb9fb
|
Swift
|
turlodales/iOSSample
|
/iOSSample/Samples/DrawRectView/RoundedRectView.swift
|
UTF-8
| 1,293
| 2.84375
| 3
|
[] |
no_license
|
//
// RoundedRectView.swift
// iOSSample
//
// Created by 大石弘一郎 on 2019/04/18.
// Copyright © 2019 KoichiroOishi. All rights reserved.
//
import UIKit
class RoundedRectView: UIView {
@IBInspectable var baseColor: UIColor?
override func draw(_ rect: CGRect) {
let r = bounds.size.height * 0.5
drawRoundRect(rect: rect, radius: r, color: baseColor ?? UIColor.clear)
}
private func drawRoundRect(rect: CGRect, radius: CGFloat, color: UIColor) {
guard let context = UIGraphicsGetCurrentContext() else { return }
context.setFillColor(color.cgColor)
context.move(to: CGPoint(x: rect.minX, y: rect.midY))
context.addArc(tangent1End: CGPoint(x: rect.minX, y: rect.minY), tangent2End: CGPoint(x: rect.midX, y: rect.minY), radius: radius)
context.addArc(tangent1End: CGPoint(x: rect.maxX, y: rect.minY), tangent2End: CGPoint(x: rect.maxX, y: rect.midY), radius: radius)
context.addArc(tangent1End: CGPoint(x: rect.maxX, y: rect.maxY), tangent2End: CGPoint(x: rect.midX, y: rect.maxY), radius: radius)
context.addArc(tangent1End: CGPoint(x: rect.minX, y: rect.maxY), tangent2End: CGPoint(x: rect.minX, y: rect.midY), radius: radius)
context.closePath()
context.fillPath()
}
}
| true
|
330efade4cc47d05a335724e365a0b545244b6c6
|
Swift
|
cweirup/JoplinSafariWebClipper
|
/Joplin Clipper Extension/Auth.swift
|
UTF-8
| 1,488
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
//
// Auth.swift
// Joplin Clipper Extension
//
// Created by Christopher Weirup on 2021-07-21.
// Copyright © 2021 Christopher Weirup. All rights reserved.
//
import Foundation
struct AuthToken: Decodable {
var auth_token: String?
}
struct AuthAcceptedResponse: Decodable {
var status: String?
var token: String?
}
struct AuthRejectedResponse: Decodable {
var status: String?
}
struct AuthWaitingResponse: Decodable {
var status: String?
}
struct ErrorResponse: Decodable {
var error: String
}
enum AuthResponse: Decodable {
case accepted(AuthAcceptedResponse)
case waiting(AuthWaitingResponse)
case rejected(AuthRejectedResponse)
case failure(ErrorResponse)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
let authData = try container.decode(AuthAcceptedResponse.self)
switch authData.status {
case "accepted":
self = .accepted(authData)
case "waiting":
self = .waiting(AuthWaitingResponse(status: authData.status))
default:
self = .rejected(AuthRejectedResponse(status: authData.status))
}
} catch DecodingError.typeMismatch {
let errorData = try container.decode(ErrorResponse.self)
self = .failure(errorData)
}
}
}
// MARK - Struct for checking if API Token is valid
struct ApiCheck: Decodable {
var valid: Bool
}
| true
|
d9e52634a754884fb1bd8f82aed140fd4354163d
|
Swift
|
quickbird-uk/Hive-iOS
|
/Hive/AddStaffViewController.swift
|
UTF-8
| 5,293
| 2.53125
| 3
|
[] |
no_license
|
//
// AddStaffViewController.swift
// Hive
//
// Created by Animesh. on 20/11/2015.
// Copyright © 2015 Animesh. All rights reserved.
//
import UIKit
class AddStaffViewController: UITableViewController, OptionsListDataSource
{
//
// MARK: - Properties & Outlets
//
let contacts = Contact.getAll("Fr")
var selectedContact: Contact!
var selectedRole: String!
let accessToken = User.get()!.accessToken!
var organisation: Organisation!
@IBOutlet weak var contactCell: TableViewCellWithSelection!
@IBOutlet weak var roleCell: TableViewCellWithSelection!
func showError(message: String)
{
let alert = UIAlertController(
title: "Oops!",
message: message,
preferredStyle: .ActionSheet)
let addAction = UIAlertAction(title: "Add Contacts Now", style: .Default) {
alert in
if self.shouldPerformSegueWithIdentifier("addContact", sender: nil) {
self.performSegueWithIdentifier("addContact", sender: nil)
}
}
alert.addAction(addAction)
let cancelAction = UIAlertAction(title: "I'll do it later.", style: .Cancel) {
alert in
self.navigationController?.popViewControllerAnimated(true)
}
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
@IBAction func add(sender: UIBarButtonItem)
{
if contactCell.selectedOption == "Select"
{
let alert = UIAlertController(
title: "Oops!",
message: "Please select a contact before proceeding.",
preferredStyle: .ActionSheet)
let cancelAction = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
return
}
if roleCell.selectedOption == "Select"
{
let alert = UIAlertController(
title: "Oops!",
message: "Please assign a role before proceeding.",
preferredStyle: .ActionSheet)
let cancelAction = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
return
}
let staff = Staff.temporary()
staff.personID = selectedContact.friendID
print(organisation)
staff.onOrganisationID = organisation.id
staff.role = selectedRole
HiveService.shared.addStaff(staff, accessToken: accessToken) {
(didAdd, newStaff, error) -> Void in
if didAdd && newStaff != nil {
dispatch_async(dispatch_get_main_queue()) {
newStaff!.moveToPersistentStore()
self.navigationController?.popViewControllerAnimated(true)
}
}
else {
dispatch_async(dispatch_get_main_queue()) {
let errorMessage = error ?? "Something bad happened"
let alert = UIAlertController(
title: "Oops!",
message: errorMessage,
preferredStyle: .ActionSheet)
let cancelAction = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
}
func updateCell(atIndex index: NSIndexPath, withOption option: String, selectedIndex: Int)
{
switch index.row
{
case 0:
selectedContact = contacts![selectedIndex]
contactCell.selectedOption = selectedContact.firstName! + " " + selectedContact.lastName!
case 1:
selectedRole = option
roleCell.selectedOption = selectedRole
default:
break
}
}
override func viewDidLoad()
{
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool
{
if identifier == "selectContactForStaff"
{
if contacts == nil {
showError("You have no contacts yet. Please add one by tapping the + in the top bar in Contacts view. If you have already sent out invites you will have to wait until they are accepted.")
return false
}
return true
}
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "selectContactForStaff"
{
let destination = segue.destinationViewController as! OptionsListViewController
destination.delegate = self
var options = [String]()
if contacts != nil {
for contact in contacts!
{
options.append(contact.firstName! + " " + contact.lastName!)
}
}
else {
options.append("You have no contacts.")
options.append("Please add a contact first.")
}
destination.options = options
destination.senderCellIndexPath = tableView.indexPathForCell(contactCell)
}
if segue.identifier == "selectRoleForStaff"
{
let destination = segue.destinationViewController as! OptionsListViewController
destination.delegate = self
destination.options = Staff.Role.allRoles
destination.senderCellIndexPath = tableView.indexPathForCell(roleCell)
}
}
}
| true
|
871fc17458a71846822f583ed8cb1d63fa1eab10
|
Swift
|
Juan-Ceballos/DSA-Resource
|
/MergeSortPractice.playground/Pages/MergeSort9.xcplaygroundpage/Contents.swift
|
UTF-8
| 1,293
| 3.828125
| 4
|
[] |
no_license
|
//: [Previous](@previous)
import Foundation
func merge(leftArr: [Int], rightArr: [Int]) -> [Int] {
// comparing left and right right arr left arr
var resultArr = [Int]()
var left = 0
var right = 0
while left < leftArr.count && right < rightArr.count {
let leftValue = leftArr[left]
let rightValue = rightArr[right]
if leftValue < rightValue {
resultArr.append(leftValue)
left += 1
} else if rightValue < leftValue {
resultArr.append(rightValue)
right += 1
} else {
resultArr.append(leftValue)
resultArr.append(rightValue)
left += 1
right += 1
}
}
if left < leftArr.count {
resultArr.append(contentsOf: leftArr[left...])
}
if right < rightArr.count {
resultArr.append(contentsOf: rightArr[right...])
}
return resultArr
}
func mergeSort(arr: [Int]) -> [Int] {
guard arr.count > 1 else {
return arr
}
let middle = arr.count / 2
let leftArr = mergeSort(arr: Array(arr[..<middle]))
let rightArr = mergeSort(arr: Array(arr[middle...]))
return merge(leftArr: leftArr, rightArr: rightArr)
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.