repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
gistya/Functional-Swift-Graph
refs/heads/master
Functional Graph.playground/Sources/Node.swift
gpl-3.0
1
import Foundation public struct Node<_Content:Hashable>:Hashable { public var createdTime: Date = Date() public var id: Id public var value: _Content public static func ==(lhs: Node, rhs: Node) -> Bool { return lhs.createdTime == rhs.createdTime && lhs.value == rhs.value } public init(id:Id, value:_Content) { self.id = id self.value = value } public var hashValue: Int { get { return Int(createdTime.timeIntervalSince1970) } } } extension Node: CustomStringConvertible { public var description:String { get { return "Id: \(id), Value: \(value)" } } }
4ff6782add4f9ca60b2616621b75a276
24.148148
75
0.587629
false
false
false
false
c650/Caesar-Cipher
refs/heads/master
caesar/swift/caesar-cipher.swift
mit
2
/**************************************************************************** Charles Bailey caesar.swift It encrypts/decrypts a phrase according to a certain caesar cipher key. ****************************************************************************/ import Foundation /* Encryption Function: Takes a key and mutates any alphabetical character by it. Note: lines 29 and 32 hopefully can be trimmed */ func encrypt(key: Int, phrase: String) -> String { let key = key % 26 // very important to get key within 0-25 range! var arr = [Character]() // make an Array ("collection") to store encryped result phrase for character in phrase.unicodeScalars { // iterate throught each UnicodeScalar in phrase if character.value >= 65 && character.value <= 90 { // check if capital Alpha // append to arr: get the UnicodeScalar of the current character + key + 7 (for some reason) // mod it by 26 to get it within Alpha range, add 65 to get it to ASCII Alpha range arr.append(Character(UnicodeScalar(((Int(character.value) + key + 7) % 26) + 65))) } else if character.value >= 97 && character.value <= 122 { // check if lower Alpha // see ln25-26; same except for the lower case arr.append(Character(UnicodeScalar(((Int(character.value) + key + 7) % 26) + 97))) } else { // just append the original if it isn't alphabetical arr.append(Character(character)) } } // return a String composed of the array from ln21 return String(arr) } /* Decryption Function: Simply calls encrypt(...) with a negated key. */ func decrypt(key: Int, phrase: String) -> String { return encrypt(-key, phrase: phrase) } /* "main()" The controller for the program. */ if Process.arguments.count != 2 { // ln 57-60: check for correct number of arguments print("\nWrong number of arguments.") print("Usuage: caesar <key>") } else { print("Put in the phrase to encrypt: ") // prompt for input, duh if let input = readLine() { // will exit if getting a string fails if let key = Int(Process.arguments[1]) { // assigns the key, exits if fails // ln67-71: presents user with the results print("Encrypting...") print(encrypt(key, phrase: input)) print("Decrypting...") print(decrypt(key, phrase: encrypt(key, phrase: input))) } // curly brace } // another curly } // i'm just trolling
76c6cf962ef019a1ced1adbe8cf0cb5d
30.648649
95
0.639897
false
false
false
false
c1moore/deckstravaganza
refs/heads/master
Deckstravaganza/StackPile.swift
mit
1
// // StackPile.swift // Deckstravaganza // // Created by Calvin Moore on 9/21/15. // Copyright © 2015 University of Florida. All rights reserved. // import UIKit class StackPile: Pile { /** * True if the top of the stack is at the first card. The first * card is defined as the card that has its back facing away from * all the other cards. */ private let topAtFirstCard : Bool; override init() { topAtFirstCard = false; super.init(); } init(isTopAtFirstCard : Bool) { topAtFirstCard = isTopAtFirstCard; super.init(); } init(oldPile : StackPile, isTopAtFirstCard : Bool = false) { topAtFirstCard = isTopAtFirstCard; super.init(); if(topAtFirstCard) { while(!oldPile.isEmpty()) { pile.insert(oldPile.pull()!, atIndex: 0); } } else { while(!oldPile.isEmpty()) { pile.append(oldPile.pull()!); } } } /** * Push newCard to the top of the stack. * * @param newCard : Card - the card to insert at the top of the stack */ func push(newCard : Card) { if(topAtFirstCard) { pile.insert(newCard, atIndex: 0); } else { pile.append(newCard); } } /** * Remove and return the card at the top of the stack. * * @return Card? - the card at the top of the stack. */ func pull() -> Card? { if(topAtFirstCard) { return pile.removeAtIndex(0); } else { return pile.popLast(); } } /** * Return the card at the top of the stack. * * @return Card? - the card at the top of the stack. */ func topCard() -> Card? { if(topAtFirstCard) { if(!pile.isEmpty) { return pile[0]; } else { return nil; } } else { return pile.last; } } /** * Push all the cards in newPile starting at the first card of the pile. The first * card is defined as the card that has its back facing away from all the other cards. * This operation removes all cards from newPile. * * @param newPile : Pile - the pile to add to this pile */ func addToStackFromFirstCardOf(newPile : Pile) { for(var index = 0, cardCount = newPile.numberOfCards(); index < cardCount; index++) { self.push(newPile.cardAt(index)!); } newPile.removeAllCards(); } /** * Push all the cards in newPile starting at the last card of the pile. The last * card is defined as the card that has its face side facing away from all the other cards. * This operation removes all cards from newPile. * * @param newPile : Pile - the pile to add to this pile */ func addToStackFromLastCardOf(newPile : Pile) { for(var index = 0, cardCount = newPile.numberOfCards(); index < cardCount; index++) { self.push(newPile.cardAt(cardCount - 1 - index)!); } newPile.removeAllCards(); } }
4756bba66c4328b1434dbefd1a8c03be
25.991597
94
0.543444
false
false
false
false
X140Yu/Lemon
refs/heads/master
Lemon/Library/Protocol/LoadableView.swift
gpl-3.0
1
import UIKit import RxSwift import RxCocoa protocol Loadable { var ld_contentView: UIView { get } func startLoading() func stopLoading() } class LoadableViewProvider: Loadable { var ld_contentView: UIView let isLoading = Variable<Bool>(false) lazy var loadingView: UIView = { let v = UIView() v.backgroundColor = UIColor.white let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray) v.addSubview(spinner) spinner.startAnimating() spinner.snp.makeConstraints({ (maker) in maker.center.equalTo(v) }) return v }() init(contentView: UIView) { ld_contentView = contentView isLoading.value = false } func startLoading() { stopLoading() isLoading.value = true ld_contentView.addSubview(loadingView) loadingView.snp.makeConstraints { (maker) in maker.edges.equalTo(ld_contentView) } } func stopLoading() { isLoading.value = false loadingView.removeFromSuperview() } }
b23a556679e3350e69675e3f6cde4744
20.888889
72
0.694416
false
false
false
false
MarcoSantarossa/SwiftyToggler
refs/heads/develop
Source/FeaturesList/ViewModel/FeaturesListViewModel.swift
mit
1
// // FeaturesListViewModel.swift // // Copyright (c) 2017 Marco Santarossa (https://marcosantadev.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // final class FeaturesListViewModel: FeaturesListViewModelProtocol { private struct Constants { static let defaultCloseButtonHeight: CGFloat = 44 static let defaultTitleLabelHeight: CGFloat = 50 } weak var delegate: FeaturesListViewModelDelegate? var featuresCount: Int { return featuresStatus.count } var titleLabelHeight: CGFloat { guard case PresentingMode.modal(_) = self.presentingMode else { return 0 } return Constants.defaultTitleLabelHeight } var closeButtonHeight: CGFloat { guard case PresentingMode.modal(_) = self.presentingMode else { return 0 } return Constants.defaultCloseButtonHeight } var shouldShowPlaceholder: Bool { return featuresCount == 0 } fileprivate let featuresManager: FeaturesManagerTogglerProtocol fileprivate let featuresStatus: [FeatureStatus] private let presentingMode: PresentingMode init(featuresManager: FeaturesManagerTogglerProtocol = FeaturesManager.shared, presentingMode: PresentingMode) { self.featuresManager = featuresManager self.presentingMode = presentingMode self.featuresStatus = featuresManager.featuresStatus } } extension FeaturesListViewModel: FeaturesListViewModelUIBindingProtocol { func featureStatus(at indexPath: IndexPath) -> FeatureStatus? { guard indexPath.row < featuresStatus.count else { return nil } return featuresStatus[indexPath.row] } func updateFeature(name: String, isEnabled: Bool) { try? featuresManager.setEnable(isEnabled, featureName: name) } func closeButtonDidTap() { delegate?.featuresListViewModelNeedsClose() } }
c508b3f608825cbb281ad463eb8f8cde
36.648649
82
0.77028
false
false
false
false
twoefay/ios-client
refs/heads/master
Twoefay/Controller/RegistrationPageViewController.swift
gpl-3.0
1
// // RegistrationPageViewController.swift // Twoefay // // Created by Jonathan Woong on 5/11/16. // Copyright © 2016 Twoefay. All rights reserved. // import UIKit class RegistrationPageViewController: UIViewController { @IBOutlet weak var firstNameField: UITextField! @IBOutlet weak var lastNameField: UITextField! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var rePasswordField: UITextField! override func viewDidLoad() { super.viewDidLoad() // this is a comment // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func submitRegistration(sender: AnyObject) { // Get textfield data let userFirstName = firstNameField.text; let userLastName = lastNameField.text; let userEmail = emailField.text; let userPassword = passwordField.text; let userRePassword = rePasswordField.text; // Check for empty fields if(userFirstName!.isEmpty || userLastName!.isEmpty || userEmail!.isEmpty || userPassword!.isEmpty || userRePassword!.isEmpty) { // Display alert message displayAlert("All fields are required"); return; } // Check if passwords match if (userPassword != userRePassword) { // Display alert message displayAlert("Passwords do not match"); return; } // Store data (locally) // TODO: store data remotely NSUserDefaults.standardUserDefaults().setObject(userFirstName, forKey:"userFirstName"); NSUserDefaults.standardUserDefaults().setObject(userLastName, forKey:"userLastName"); NSUserDefaults.standardUserDefaults().setObject(userEmail, forKey:"userEmail"); NSUserDefaults.standardUserDefaults().setObject(userPassword, forKey:"userPassword"); NSUserDefaults.standardUserDefaults().setObject(userRePassword, forKey:"userRePassword"); NSUserDefaults.standardUserDefaults().synchronize(); // Confirm submission let Alert = UIAlertController(title:"Alert", message:"Registration Successful", preferredStyle: UIAlertControllerStyle.Alert); let OK = UIAlertAction(title:"OK", style:UIAlertActionStyle.Default) { action in self.dismissViewControllerAnimated(true, completion:nil); } Alert.addAction(OK); self.presentViewController(Alert, animated:true,completion:nil); } // Display alert with message userMessage func displayAlert(userMessage:String) { let Alert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.Alert); let OK = UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:nil); Alert.addAction(OK); self.presentViewController(Alert, animated:true, completion:nil); } }
8e7ccf8bd4ae81b058fe64c22da04141
36.845238
135
0.663102
false
false
false
false
tsalvo/nes-chr-editor
refs/heads/master
NES CHR Editor/NES CHR Editor/ViewControllers/FullGridCollectionViewController.swift
apache-2.0
1
// // FullGridCollectionViewController.swift // NES CHR Editor // // Created by Tom Salvo on 11/5/16. // Copyright © 2016 Tom Salvo. All rights reserved. // import AppKit class FullGridCollectionViewController: NSViewController, NSCollectionViewDelegateFlowLayout, NSCollectionViewDataSource, CHREditProtocol, CHRGridHistoryProtocol { @IBOutlet weak private var gridCollectionView:NSCollectionView! var CHRGridHistory:[CHRGrid] = [] // for tracking undo operations, most recent = beginning var CHRGridFuture:[CHRGrid] = [] // for tracking redo operations var tileSelectionDelegate:CHRSelectionProtocol? var fileEditDelegate:FileEditProtocol? var grid:CHRGrid = CHRGrid() { didSet { self.gridCollectionView.reloadData() } } static var CHRClipboard:CHR? var brushColor:PaletteColor = .Color3 override func viewDidLoad() { super.viewDidLoad() self.gridCollectionView.allowsMultipleSelection = false self.gridCollectionView.allowsEmptySelection = false self.gridCollectionView.register(GridCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "gridCollectionItem")) self.gridCollectionView.delegate = self self.gridCollectionView.dataSource = self } override func updateViewConstraints() { super.updateViewConstraints() self.gridCollectionView.collectionViewLayout?.invalidateLayout() } // MARK: - NSCollectionViewDelegateFlowLayout func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize { let possibleNumbersOfItemsPerRow:[CGFloat] = [32, 16, 8, 4, 2] let collectionViewWidth = collectionView.bounds.width let minimumItemWidth:CGFloat = min(collectionViewWidth, 50) var itemWidth:CGFloat = collectionViewWidth // default for possibleNumberOfItemsPerRow in possibleNumbersOfItemsPerRow { if collectionViewWidth / possibleNumberOfItemsPerRow >= minimumItemWidth { itemWidth = collectionViewWidth / possibleNumberOfItemsPerRow break } } return NSSize(width: itemWidth, height: itemWidth) } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets { return NSEdgeInsetsZero } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> NSSize { return NSSize.zero } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForFooterInSection section: Int) -> NSSize { return NSSize.zero } func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) { if let safeFirstIndexPath = indexPaths.first { let previousIndexPath = IndexPath(item: Int(self.grid.selectedCHRIndex), section: 0) self.grid.selectedCHRIndex = UInt(safeFirstIndexPath.item) collectionView.reloadItems(at: [previousIndexPath, IndexPath(item: Int(self.grid.selectedCHRIndex), section: 0)]) self.tileSelectionDelegate?.tileSelected(withCHR: self.grid.getCHR(atIndex: self.grid.selectedCHRIndex)) } } // MARK: - NSCollectionViewDataSource func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return Int(ChrFileSize(numChrBlocks: grid.numChrBlocks).numCHRsInFile) } func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { // Recycle or create an item. guard let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "gridCollectionItem"), for: indexPath) as? GridCollectionViewItem else { return NSCollectionViewItem() } item.itemView.chr = self.grid.getCHR(atIndex: UInt(indexPath.item)) item.itemView.isSelected = UInt(indexPath.item) == self.grid.selectedCHRIndex item.itemView.setNeedsDisplay(item.itemView.bounds) return item } // MARK: - TileEditProtocol func tileEdited(withCHR aCHR: CHR) { self.grid.setCHR(chr: aCHR, atIndex: self.grid.selectedCHRIndex) self.gridCollectionView.reloadItems(at: [IndexPath(item: Int(self.grid.selectedCHRIndex), section: 0)]) } // MARK : - CHRGridHistoryProtocol func CHRGridWillChange() { // remove the oldest CHR grids from the history until we're below the maximum allowed while self.CHRGridHistory.count >= Int(Constants.maxCHRGridHistory) { let _ = self.CHRGridHistory.popLast() } // if the user edited the grid, there should be no grid future for Redo operations self.CHRGridFuture.removeAll() self.CHRGridHistory.insert(self.grid, at: 0) // add most recent grid to the front of the history self.fileEditDelegate?.fileWasEdited() } func undo() { // if there's a CHR grid in the history if let safeMostRecentGrid = self.CHRGridHistory.first { // remove the oldest CHR grids from the grid future until we're below the maximum allowed while self.CHRGridFuture.count >= Int(Constants.maxCHRGridHistory) { let _ = self.CHRGridFuture.popLast() } self.CHRGridFuture.insert(self.grid, at: 0) // add current grid to the front of the future self.grid = safeMostRecentGrid self.gridCollectionView.reloadData() self.tileSelectionDelegate?.tileSelected(withCHR: self.grid.getCHR(atIndex: self.grid.selectedCHRIndex)) self.CHRGridHistory.removeFirst() // remove most recent grid from the front of the history } } func redo() { // if there's a CHR Grid in the future if let safeNextFutureGrid = self.CHRGridFuture.first { self.CHRGridHistory.insert(self.grid, at: 0) // add current grid to the front of the history self.grid = safeNextFutureGrid self.gridCollectionView.reloadData() self.tileSelectionDelegate?.tileSelected(withCHR: self.grid.getCHR(atIndex: self.grid.selectedCHRIndex)) self.CHRGridFuture.removeFirst() // remove most recent grid from the front of the future } } func cutCHR() { FullGridCollectionViewController.CHRClipboard = self.grid.getCHR(atIndex: self.grid.selectedCHRIndex) if let safeCHRClipboard = FullGridCollectionViewController.CHRClipboard, !safeCHRClipboard.isEmpty() { self.CHRGridWillChange() self.grid.setCHR(chr: CHR(), atIndex: self.grid.selectedCHRIndex) self.gridCollectionView.reloadItems(at: [IndexPath(item: Int(self.grid.selectedCHRIndex), section: 0)]) self.tileSelectionDelegate?.tileSelected(withCHR: self.grid.getCHR(atIndex: self.grid.selectedCHRIndex)) } } func copyCHR() { FullGridCollectionViewController.CHRClipboard = self.grid.getCHR(atIndex: self.grid.selectedCHRIndex) } func pasteCHR() { if let safeCHRClipboard = FullGridCollectionViewController.CHRClipboard { self.CHRGridWillChange() self.grid.setCHR(chr: safeCHRClipboard, atIndex: self.grid.selectedCHRIndex) self.gridCollectionView.reloadItems(at: [IndexPath(item: Int(self.grid.selectedCHRIndex), section: 0)]) self.tileSelectionDelegate?.tileSelected(withCHR: self.grid.getCHR(atIndex: self.grid.selectedCHRIndex)) } } }
9bbab9932ef7f39b1675e550a6a26422
40.898551
209
0.676237
false
false
false
false
kosua20/PtahRenderer
refs/heads/master
PtahRenderer/Geometry.swift
mit
1
// // Geometry.swift // PtahRenderer // // Created by Simon Rodriguez on 14/02/2016. // Copyright © 2016 Simon Rodriguez. All rights reserved. // import Foundation #if os(macOS) import simd #endif /*--Barycentre-------*/ func barycentre(_ p: Point3, _ v0: Point3, _ v1: Point3, _ v2: Point3) -> Point3{ let ab = v1 - v0 let ac = v2 - v0 let pa = v0 - p let uv1 = cross(Point3(ac.x, ab.x, pa.x), Point3(ac.y, ab.y, pa.y)) if abs(uv1.z) < 1e-2 { return Point3(-1, 1, 1) } return (1.0/uv1.z)*Point3(uv1.z-(uv1.x+uv1.y), uv1.y, uv1.x) } func barycentricInterpolation(coeffs: Point3, t1: Point2, t2: Point2, t3: Point2) -> Point2{ return coeffs.x * t1 + coeffs.y * t2 + coeffs.z * t3 } func barycentricInterpolation(coeffs: Point3, t1: Point3, t2: Point3, t3: Point3) -> Point3{ return coeffs.x * t1 + coeffs.y * t2 + coeffs.z * t3 } func barycentricInterpolation(coeffs: Point3, t1: [Scalar], t2: [Scalar], t3: [Scalar]) -> [Scalar]{ var newOthers : [Scalar] = [] for i in 0..<t1.count { newOthers.append(coeffs.x * t1[i] + coeffs.y * t2[i] + coeffs.z * t3[i]) } return newOthers } /*--Bounding box-------------*/ func boundingBox(_ vs: [Point3], _ width: Int, _ height: Int) -> (Point2, Point2){ var mini = Point2(Scalar.infinity, Scalar.infinity) var maxi = Point2(-Scalar.infinity, -Scalar.infinity) let lim = Point2(Scalar(width-1), Scalar(height-1)) for v in vs { let v2 = Point2(v.x, v.y) mini = min(mini, v2) maxi = max(maxi, v2) } let finalMin = clamp(min(mini,maxi), min: Point2(0.0), max: lim) let finalMax = clamp(max(mini,maxi), min: Point2(0.0), max: lim) return (finalMin, finalMax) }
4e5ff1c0f535c0ab12d46ea8bf4521c2
20.384615
100
0.625899
false
false
false
false
AaronMT/firefox-ios
refs/heads/main
Sync/Synchronizers/TabsSynchronizer.swift
mpl-2.0
9
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger import SwiftyJSON private let log = Logger.syncLogger let TabsStorageVersion = 1 open class TabsSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs, why: SyncReason) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, why: why, collection: "tabs") } override var storageVersion: Int { return TabsStorageVersion } var tabsRecordLastUpload: Timestamp { set(value) { self.prefs.setLong(value, forKey: "lastTabsUpload") } get { return self.prefs.unsignedLongForKey("lastTabsUpload") ?? 0 } } fileprivate func createOwnTabsRecord(_ tabs: [RemoteTab]) -> Record<TabsPayload> { let guid = self.scratchpad.clientGUID let tabsJSON = JSON([ "id": guid, "clientName": self.scratchpad.clientName, "tabs": tabs.compactMap { $0.toDictionary() } ]) if Logger.logPII { log.verbose("Sending tabs JSON \(tabsJSON.stringify() ?? "nil")") } let payload = TabsPayload(tabsJSON) return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds) } fileprivate func uploadOurTabs(_ localTabs: RemoteClientsAndTabs, toServer tabsClient: Sync15CollectionClient<TabsPayload>) -> Success { // check to see if our tabs have changed or we're in a fresh start let lastUploadTime: Timestamp? = (self.tabsRecordLastUpload == 0) ? nil : self.tabsRecordLastUpload if let lastUploadTime = lastUploadTime, lastUploadTime >= (Date.now() - (OneMinuteInMilliseconds)) { log.debug("Not uploading tabs: already did so at \(lastUploadTime).") return succeed() } return localTabs.getTabsForClientWithGUID(nil) >>== { tabs in if let lastUploadTime = lastUploadTime { // TODO: track this in memory so we don't have to hit the disk to figure out when our tabs have // changed and need to be uploaded. if tabs.every({ $0.lastUsed < lastUploadTime }) { return succeed() } } let tabsRecord = self.createOwnTabsRecord(tabs) log.debug("Uploading our tabs: \(tabs.count).") var uploadStats = SyncUploadStats() uploadStats.sent += 1 // We explicitly don't send If-Unmodified-Since, because we always // want our upload to succeed -- we own the record. return tabsClient.put(tabsRecord, ifUnmodifiedSince: nil) >>== { resp in if let ts = resp.metadata.lastModifiedMilliseconds { // Protocol says this should always be present for success responses. log.debug("Tabs record upload succeeded. New timestamp: \(ts).") self.tabsRecordLastUpload = ts } else { uploadStats.sentFailed += 1 } return succeed() } >>== effect({ self.statsSession.recordUpload(stats: uploadStats) }) } } open func synchronizeLocalTabs(_ localTabs: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult { func onResponseReceived(_ response: StorageResponse<[Record<TabsPayload>]>) -> Success { func afterWipe() -> Success { var downloadStats = SyncDownloadStats() let doInsert: (Record<TabsPayload>) -> Deferred<Maybe<(Int)>> = { record in let remotes = record.payload.isValid() ? record.payload.remoteTabs : [] let ins = localTabs.insertOrUpdateTabsForClientGUID(record.id, tabs: remotes) // Since tabs are all sent within a single record, we don't count number of tabs applied // but number of records. In this case it's just one. downloadStats.applied += 1 ins.upon() { res in if let inserted = res.successValue { if inserted != remotes.count { log.warning("Only inserted \(inserted) tabs, not \(remotes.count). Malformed or missing client?") } downloadStats.applied += 1 } else { downloadStats.failed += 1 } } return ins } let ourGUID = self.scratchpad.clientGUID let records = response.value let responseTimestamp = response.metadata.lastModifiedMilliseconds log.debug("Got \(records.count) tab records.") // We can only insert tabs for clients that we know locally, so // first we fetch the list of IDs and intersect the two. // TODO: there's a much more efficient way of doing this. return localTabs.getClientGUIDs() >>== { clientGUIDs in let filtered = records.filter({ $0.id != ourGUID && clientGUIDs.contains($0.id) }) if filtered.count != records.count { log.debug("Filtered \(records.count) records down to \(filtered.count).") } let allDone = all(filtered.map(doInsert)) return allDone.bind { (results) -> Success in if let failure = results.find({ $0.isFailure }) { return deferMaybe(failure.failureValue!) } self.lastFetched = responseTimestamp! return succeed() } } >>== effect({ self.statsSession.downloadStats }) } // If this is a fresh start, do a wipe. if self.lastFetched == 0 { log.info("Last fetch was 0. Wiping tabs.") return localTabs.wipeRemoteTabs() >>== afterWipe } return afterWipe() } if let reason = self.reasonToNotSync(storageClient) { return deferMaybe(SyncStatus.notStarted(reason)) } let keys = self.scratchpad.keys?.value let encoder = RecordEncoder<TabsPayload>(decode: { TabsPayload($0) }, encode: { $0.json }) if let encrypter = keys?.encrypter(self.collection, encoder: encoder) { let tabsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter) statsSession.start() if !self.remoteHasChanges(info) { // upload local tabs if they've changed or we're in a fresh start. return uploadOurTabs(localTabs, toServer: tabsClient) >>> { deferMaybe(self.completedWithStats) } } return tabsClient.getSince(self.lastFetched) >>== onResponseReceived >>> { self.uploadOurTabs(localTabs, toServer: tabsClient) } >>> { deferMaybe(self.completedWithStats) } } log.error("Couldn't make tabs factory.") return deferMaybe(FatalError(message: "Couldn't make tabs factory.")) } /** * This is a dedicated resetting interface that does both tabs and clients at the * same time. */ public static func resetClientsAndTabsWithStorage(_ storage: ResettableSyncStorage, basePrefs: Prefs) -> Success { let clientPrefs = BaseCollectionSynchronizer.prefsForCollection("clients", withBasePrefs: basePrefs) let tabsPrefs = BaseCollectionSynchronizer.prefsForCollection("tabs", withBasePrefs: basePrefs) clientPrefs.removeObjectForKey("lastFetched") tabsPrefs.removeObjectForKey("lastFetched") return storage.resetClient() } } extension RemoteTab { public func toDictionary() -> Dictionary<String, Any>? { let tabHistory = history.compactMap { $0.absoluteString } if tabHistory.isEmpty { return nil } return [ "title": title, "icon": icon?.absoluteString as Any? ?? NSNull(), "urlHistory": tabHistory, "lastUsed": millisecondsToDecimalSeconds(lastUsed) ] } }
4b2235ad16335a512fa0dd542149a5d9
41.941463
155
0.575826
false
false
false
false
narner/AudioKit
refs/heads/master
AudioKit/Common/Internals/AudioKit.swift
mit
1
// // AudioKit.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // #if !os(tvOS) import CoreAudioKit #endif #if !os(macOS) import UIKit #endif import Dispatch public typealias AKCallback = () -> Void /// Top level AudioKit managing class @objc open class AudioKit: NSObject { // MARK: Global audio format (44.1K, Stereo) /// Format of AudioKit Nodes @objc open static var format = AKSettings.audioFormat // MARK: - Internal audio engine mechanics /// Reference to the AV Audio Engine @objc open static let engine = AVAudioEngine() @objc static var shouldBeRunning = false @objc static var finalMixer = AKMixer() /// An audio output operation that most applications will need to use last @objc open static var output: AKNode? { didSet { updateSessionCategoryAndOptions() output?.connect(to: finalMixer) engine.connect(finalMixer.avAudioNode, to: engine.outputNode) } } // MARK: - Device Management /// Enumerate the list of available input devices. @objc open static var inputDevices: [AKDevice]? { #if os(macOS) EZAudioUtilities.setShouldExitOnCheckResultFail(false) return EZAudioDevice.inputDevices().map { AKDevice(name: ($0 as AnyObject).name, deviceID: ($0 as AnyObject).deviceID) } #else var returnDevices = [AKDevice]() if let devices = AVAudioSession.sharedInstance().availableInputs { for device in devices { if device.dataSources == nil || device.dataSources!.isEmpty { returnDevices.append(AKDevice(name: device.portName, deviceID: device.uid)) } else { for dataSource in device.dataSources! { returnDevices.append(AKDevice(name: device.portName, deviceID: "\(device.uid) \(dataSource.dataSourceName)")) } } } return returnDevices } return nil #endif } /// Enumerate the list of available output devices. @objc open static var outputDevices: [AKDevice]? { #if os(macOS) EZAudioUtilities.setShouldExitOnCheckResultFail(false) return EZAudioDevice.outputDevices().map { AKDevice(name: ($0 as AnyObject).name, deviceID: ($0 as AnyObject).deviceID) } #else let devs = AVAudioSession.sharedInstance().currentRoute.outputs if devs.isNotEmpty { var outs = [AKDevice]() for dev in devs { outs.append(AKDevice(name: dev.portName, deviceID: dev.uid)) } return outs } return nil #endif } /// The name of the current input device, if available. @objc open static var inputDevice: AKDevice? { #if os(macOS) if let dev = EZAudioDevice.currentInput() { return AKDevice(name: dev.name, deviceID: dev.deviceID) } #else if let dev = AVAudioSession.sharedInstance().preferredInput { return AKDevice(name: dev.portName, deviceID: dev.uid) } else { let inputDevices = AVAudioSession.sharedInstance().currentRoute.inputs if inputDevices.isNotEmpty { for device in inputDevices { let dataSourceString = device.selectedDataSource?.description ?? "" let id = "\(device.uid) \(dataSourceString)".trimmingCharacters(in: [" "]) return AKDevice(name: device.portName, deviceID: id) } } } #endif return nil } /// The name of the current output device, if available. @objc open static var outputDevice: AKDevice? { #if os(macOS) if let dev = EZAudioDevice.currentOutput() { return AKDevice(name: dev.name, deviceID: dev.deviceID) } #else let devs = AVAudioSession.sharedInstance().currentRoute.outputs if devs.isNotEmpty { return AKDevice(name: devs[0].portName, deviceID: devs[0].uid) } #endif return nil } /// Change the preferred input device, giving it one of the names from the list of available inputs. @objc open static func setInputDevice(_ input: AKDevice) throws { #if os(macOS) var address = AudioObjectPropertyAddress( mSelector: kAudioHardwarePropertyDefaultInputDevice, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMaster) var devid = input.deviceID AudioObjectSetPropertyData( AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, UInt32(MemoryLayout<AudioDeviceID>.size), &devid) #else if let devices = AVAudioSession.sharedInstance().availableInputs { for device in devices { if device.dataSources == nil || device.dataSources!.isEmpty { if device.uid == input.deviceID { do { try AVAudioSession.sharedInstance().setPreferredInput(device) } catch { AKLog("Could not set the preferred input to \(input)") } } } else { for dataSource in device.dataSources! { if input.deviceID == "\(device.uid) \(dataSource.dataSourceName)" { do { try AVAudioSession.sharedInstance().setInputDataSource(dataSource) } catch { AKLog("Could not set the preferred input to \(input)") } } } } } } if let devices = AVAudioSession.sharedInstance().availableInputs { for dev in devices { if dev.uid == input.deviceID { do { try AVAudioSession.sharedInstance().setPreferredInput(dev) } catch { AKLog("Could not set the preferred input to \(input)") } } } } #endif } /// Change the preferred output device, giving it one of the names from the list of available output. @objc open static func setOutputDevice(_ output: AKDevice) throws { #if os(macOS) var id = output.deviceID if let audioUnit = AudioKit.engine.outputNode.audioUnit { AudioUnitSetProperty(audioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &id, UInt32(MemoryLayout<DeviceID>.size)) } #else //not available on ios #endif } // MARK: - Start/Stop /// Start up the audio engine with periodic functions open static func start(withPeriodicFunctions functions: AKPeriodicFunction...) { for function in functions { function.connect(to: finalMixer) } start() } /// Start up the audio engine @objc open static func start() { if output == nil { AKLog("AudioKit: No output node has been set yet, no processing will happen.") } // Start the engine. do { engine.prepare() #if os(iOS) if AKSettings.enableRouteChangeHandling { NotificationCenter.default.addObserver( self, selector: #selector(AudioKit.restartEngineAfterRouteChange), name: .AVAudioSessionRouteChange, object: nil) } if AKSettings.enableCategoryChangeHandling { NotificationCenter.default.addObserver( self, selector: #selector(AudioKit.restartEngineAfterConfigurationChange), name: .AVAudioEngineConfigurationChange, object: engine) } updateSessionCategoryAndOptions() try AVAudioSession.sharedInstance().setActive(true) #endif try engine.start() shouldBeRunning = true } catch { fatalError("AudioKit: Could not start engine. error: \(error).") } } @objc fileprivate static func updateSessionCategoryAndOptions() { #if !os(macOS) do { let sessionCategory = AKSettings.computedSessionCategory() let sessionOptions = AKSettings.computedSessionOptions() #if os(iOS) try AKSettings.setSession(category: sessionCategory, with: sessionOptions) #elseif os(tvOS) try AKSettings.setSession(category: sessionCategory) #endif } catch { fatalError("AudioKit: Could not update AVAudioSession category and options. error: \(error).") } #endif } /// Stop the audio engine @objc open static func stop() { // Stop the engine. engine.stop() shouldBeRunning = false #if os(iOS) do { try AVAudioSession.sharedInstance().setActive(false) } catch { AKLog("couldn't stop session \(error)") } #endif } // MARK: - Testing /// Testing AKNode @objc open static var tester: AKTester? /// Test the output of a given node /// /// - Parameters: /// - node: AKNode to test /// - duration: Number of seconds to test (accurate to the sample) /// @objc open static func test(node: AKNode, duration: Double, afterStart: () -> Void = {}) { #if swift(>=3.2) if #available(iOS 11, macOS 10.13, tvOS 11, *) { let samples = Int(duration * AKSettings.sampleRate) tester = AKTester(node, samples: samples) output = tester do { // maximum number of frames the engine will be asked to render in any single render call let maxNumberOfFrames: AVAudioFrameCount = 4_096 engine.reset() try engine.enableManualRenderingMode(.offline, format: format, maximumFrameCount: maxNumberOfFrames) try engine.start() } catch { fatalError("could not enable manual rendering mode, \(error)") } afterStart() tester?.play() let buffer: AVAudioPCMBuffer = AVAudioPCMBuffer(pcmFormat: engine.manualRenderingFormat, frameCapacity: engine.manualRenderingMaximumFrameCount)! while engine.manualRenderingSampleTime < samples { do { let framesToRender = buffer.frameCapacity let status = try engine.renderOffline(framesToRender, to: buffer) switch status { case .success: // data rendered successfully break case .insufficientDataFromInputNode: // applicable only if using the input node as one of the sources break case .cannotDoInCurrentContext: // engine could not render in the current render call, retry in next iteration break case .error: // error occurred while rendering fatalError("render failed") } } catch { fatalError("render failed, \(error)") } } tester?.stop() } #endif } /// Audition the test to hear what it sounds like /// /// - Parameters: /// - node: AKNode to test /// - duration: Number of seconds to test (accurate to the sample) /// @objc open static func auditionTest(node: AKNode, duration: Double) { output = node start() if let playableNode = node as? AKToggleable { playableNode.play() } usleep(UInt32(duration * 1_000_000)) stop() start() } // MARK: - Configuration Change Response // Listen to changes in audio configuration // and restart the audio engine if it stops and should be playing @objc fileprivate static func restartEngineAfterConfigurationChange(_ notification: Notification) { DispatchQueue.main.async { if shouldBeRunning && !engine.isRunning { do { #if !os(macOS) let appIsNotActive = UIApplication.shared.applicationState != .active let appDoesNotSupportBackgroundAudio = !AKSettings.appSupportsBackgroundAudio if appIsNotActive && appDoesNotSupportBackgroundAudio { AKLog("engine not restarted after configuration change since app was not active and does not support background audio") return } #endif try engine.start() // Sends notification after restarting the engine, so it is safe to resume AudioKit functions. if AKSettings.notificationsEnabled { NotificationCenter.default.post( name: .AKEngineRestartedAfterConfigurationChange, object: nil, userInfo: notification.userInfo) } } catch { AKLog("couldn't start engine after configuration change \(error)") } } } } // Restarts the engine after audio output has been changed, like headphones plugged in. @objc fileprivate static func restartEngineAfterRouteChange(_ notification: Notification) { DispatchQueue.main.async { if shouldBeRunning && !engine.isRunning { do { #if !os(macOS) let appIsNotActive = UIApplication.shared.applicationState != .active let appDoesNotSupportBackgroundAudio = !AKSettings.appSupportsBackgroundAudio if appIsNotActive && appDoesNotSupportBackgroundAudio { AKLog("engine not restarted after route change since app was not active and does not support background audio") return } #endif try engine.start() // Sends notification after restarting the engine, so it is safe to resume AudioKit functions. if AKSettings.notificationsEnabled { NotificationCenter.default.post( name: .AKEngineRestartedAfterRouteChange, object: nil, userInfo: notification.userInfo) } } catch { AKLog("error restarting engine after route change") } } } } // MARK: - Disconnect node inputs /// Disconnect all inputs @objc open static func disconnectAllInputs() { engine.disconnectNodeInput(finalMixer.avAudioNode) } // MARK: - Deinitialization deinit { #if os(iOS) NotificationCenter.default.removeObserver( self, name: .AKEngineRestartedAfterRouteChange, object: nil) #endif } } //This extension makes connect calls shorter, and safer by attaching nodes if not already attached. extension AudioKit { // Attaches nodes if node.engine == nil private static func safeAttach(_ nodes: [AVAudioNode]) { _ = nodes.filter { $0.engine == nil }.map { engine.attach($0) } } // AVAudioMixer will crash if engine is started and connection is made to a bus exceeding mixer's // numberOfInputs. The crash only happens when using the AVAudioEngine function that connects a node to an array // of AVAudioConnectionPoints and the mixer is one of those points. When AVAudioEngine uses a different function // that connects a node's output to a single AVAudioMixerNode, the mixer's inputs are incremented to accommodate // the new connection. So the workaround is to create dummy nodes, make a connections to the mixer using the // function that makes the mixer create new inputs, then remove the dummy nodes so that there is an available // bus to connect to. // private static func checkMixerInputs(_ connectionPoints: [AVAudioConnectionPoint]) { if !engine.isRunning { return } for connection in connectionPoints { if let mixer = connection.node as? AVAudioMixerNode, connection.bus >= mixer.numberOfInputs { var dummyNodes = [AVAudioNode]() while connection.bus >= mixer.numberOfInputs { let dummyNode = AVAudioUnitSampler() dummyNode.setOutput(to: mixer) dummyNodes.append(dummyNode) } for dummyNode in dummyNodes { dummyNode.disconnectOutput() } } } } // If an AVAudioMixerNode's output connection is made while engine is running, and there are no input connections // on the mixer, subsequent connections made to the mixer will silently fail. A workaround is to connect a dummy // node to the mixer prior to making a connection, then removing the dummy node after the connection has been made. // private static func addDummyOnEmptyMixer(_ node: AVAudioNode) -> AVAudioNode? { func mixerHasInputs(_ mixer: AVAudioMixerNode) -> Bool { for i in 0..<mixer.numberOfInputs { if engine.inputConnectionPoint(for: mixer, inputBus: i) != nil { return true } } return false } // Only an issue if engine is running, node is a mixer, and mixer has no inputs guard let mixer = node as? AVAudioMixerNode, engine.isRunning, !mixerHasInputs(mixer) else { return nil } let dummy = AVAudioUnitSampler() engine.attach(dummy) engine.connect(dummy, to: mixer, format: AudioKit.format) return dummy } @objc open static func connect(_ sourceNode: AVAudioNode, to destNodes: [AVAudioConnectionPoint], fromBus sourceBus: AVAudioNodeBus, format: AVAudioFormat?) { let connectionsWithNodes = destNodes.filter { $0.node != nil } safeAttach([sourceNode] + connectionsWithNodes.map { $0.node! }) // See addDummyOnEmptyMixer for dummyNode explanation. let dummyNode = addDummyOnEmptyMixer(sourceNode) checkMixerInputs(connectionsWithNodes) engine.connect(sourceNode, to: connectionsWithNodes, fromBus: sourceBus, format: format) dummyNode?.disconnectOutput() } @objc open static func connect(_ node1: AVAudioNode, to node2: AVAudioNode, fromBus bus1: AVAudioNodeBus, toBus bus2: AVAudioNodeBus, format: AVAudioFormat?) { safeAttach([node1, node2]) // See addDummyOnEmptyMixer for dummyNode explanation. let dummyNode = addDummyOnEmptyMixer(node1) engine.connect(node1, to: node2, fromBus: bus1, toBus: bus2, format: format) dummyNode?.disconnectOutput() } @objc open static func connect(_ node1: AVAudioNode, to node2: AVAudioNode, format: AVAudioFormat?) { connect(node1, to: node2, fromBus: 0, toBus: 0, format: format) } //Convenience @objc open static func detach(nodes: [AVAudioNode]) { for node in nodes { engine.detach(node) } } /// Render output to an AVAudioFile for a duration. /// - Parameters /// - audioFile: An file initialized for writing /// - seconds: Duration to render /// - prerender: A closure called before rendering starts, use this to start players, set initial parameters, etc... /// @available(iOS 11, macOS 10.13, tvOS 11, *) @objc open static func renderToFile(_ audioFile: AVAudioFile, seconds: Double, prerender: (() -> Void)? = nil) throws { try engine.renderToFile(audioFile, seconds: seconds, prerender: prerender) } } extension AVAudioEngine { /// Adding connection between nodes with default format open func connect(_ node1: AVAudioNode, to node2: AVAudioNode) { connect(node1, to: node2, format: AudioKit.format) } /// Render output to an AVAudioFile for a duration. /// - Parameters /// - audioFile: An file initialized for writing /// - seconds: Duration to render /// - prerender: A closure called before rendering starts, use this to start players, set initial parameters, etc... /// @available(iOS 11.0, macOS 10.13, tvOS 11.0, *) public func renderToFile(_ audioFile: AVAudioFile, seconds: Double, prerender: (() -> Void)? = nil) throws { guard seconds >= 0 else { throw NSError.init(domain: "AVAudioEngine ext", code: 1, userInfo: [NSLocalizedDescriptionKey:"Seconds needs to be a positive value"]) } // Engine can't be running when switching to offline render mode. if isRunning { stop() } try enableManualRenderingMode(.offline, format: audioFile.processingFormat, maximumFrameCount: 4096) // This resets the sampleTime of offline rendering to 0. reset() try start() guard let buffer = AVAudioPCMBuffer(pcmFormat: manualRenderingFormat, frameCapacity: manualRenderingMaximumFrameCount) else { throw NSError.init(domain: "AVAudioEngine ext", code: 1, userInfo: [NSLocalizedDescriptionKey:"Couldn't creat buffer in renderToFile"]) } // This is for users to prepare the nodes for playing, i.e player.play() prerender?() // Render until file contains >= target samples let targetSamples = AVAudioFramePosition(seconds * manualRenderingFormat.sampleRate) while audioFile.framePosition < targetSamples { let framesToRender = min(buffer.frameCapacity, AVAudioFrameCount( targetSamples - audioFile.framePosition)) let status = try renderOffline(framesToRender, to: buffer) switch status { case .success: try audioFile.write(from: buffer) case .cannotDoInCurrentContext: print("renderToFile cannotDoInCurrentContext") continue case .error, .insufficientDataFromInputNode: throw NSError.init(domain: "AVAudioEngine ext", code: 1, userInfo: [NSLocalizedDescriptionKey:"renderToFile render error"]) } } stop() disableManualRenderingMode() } }
16cf066cead6679a3499716f621347a7
38.3021
147
0.559191
false
false
false
false
PureSwift/Cacao
refs/heads/develop
Sources/Cacao/UIViewContentMode.swift
mit
1
// // UIViewContentMode.swift // Cacao // // Created by Alsey Coleman Miller on 5/31/16. // Copyright © 2016 PureSwift. All rights reserved. // #if os(macOS) import Darwin.C.math #elseif os(Linux) import Glibc #endif import Foundation import Silica public enum UIViewContentMode: Int { public init() { self = .scaleToFill } case scaleToFill case scaleAspectFit case scaleAspectFill case redraw case center case top case bottom case left case right case topLeft case topRight case bottomLeft case bottomRight } // MARK: - Internal Cacao Extension internal extension UIViewContentMode { func rect(for bounds: CGRect, size: CGSize) -> CGRect { switch self { case .redraw: fallthrough case .scaleToFill: return CGRect(origin: .zero, size: bounds.size) case .scaleAspectFit: let widthRatio = bounds.width / size.width let heightRatio = bounds.height / size.height var newSize = bounds.size if (widthRatio < heightRatio) { newSize.height = bounds.size.width / size.width * size.height } else if (heightRatio < widthRatio) { newSize.width = bounds.size.height / size.height * size.width } newSize = CGSize(width: ceil(newSize.width), height: ceil(newSize.height)) var origin = bounds.origin origin.x += (bounds.size.width - newSize.width) / 2.0 origin.y += (bounds.size.height - newSize.height) / 2.0 return CGRect(origin: origin, size: newSize) case .scaleAspectFill: let widthRatio = (bounds.size.width / size.width) let heightRatio = (bounds.size.height / size.height) var newSize = bounds.size if (widthRatio > heightRatio) { newSize.height = bounds.size.width / size.width * size.height } else if (heightRatio > widthRatio) { newSize.width = bounds.size.height / size.height * size.width } newSize = CGSize(width: ceil(newSize.width), height: ceil(newSize.height)) var origin = CGPoint() origin.x = (bounds.size.width - newSize.width) / 2.0 origin.y = (bounds.size.height - newSize.height) / 2.0 return CGRect(origin: origin, size: newSize) case .center: var rect = CGRect(origin: .zero, size: size) rect.origin.x = (bounds.size.width - rect.size.width) / 2.0 rect.origin.y = (bounds.size.height - rect.size.height) / 2.0 return rect case .top: var rect = CGRect(origin: .zero, size: size) rect.origin.y = 0.0 rect.origin.x = (bounds.size.width - rect.size.width) / 2.0 return rect case .bottom: var rect = CGRect(origin: .zero, size: size) rect.origin.x = (bounds.size.width - rect.size.width) / 2.0 rect.origin.y = bounds.size.height - rect.size.height return rect case .left: var rect = CGRect(origin: .zero, size: size) rect.origin.x = 0.0 rect.origin.y = (bounds.size.height - rect.size.height) / 2.0 return rect case .right: var rect = CGRect(origin: .zero, size: size) rect.origin.x = bounds.size.width - rect.size.width rect.origin.y = (bounds.size.height - rect.size.height) / 2.0 return rect case .topLeft: return CGRect(origin: .zero, size: size) case .topRight: var rect = CGRect(origin: .zero, size: size) rect.origin.x = bounds.size.width - rect.size.width rect.origin.y = 0.0 return rect case .bottomLeft: var rect = CGRect(origin: .zero, size: size) rect.origin.x = 0.0 rect.origin.y = bounds.size.height - rect.size.height return rect case .bottomRight: var rect = CGRect(origin: .zero, size: size) rect.origin.x = bounds.size.width - rect.size.width rect.origin.y = bounds.size.height - rect.size.height return rect } } }
f6029cd3fe6efa33c30e922269d39a8f
27.772727
86
0.484795
false
false
false
false
gluecode/ImagePickerSheetStoryBoard
refs/heads/master
photoSheetTest/ViewController.swift
mit
1
// // ViewController.swift // photoSheetTest // // Created by Sunil Karkera on 5/22/15. // import UIKit import Photos import ImagePickerSheet class ViewController: UIViewController, ImagePickerSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var photoButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onPhotoButton(sender: AnyObject) { let sheet = ImagePickerSheet() sheet.numberOfButtons = 3 sheet.delegate = self sheet.showInView(view) } func imagePickerSheet(imagePickerSheet: ImagePickerSheet, titleForButtonAtIndex buttonIndex: Int) -> String { let photosSelected = (imagePickerSheet.selectedPhotos.count > 0) if (buttonIndex == 0) { if photosSelected { return NSLocalizedString("Add comment", comment: "Add comment") } else { return NSLocalizedString("Take Photo Or Video", comment: "Take Photo Or Video") } } else { if photosSelected { return NSString.localizedStringWithFormat(NSLocalizedString("ImagePickerSheet.button1.Send %lu Photo", comment: "The secondary title of the image picker sheet to send the photos"), imagePickerSheet.selectedPhotos.count) } else { return NSLocalizedString("Photo Library", comment: "Photo Library") } } } func imagePickerSheet(imagePickerSheet: ImagePickerSheet, willDismissWithButtonIndex buttonIndex: Int) { if buttonIndex != imagePickerSheet.cancelButtonIndex { if imagePickerSheet.selectedPhotos.count > 0 { println(imagePickerSheet.selectedPhotos) } else { let controller = UIImagePickerController() controller.delegate = self controller.sourceType = (buttonIndex == 2) ? .PhotoLibrary : .Camera presentViewController(controller, animated: true, completion: nil) } } } }
174dbe77f545e2794e725f08a9d17cb5
34
235
0.636134
false
false
false
false
MinMao-Hub/MMActionSheet
refs/heads/master
Sources/MMActionSheet/MMActionSheet.swift
mit
1
// // MMActionSheet.swift // swiftui // // Created by 郭永红 on 2017/10/9. // Copyright © 2017年 keeponrunning. All rights reserved. // import UIKit public class MMActionSheet: UIView { /// MMSelectionClosure public typealias MMSelectionClosure = (_ item: MMButtonItem?) -> Void /// SelectionClosure public var selectionClosure: MMSelectionClosure? /// top cornerRadius public var topCornerRadius: CGFloat = 0 /// Parmeters private var title: MMTitleItem? private var buttons: [MMButtonItem] = [] private var duration: Double? private var cancelButton: MMButtonItem? /// Constants private struct Constants { /// 按钮与按钮之间的分割线高度 static let mmdivideLineHeight: CGFloat = 1 /// 屏幕Bounds static let mmscreenBounds = UIScreen.main.bounds /// 屏幕大小 static let mmscreenSize = UIScreen.main.bounds.size /// 屏幕宽度 static let mmscreenWidth = mmscreenBounds.width /// 屏幕高度 static let mmscreenHeight = mmscreenBounds.height /// button高度 static let mmbuttonHeight: CGFloat = 48.0 * mmscreenBounds.width / 375 /// 标题的高度 static let mmtitleHeight: CGFloat = 40.0 * mmscreenBounds.width / 375 /// 取消按钮与其他按钮之间的间距 static let mmbtnPadding: CGFloat = 5 * mmscreenBounds.width / 375 /// mmdefaultDuration static let mmdefaultDuration = 0.25 /// sheet的最大高度 static let mmmaxHeight = mmscreenHeight * 0.62 /// 适配iphoneX static let paddng_bottom: CGFloat = MMTools.isIphoneX ? 34.0 : 0.0 } /// ActionSheet private var actionSheetView: UIView = UIView() private var actionSheetHeight: CGFloat = 0 public var actionSheetViewBackgroundColor: UIColor? = MMTools.DefaultColor.backgroundColor /// scrollView private var scrollView: UIScrollView = UIScrollView() public var buttonBackgroundColor: UIColor? /// Init override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 初始化 /// /// - Parameters: /// - title: 标题 /// - buttons: 按钮数组 /// - duration: 动画时长 /// - cancel: 是否需要取消按钮 public convenience init( title: MMTitleItem?, buttons: [MMButtonItem], duration: Double?, cancelButton: MMButtonItem? ) { /// 半透明背景 self.init(frame: Constants.mmscreenBounds) self.title = title self.buttons = buttons self.duration = duration ?? Constants.mmdefaultDuration self.cancelButton = cancelButton /// 添加单击事件,隐藏sheet let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTapDismiss)) singleTap.delegate = self addGestureRecognizer(singleTap) /// actionSheet initActionSheet() /// 初始化UI initUI() } func initActionSheet() { let btnCount = buttons.count var tHeight: CGFloat = 0.0 if title != nil { tHeight = Constants.mmtitleHeight } var cancelHeight: CGFloat = 0.0 if cancelButton != nil { cancelHeight = Constants.mmbuttonHeight + Constants.mmbtnPadding } let contentHeight = CGFloat(btnCount) * Constants.mmbuttonHeight + CGFloat(btnCount) * Constants.mmdivideLineHeight let height = min(contentHeight, Constants.mmmaxHeight - tHeight - cancelHeight) scrollView.frame = CGRect(x: 0, y: tHeight, width: Constants.mmscreenWidth, height: height) actionSheetView.addSubview(scrollView) actionSheetHeight = tHeight + height + cancelHeight + Constants.paddng_bottom let aFrame: CGRect = CGRect(x: 0, y: Constants.mmscreenHeight, width: Constants.mmscreenWidth, height: actionSheetHeight) actionSheetView.frame = aFrame addSubview(actionSheetView) /// 根据内容高度计算动画时长 duration = duration ?? (Constants.mmdefaultDuration * Double(actionSheetHeight / 216)) } func initUI() { /// setTitleView setTitleView() /// setButtons setButtons() /// Cancel Button setCancelButton() /// setExtraView setExtraView() } /// Title private func setTitleView() { /// 标题不为空,则添加标题 if title != nil { let titleFrame = CGRect(x: 0, y: 0, width: Constants.mmscreenWidth, height: Constants.mmtitleHeight) let titlelabel = UILabel(frame: titleFrame) titlelabel.text = title!.text titlelabel.textAlignment = title!.textAlignment! titlelabel.textColor = title!.textColor titlelabel.font = title!.textFont titlelabel.backgroundColor = title!.backgroundColor?.rawValue actionSheetView.addSubview(titlelabel) } } /// Buttons private func setButtons() { let contentHeight = CGFloat(buttons.count) * Constants.mmbuttonHeight + CGFloat(buttons.count) * Constants.mmdivideLineHeight let view = UIView(frame: CGRect(x: 0, y: 0, width: Constants.mmscreenWidth, height: contentHeight)) view.clipsToBounds = true scrollView.addSubview(view) scrollView.contentSize = CGSize(width: Constants.mmscreenWidth, height: contentHeight) let buttonsCount = buttons.count for index in 0 ..< buttonsCount { let item = buttons[index] let origin_y = Constants.mmbuttonHeight * CGFloat(index) + Constants.mmdivideLineHeight * CGFloat(index) let button = MMButton(type: .custom) button.frame = CGRect(x: 0.0, y: origin_y, width: Constants.mmscreenWidth, height: Constants.mmbuttonHeight) /// Button Item button.item = item button.addTarget(self, action: #selector(actionClick), for: .touchUpInside) view.addSubview(button) } } /// ExtraView private func setExtraView() { guard MMTools.isIphoneX else { return } let frame = CGRect(x: 0, y: self.actionSheetView.bounds.size.height - Constants.paddng_bottom, width: Constants.mmscreenWidth, height: Constants.paddng_bottom) let extraView = UIView() extraView.frame = frame if cancelButton != nil { extraView.backgroundColor = cancelButton?.backgroudImageColorNormal?.rawValue } else { let bgColor = buttons.first?.backgroudImageColorNormal?.rawValue extraView.backgroundColor = bgColor } self.actionSheetView.addSubview(extraView) } /// Cancel Button private func setCancelButton() { /// 如果取消为ture则添加取消按钮 if cancelButton != nil { let button = MMButton(type: .custom) button.frame = CGRect(x: 0, y: actionSheetView.bounds.size.height - Constants.mmbuttonHeight - Constants.paddng_bottom, width: Constants.mmscreenWidth, height: Constants.mmbuttonHeight) button.item = cancelButton button.addTarget(self, action: #selector(actionClick), for: .touchUpInside) actionSheetView.addSubview(button) } } private func updateTopCornerMask() { guard topCornerRadius > 0 else { return } let shape = CAShapeLayer() let path = UIBezierPath(roundedRect: actionSheetView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: topCornerRadius, height: topCornerRadius)) shape.path = path.cgPath shape.frame = actionSheetView.bounds actionSheetView.layer.mask = shape } /// 修改样式 override public func layoutSubviews() { super.layoutSubviews() /// 顶部圆角 updateTopCornerMask() } } //MARK: Event extension MMActionSheet { /// items action @objc func actionClick(button: MMButton) { dismiss() guard let item = button.item else { return } /// Callback selectionClosure?(item) } //tap action @objc func singleTapDismiss() { dismiss() /// Callback selectionClosure?(nil) } } //MARK: present, dismiss extension MMActionSheet { /// 显示 public func present() { if #available(iOS 13.0, *) { if let keyWindow = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first { keyWindow.addSubview(self) } } else { UIApplication.shared.keyWindow?.addSubview(self) } UIView.animate(withDuration: 0.1, animations: { [self] in /// backgroundColor self.actionSheetView.backgroundColor = actionSheetViewBackgroundColor }) { (_: Bool) in UIView.animate(withDuration: self.duration!) { self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.3) self.actionSheetView.transform = CGAffineTransform(translationX: 0, y: -self.actionSheetView.frame.size.height) } } } /// 隐藏 func dismiss() { UIView.animate(withDuration: duration!, animations: { self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) self.actionSheetView.transform = .identity }) { (_: Bool) in self.removeFromSuperview() } } } // MARK: - UIGestureRecognizerDelegate extension MMActionSheet: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard touch.view == actionSheetView else { return true } return false } }
d6d39f108841ffd3006e9aebfaaea68c
33.179577
197
0.629855
false
false
false
false
CoderJChen/SWWB
refs/heads/master
CJWB/CJWB/Classes/Profile/Tools/category/UITextView-Extension.swift
apache-2.0
1
// // UITextView-Extension.swift // CJWB // // Created by 星驿ios on 2017/9/14. // Copyright © 2017年 CJ. All rights reserved. // import UIKit extension UITextView{ /// 获取textView属性字符串,对应的表情字符串 func getEmotionString() -> String{ // 1、获取属性字符串 let attrMStr = NSMutableAttributedString(attributedString: attributedText) // 2、遍历属性字符串 let range = NSRange(location: 0, length: attrMStr.length) attrMStr.enumerateAttributes(in: range, options: []) { (dict, range, _) in if let attachment = dict["NSAttachment"] as? CJEmotionAttachment{ attrMStr.replaceCharacters(in: range, with: attachment.chs!) } } // 3、获取字符串 return attrMStr.string } // 给textView插入表情 func insertEmotion(emotion : CJEmotionModel){ // 1、空白表情 if emotion.isEmpty { return } // 2、删除按钮 if emotion.isRemove { return } // 3、emoji表情 if emotion.emojiCode != nil { // 3.1 获取光标所在位置:UITextView let textRange = selectedTextRange // 3.2 替换emoji表情 replace(textRange!, withText: emotion.emojiCode!) return } // 4、普通表情:图文混排 // 4.1根据图片路径创建属性字符串 let attachment = CJEmotionAttachment() attachment.chs = emotion.chs attachment.image = UIImage(contentsOfFile: emotion.pngPath!) let font = self.font! attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight) let attrImageStr = NSAttributedString(attachment: attachment) // 4.2 创建可变的属性字符串你 let attrMStr = NSMutableAttributedString(attributedString: attributedText) // 4.3 将图片属性字符串,替换到可变属性字符串的某一个位置 // 4.3.1 获取光标所在位置 let range = selectedRange // 4.3.2 替换属性字符串 attrMStr.replaceCharacters(in: range, with: attrImageStr) // 显示属性字符串 attributedText = attrMStr // 将文字的大小重置 self.font = font // 将光标设置回原来的位置+1 selectedRange = NSRange(location: range.location + 1, length: 0) } }
8de8b79008721b0539d050d17643c251
29.166667
96
0.587477
false
false
false
false
arvedviehweger/swift
refs/heads/master
test/attr/attr_objc_swift3_deprecated.swift
apache-2.0
3
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 3 -warn-swift3-objc-inference // REQUIRES: objc_interop import Foundation class ObjCSubclass : NSObject { func foo() { } // expected-warning{{inference of '@objc' for members of Objective-C-derived classes is deprecated}} // expected-note@-1{{add `@objc` to continue exposing an Objective-C entry point (Swift 3 behavior)}}{{3-3=@objc }} // expected-note@-2{{add `@nonobjc` to suppress the Objective-C entry point (Swift 4 behavior)}}{{3-3=@nonobjc }} var bar: NSObject? = nil // expected-warning{{inference of '@objc' for members of Objective-C-derived classes is deprecated}} // expected-note@-1{{add `@objc` to continue exposing an Objective-C entry point (Swift 3 behavior)}}{{3-3=@objc }} // expected-note@-2{{add `@nonobjc` to suppress the Objective-C entry point (Swift 4 behavior)}}{{3-3=@nonobjc }} } class DynamicMembers { dynamic func foo() { } // expected-warning{{inference of '@objc' for 'dynamic' members is deprecated}}{{3-3=@objc }} dynamic var bar: NSObject? = nil // expected-warning{{inference of '@objc' for 'dynamic' members is deprecated}}{{3-3=@objc }} } // Suppress diagnostices about references to inferred @objc declarations // in this mode. func test(sc: ObjCSubclass, dm: DynamicMembers) { _ = #selector(sc.foo) _ = #selector(getter: dm.bar) _ = #keyPath(DynamicMembers.bar) }
b0fecef20c754f73946111b50dbfa053
51.071429
143
0.701646
false
false
false
false
dawsonbotsford/MobileAppsFall2015
refs/heads/master
iOS/lab7/lab7/ViewController.swift
mit
1
// // ViewController.swift // lab7 // // Created by Dawson Botsford on 10/15/15. // Copyright © 2015 Dawson Botsford. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate{ var audioPlayer: AVAudioPlayer? var audioRecorder: AVAudioRecorder? let fileName = "audio.caf" @IBOutlet weak var recordButton: UIButton! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var stopButton: UIButton! @IBAction func recordAction(sender: AnyObject) { if audioRecorder?.recording == false { playButton.enabled = false stopButton.enabled = true audioRecorder?.record() } } @IBAction func playAction(sender: AnyObject) { if audioRecorder?.recording == false{ stopButton.enabled = true recordButton.enabled = false do { audioPlayer = try AVAudioPlayer(contentsOfURL: (audioRecorder?.url)!) audioPlayer?.delegate = self audioPlayer?.play() } catch let error { print("AVAudioPlayer error: \(error)") } } } @IBAction func stopAction(sender: AnyObject) { stopButton.enabled = false playButton.enabled = true recordButton.enabled = true if audioRecorder?.recording == true { audioRecorder?.stop() } else { audioPlayer?.stop() } } override func viewDidLoad() { playButton.enabled = false stopButton.enabled = false let dirPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let docDir = dirPath[0] let audioFilePath = docDir.stringByAppendingString(fileName) let audioFileURL = NSURL(fileURLWithPath: audioFilePath) let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue, AVEncoderBitRateKey: 16, AVNumberOfChannelsKey: 2, AVSampleRateKey: 44100.0] let error: NSError! //audioRecorder = AVAudioRecorder(URL: <#T##NSURL#>, settings: <#T##[String : AnyObject]#>), do { audioRecorder=try AVAudioRecorder(URL: audioFileURL, settings: recordSettings as! [String : AnyObject]) audioRecorder?.delegate = self audioRecorder?.meteringEnabled = true audioRecorder?.prepareToRecord() } catch let error { audioRecorder = nil print(error) } //audioRecorder = AVAudioRecorder(URL: audioFileURL, settings: recordSettings as! [String: AnyObject], error: &error) /* if let err = error { print("AVAudioRecorder error: \(err.localizedDescription)") } else { audioRecorder?.delegate = self audioRecorder?.prepareToRecord() }*/ super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
3f5e22a210e080a54b40e26c52e503f3
30.266055
161
0.598005
false
false
false
false
JaSpa/swift
refs/heads/master
test/SILGen/toplevel.swift
apache-2.0
4
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s func markUsed<T>(_ t: T) {} func trap() -> Never { fatalError() } // CHECK-LABEL: sil @main // CHECK: bb0({{%.*}} : $Int32, {{%.*}} : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): // -- initialize x // CHECK: alloc_global @_T08toplevel1xSiv // CHECK: [[X:%[0-9]+]] = global_addr @_T08toplevel1xSiv : $*Int // CHECK: integer_literal $Builtin.Int2048, 999 // CHECK: store {{.*}} to [trivial] [[X]] var x = 999 func print_x() { markUsed(x) } // -- assign x // CHECK: integer_literal $Builtin.Int2048, 0 // CHECK: assign {{.*}} to [[X]] // CHECK: [[PRINT_X:%[0-9]+]] = function_ref @_T08toplevel7print_xyyF : // CHECK: apply [[PRINT_X]] x = 0 print_x() // <rdar://problem/19770775> Deferred initialization of let bindings rejected at top level in playground // CHECK: alloc_global @_T08toplevel5countSiv // CHECK: [[COUNTADDR:%[0-9]+]] = global_addr @_T08toplevel5countSiv : $*Int // CHECK-NEXT: [[COUNTMUI:%[0-9]+]] = mark_uninitialized [var] [[COUNTADDR]] : $*Int let count: Int // CHECK: cond_br if x == 5 { count = 0 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE:bb[0-9]+]] } else { count = 10 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE]] } // CHECK: [[MERGE]]: // CHECK: load [trivial] [[COUNTMUI]] markUsed(count) var y : Int func print_y() { markUsed(y) } // -- assign y // CHECK: alloc_global @_T08toplevel1ySiv // CHECK: [[Y1:%[0-9]+]] = global_addr @_T08toplevel1ySiv : $*Int // CHECK: [[Y:%[0-9]+]] = mark_uninitialized [var] [[Y1]] // CHECK: assign {{.*}} to [[Y]] // CHECK: [[PRINT_Y:%[0-9]+]] = function_ref @_T08toplevel7print_yyyF y = 1 print_y() // -- treat 'guard' vars as locals // CHECK-LABEL: function_ref toplevel.A.__allocating_init // CHECK: switch_enum {{%.+}} : $Optional<A>, case #Optional.some!enumelt.1: [[SOME_CASE:.+]], default // CHECK: [[SOME_CASE]]([[VALUE:%.+]] : $A): // CHECK: store [[VALUE]] to [init] [[BOX:%.+]] : $*A // CHECK-NOT: destroy_value // CHECK: [[SINK:%.+]] = function_ref @_T08toplevel8markUsedyxlF // CHECK-NOT: destroy_value // CHECK: apply [[SINK]]<A>({{%.+}}) class A {} guard var a = Optional(A()) else { trap() } markUsed(a) // CHECK: alloc_global @_T08toplevel21NotInitializedIntegerSiv // CHECK-NEXT: [[VARADDR:%[0-9]+]] = global_addr @_T08toplevel21NotInitializedIntegerSiv // CHECK-NEXT: [[VARMUI:%[0-9]+]] = mark_uninitialized [var] [[VARADDR]] : $*Int // CHECK-NEXT: mark_function_escape [[VARMUI]] : $*Int // <rdar://problem/21753262> Bug in DI when it comes to initialization of global "let" variables let NotInitializedInteger : Int func fooUsesUninitializedValue() { _ = NotInitializedInteger } fooUsesUninitializedValue() NotInitializedInteger = 10 fooUsesUninitializedValue() // CHECK: [[RET:%[0-9]+]] = struct $Int32 // CHECK: return [[RET]] // CHECK-LABEL: sil hidden @_T08toplevel7print_xyyF // CHECK-LABEL: sil hidden @_T08toplevel7print_yyyF // CHECK: sil hidden @_T08toplevel13testGlobalCSESiyF // CHECK-NOT: global_addr // CHECK: %0 = global_addr @_T08toplevel1xSiv : $*Int // CHECK-NOT: global_addr // CHECK: return func testGlobalCSE() -> Int { // We should only emit one global_addr in this function. return x + x }
135b0b659ad91c018f41bfb8a2b92032
25.766129
119
0.639349
false
false
false
false
dxdp/Stage
refs/heads/master
Stage/PropertyBindings/UITextViewBindings.swift
mit
1
// // UITextViewBindings.swift // Stage // // Copyright © 2016 David Parton // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies // or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation public extension StageRegister { public class func TextView(_ registration: StagePropertyRegistration) { tap(registration) { $0.register("font") { scanner in try UIFont.create(using: scanner, defaultPointSize: 14) } .apply { (view: UITextView, value) in view.font = value } $0.register("keyboardType") { scanner in try UIKeyboardType.create(using: scanner) } .apply { (view: UITextView, value) in view.keyboardType = value } $0.register("text") { scanner in scanner.scanLinesTrimmed().joined(separator: "\n") } .apply { (view: UITextView, value) in view.text = value } $0.register("textAlignment") { scanner in try NSTextAlignment.create(using: scanner) } .apply { (view: UITextView, value) in view.textAlignment = value } $0.registerColor("textColor") .apply { (view: UITextView, value) in view.textColor = value } $0.register("textContainerInset") { scanner in try UIEdgeInsets.create(using: scanner) } .apply { (view: UITextView, value) in view.textContainerInset = value } $0.register("inputAccessoryView") { scanner in scanner.string.trimmed() } .apply { (view: UITextView, value, context) in guard let accessoryView = try? context.view(named: value) else { print("Warning. inputAccessoryView '\(value)' for UITextView not present in the StageLiveContext") return } if let superview = accessoryView.superview { accessoryView.removeFromSuperview() superview.setNeedsUpdateConstraints() } view.inputAccessoryView = accessoryView DispatchQueue.main.async { let size = accessoryView.systemLayoutSizeFitting(UIScreen.main.bounds.size) let frame = accessoryView.frame accessoryView.frame = CGRect(origin: frame.origin, size: size) } } } } }
f4f3f331100fe05da47440ed2cdb85a8
54
122
0.627859
false
false
false
false
zzeleznick/piazza-clone
refs/heads/master
Pizzazz/Pizzazz/ClassInfoViewCell.swift
mit
1
// // ClassInfoViewCell.swift // Pizzazz // // Created by Zach Zeleznick on 5/6/16. // Copyright © 2016 zzeleznick. All rights reserved. // import Foundation import UIKit class ClassInfoViewCell: UITableViewCell { var w: CGFloat! var lines: [String]! { willSet(values) { for (idx, name) in values.enumerated() { let label = UILabel() let font = UIFont(name: "Helvetica", size: 12) label.font = font let y:CGFloat = 22*CGFloat(idx) + 5.0 let labelFrame = CGRect(x: 25, y: y, width: w-25, height: 20) contentView.addUIElement(label, text: name, frame: labelFrame) { _ in // print("Adding \(name)") } } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) w = UIScreen.main.bounds.size.width } required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } }
63b83507a28167f58ac80cc1728b54c8
27.333333
85
0.558371
false
false
false
false
apple/swift-experimental-string-processing
refs/heads/main
Sources/_StringProcessing/Engine/MEBuiltins.swift
apache-2.0
1
@_implementationOnly import _RegexParser // For AssertionKind extension Character { var _isHorizontalWhitespace: Bool { self.unicodeScalars.first?.isHorizontalWhitespace == true } var _isNewline: Bool { self.unicodeScalars.first?.isNewline == true } } extension Processor { mutating func matchBuiltin( _ cc: _CharacterClassModel.Representation, _ isInverted: Bool, _ isStrictASCII: Bool, _ isScalarSemantics: Bool ) -> Bool { guard let next = _doMatchBuiltin( cc, isInverted, isStrictASCII, isScalarSemantics ) else { signalFailure() return false } currentPosition = next return true } func _doMatchBuiltin( _ cc: _CharacterClassModel.Representation, _ isInverted: Bool, _ isStrictASCII: Bool, _ isScalarSemantics: Bool ) -> Input.Index? { guard let char = load(), let scalar = loadScalar() else { return nil } let asciiCheck = (char.isASCII && !isScalarSemantics) || (scalar.isASCII && isScalarSemantics) || !isStrictASCII var matched: Bool var next: Input.Index switch (isScalarSemantics, cc) { case (_, .anyGrapheme): next = input.index(after: currentPosition) case (_, .anyScalar): next = input.unicodeScalars.index(after: currentPosition) case (true, _): next = input.unicodeScalars.index(after: currentPosition) case (false, _): next = input.index(after: currentPosition) } switch cc { case .any, .anyGrapheme: matched = true case .anyScalar: if isScalarSemantics { matched = true } else { matched = input.isOnGraphemeClusterBoundary(next) } case .digit: if isScalarSemantics { matched = scalar.properties.numericType != nil && asciiCheck } else { matched = char.isNumber && asciiCheck } case .horizontalWhitespace: if isScalarSemantics { matched = scalar.isHorizontalWhitespace && asciiCheck } else { matched = char._isHorizontalWhitespace && asciiCheck } case .verticalWhitespace: if isScalarSemantics { matched = scalar.isNewline && asciiCheck } else { matched = char._isNewline && asciiCheck } case .newlineSequence: if isScalarSemantics { matched = scalar.isNewline && asciiCheck if matched && scalar == "\r" && next != input.endIndex && input.unicodeScalars[next] == "\n" { // Match a full CR-LF sequence even in scalar semantics input.unicodeScalars.formIndex(after: &next) } } else { matched = char._isNewline && asciiCheck } case .whitespace: if isScalarSemantics { matched = scalar.properties.isWhitespace && asciiCheck } else { matched = char.isWhitespace && asciiCheck } case .word: if isScalarSemantics { matched = scalar.properties.isAlphabetic && asciiCheck } else { matched = char.isWordCharacter && asciiCheck } } if isInverted { matched.toggle() } guard matched else { return nil } return next } func isAtStartOfLine(_ payload: AssertionPayload) -> Bool { if currentPosition == subjectBounds.lowerBound { return true } switch payload.semanticLevel { case .graphemeCluster: return input[input.index(before: currentPosition)].isNewline case .unicodeScalar: return input.unicodeScalars[input.unicodeScalars.index(before: currentPosition)].isNewline } } func isAtEndOfLine(_ payload: AssertionPayload) -> Bool { if currentPosition == subjectBounds.upperBound { return true } switch payload.semanticLevel { case .graphemeCluster: return input[currentPosition].isNewline case .unicodeScalar: return input.unicodeScalars[currentPosition].isNewline } } mutating func builtinAssert(by payload: AssertionPayload) throws -> Bool { // Future work: Optimize layout and dispatch switch payload.kind { case .startOfSubject: return currentPosition == subjectBounds.lowerBound case .endOfSubjectBeforeNewline: if currentPosition == subjectBounds.upperBound { return true } switch payload.semanticLevel { case .graphemeCluster: return input.index(after: currentPosition) == subjectBounds.upperBound && input[currentPosition].isNewline case .unicodeScalar: return input.unicodeScalars.index(after: currentPosition) == subjectBounds.upperBound && input.unicodeScalars[currentPosition].isNewline } case .endOfSubject: return currentPosition == subjectBounds.upperBound case .resetStartOfMatch: fatalError("Unreachable, we should have thrown an error during compilation") case .firstMatchingPositionInSubject: return currentPosition == searchBounds.lowerBound case .textSegment: return input.isOnGraphemeClusterBoundary(currentPosition) case .notTextSegment: return !input.isOnGraphemeClusterBoundary(currentPosition) case .startOfLine: return isAtStartOfLine(payload) case .endOfLine: return isAtEndOfLine(payload) case .caretAnchor: if payload.anchorsMatchNewlines { return isAtStartOfLine(payload) } else { return currentPosition == subjectBounds.lowerBound } case .dollarAnchor: if payload.anchorsMatchNewlines { return isAtEndOfLine(payload) } else { return currentPosition == subjectBounds.upperBound } case .wordBoundary: if payload.usesSimpleUnicodeBoundaries { // TODO: How should we handle bounds? return atSimpleBoundary(payload.usesASCIIWord, payload.semanticLevel) } else { return input.isOnWordBoundary(at: currentPosition, using: &wordIndexCache, &wordIndexMaxIndex) } case .notWordBoundary: if payload.usesSimpleUnicodeBoundaries { // TODO: How should we handle bounds? return !atSimpleBoundary(payload.usesASCIIWord, payload.semanticLevel) } else { return !input.isOnWordBoundary(at: currentPosition, using: &wordIndexCache, &wordIndexMaxIndex) } } } }
129418879857af965b071324356a57c5
29.642157
103
0.664694
false
false
false
false
iOSDevLog/iOSDevLog
refs/heads/master
169. Camera/Camera/GLPreviewViewController.swift
mit
1
// // GLPreviewViewController.swift // Camera // // Created by Matteo Caldari on 28/01/15. // Copyright (c) 2015 Matteo Caldari. All rights reserved. // import UIKit import GLKit import CoreImage import OpenGLES class GLPreviewViewController: UIViewController, CameraPreviewViewController, CameraFramesDelegate { var cameraController:CameraController? { didSet { cameraController?.framesDelegate = self } } private var glContext:EAGLContext? private var ciContext:CIContext? private var renderBuffer:GLuint = GLuint() private var filter = CIFilter(name:"CIPhotoEffectMono") private var glView:GLKView { get { return view as! GLKView } } override func loadView() { self.view = GLKView() } override func viewDidLoad() { super.viewDidLoad() glContext = EAGLContext(API: .OpenGLES2) glView.context = glContext! glView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) if let window = glView.window { glView.frame = window.bounds } ciContext = CIContext(EAGLContext: glContext!) } // MARK: CameraControllerDelegate func cameraController(cameraController: CameraController, didOutputImage image: CIImage) { if glContext != EAGLContext.currentContext() { EAGLContext.setCurrentContext(glContext) } glView.bindDrawable() filter!.setValue(image, forKey: "inputImage") let outputImage = filter!.outputImage ciContext?.drawImage(outputImage!, inRect:image.extent, fromRect: image.extent) glView.display() } }
d237288df9989992c3fd9a7d1546e2e9
20.323944
100
0.73646
false
false
false
false
techgrains/TGFramework-iOS
refs/heads/master
TGFrameworkExample/TGFrameworkExample/Classes/Controller/ServiceViewController.swift
apache-2.0
1
import UIKit import TGFramework class ServiceViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var serviceListTableView:UITableView! var serviceList = [Any]() override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.isHidden = false // self.navigationController?.navigationBar.barTintColor = UIColor(colorLiteralRed: 125/255, green: 194/255, blue: 66/255, alpha: 1) // self.navigationController?.navigationBar.tintColor = UIColor(colorLiteralRed: 24/255, green: 100/255, blue: 173/255, alpha: 1) // self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor(colorLiteralRed: 24/255, green: 100/255, blue: 173/255, alpha: 1)] self.navigationController?.navigationBar.barTintColor = UIColor(colorLiteralRed: 24/255, green: 100/255, blue: 173/255, alpha: 1) self.navigationController?.navigationBar.tintColor = UIColor.white self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] /** * Add service name in list */ serviceList.append(["Service Name": "Create Employee"]) serviceList.append(["Service Name": "Employee List"]) serviceList.append(["Service Name": "Employee List with Name"]) serviceListTableView.reloadData() serviceListTableView.tableFooterView = UIView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationItem.title = "Service List" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table Delegate /** * Render List of Service Name */ func numberOfSections(in aTableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return serviceList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell:UITableViewCell? cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell?.selectionStyle = UITableViewCellSelectionStyle.none let servicaNameDic = serviceList[indexPath.row] as! Dictionary<String, Any> cell?.textLabel?.text = servicaNameDic["Service Name"] as! String? cell?.textLabel?.textColor = UIColor(colorLiteralRed: 24/255, green: 100/255, blue: 173/255, alpha: 1) return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if(TGSession.isInternetAvailable()) { self.navigationItem.title = "Back" if (indexPath.row == 0) { let viewController = self.storyboard?.instantiateViewController(withIdentifier: "CreateEmployeeServiceVC") as! CreateEmployeeServiceViewController self.navigationController?.pushViewController(viewController, animated: true) } else if(indexPath.row == 1) { let viewController = self.storyboard?.instantiateViewController(withIdentifier: "EmployeeListVC") as! EmployeeListViewController self.navigationController?.pushViewController(viewController, animated: true) } else if(indexPath.row == 2) { let viewController = self.storyboard?.instantiateViewController(withIdentifier: "FilterEmployeeListVC") as! FilterEmployeeListViewController self.navigationController?.pushViewController(viewController, animated: true) } } else { TGUtil.showAlertView("Sorry", message: "Internet is not reachable.") } } }
b36c953dc736a1c8af90dcd16d4f52c4
46.158537
180
0.682441
false
false
false
false
chen392356785/DouyuLive
refs/heads/master
DouyuLive/DouyuLive/Classes/Tools/Extension/AnchorModel.swift
mit
1
// // AnchorModel.swift // DouyuLive // // Created by chenxiaolei on 2016/9/30. // Copyright © 2016年 chenxiaolei. All rights reserved. // import UIKit class AnchorModel: NSObject { /// 房间ID var room_id : Int = 0 /// 房间图片对应的URLString var vertical_src : String = "" /// 判断是手机直播还是电脑直播 // 0 : 电脑直播 1 : 手机直播 var isVertical : Int = 0 /// 房间名称 var room_name : String = "" /// 主播昵称 var nickname : String = "" /// 观看人数 var online : Int = 0 /// 所在城市 var anchor_city : String = "" init(dict : [String : NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
a8bb8a90b203867b1914f649a5973cc6
19.361111
72
0.557981
false
false
false
false
omise/omise-ios
refs/heads/master
OmiseSDK/PaymentOptionTableViewCell.swift
mit
1
import UIKit class PaymentOptionTableViewCell: UITableViewCell { let separatorView = UIView() @IBInspectable var separatorHeight: CGFloat = 1 override init(style: TableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initializeInstance() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializeInstance() } private func initializeInstance() { addSubview(separatorView) let selectedBackgroundView = UIView() selectedBackgroundView.backgroundColor = UIColor.selectedCellBackgroundColor self.selectedBackgroundView = selectedBackgroundView } override func layoutSubviews() { super.layoutSubviews() contentView.frame.size.height = bounds.height - separatorHeight var separatorFrame = bounds if let textLabel = self.textLabel { let textLabelFrame = self.convert(textLabel.frame, from: contentView) (_, separatorFrame) = separatorFrame.divided(atDistance: textLabelFrame.minX, from: .minXEdge) } else { (_, separatorFrame) = separatorFrame.divided(atDistance: layoutMargins.left, from: .minXEdge) } separatorFrame.origin.y = bounds.height - separatorHeight separatorFrame.size.height = separatorHeight separatorView.frame = separatorFrame } }
e148ce19cffdf54e82764674c3f9e1dd
33.97619
106
0.675289
false
false
false
false
pksprojects/ElasticSwift
refs/heads/master
Sources/ElasticSwiftCore/ElasticSwiftCore.swift
mit
1
// // utils.swift // ElasticSwift // // Created by Prafull Kumar Soni on 6/18/17. // // import Foundation // MARK: - Serializer Protocol public protocol Serializer { func decode<T>(data: Data) -> Result<T, DecodingError> where T: Decodable func encode<T>(_ value: T) -> Result<Data, EncodingError> where T: Encodable } // MARK: - HTTPSettings public enum HTTPSettings { case managed(adaptorConfig: HTTPAdaptorConfiguration) case independent(adaptor: HTTPClientAdaptor) } // MARK: - ClientCredential public protocol ClientCredential { var token: String { get } } // MARK: - QueryParams enums /// Enum QueryParams represent all the query params supported by ElasticSearch. public enum QueryParams: String { case format case h case help case local case masterTimeout = "master_timeout" case s case v case ts case bytes case health case pri case fullId = "full_id" case size case ignoreUnavailable = "ignore_unavailable" case actions case detailed case nodeId = "node_id" case parentNode = "parent_node" case version case versionType = "version_type" case refresh case parentTask = "parent_task" case waitForActiveShards = "wait_for_active_shards" case waitForCompletion = "wait_for_completion" case opType = "op_type" case routing case timeout case ifSeqNo = "if_seq_no" case ifPrimaryTerm = "if_primary_term" case pipeline case includeTypeName = "include_type_name" case parent case retryOnConflict = "retry_on_conflict" case fields case lang case source = "_source" case sourceIncludes = "_source_includes" case sourceExcludes = "_source_excludes" case conflicts case requestsPerSecond = "requests_per_second" case slices case requestCache = "request_cache" case stats case from case scrollSize = "scroll_size" case realTime = "realtime" case preference case storedFields = "stored_fields" case termStatistics = "term_statistics" case fieldStatistics = "field_statistics" case offsets case positions case payloads case scroll case restTotalHitsAsInt = "rest_total_hits_as_int" case searchType = "search_type" case ignoreThrottled = "ignore_throttled" case allowNoIndices = "allow_no_indices" case expandWildcards = "expand_wildcards" case minScore = "min_score" case q case analyzer case analyzeWildcard = "analyze_wildcard" case defaultOperator = "default_operator" case df case lenient case terminateAfter = "terminate_after" case typedKeys = "typed_keys" case level case waitForNodes = "wait_for_nodes" case waitForEvents = "wait_for_events" case waitForNoRelocatingShards = "wait_for_no_relocating_shards" case waitForNoInitializingShards = "wait_for_no_initializing_shards" case waitForStatus = "wait_for_status" case flatSettings = "flat_settings" case includeDefaults = "include_defaults" } enum EndPointCategory: String { case cat = "_cat" case cluster = "_cluster" case ingest = "_ingest" case nodes = "_nodes" case snapshots = "_snapshots" case tasks = "_tasks" } enum EndPointPath: String { case aliases case allocation case count case health case indices case master case nodes case recovery case shards case segments case pendingTasks = "pending_tasks" case threadPool = "thread_pool" case fieldData = "fielddata" case plugins case nodeAttributes = "nodeattrs" case repositories case snapshots case tasks case templates case state case stats case reroute case settings case allocationExplain = "allocation/explain" case pipeline case simulate case hotThreads = "hotthreads" case restore = "_recovery" case status = "_status" case verify = "_verify" case `default` = "" } /// Enum representing URLScheme public enum URLScheme: String { case http case https } /// Generic protocol for Type Builders in ElasticSwift public protocol ElasticSwiftTypeBuilder { associatedtype ElasticSwiftType func build() throws -> ElasticSwiftType }
12ee3b80f7432b288f1b987e616bfb91
24.279762
80
0.68519
false
false
false
false
WalterCreazyBear/Swifter30
refs/heads/master
DotDemo/DotDemo/ViewController.swift
mit
1
// // ViewController.swift // DotDemo // // Created by Bear on 2017/6/29. // Copyright © 2017年 Bear. All rights reserved. // import UIKit class ViewController: UIViewController { var dotOne : UIImageView! var dotTwo : UIImageView! var dotThree : UIImageView! lazy var logoImage : UIImageView = { let view : UIImageView = UIImageView(frame: CGRect.init(x: 0, y: 50, width: UIScreen.main.bounds.width, height: 100)) view.image = #imageLiteral(resourceName: "logo") view.contentMode = .scaleAspectFit return view }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white // view.addSubview(logoImage) dotOne = generateImgeView(frame: CGRect.init(x: 50, y: 150, width: 30, height: 30)) dotTwo = generateImgeView(frame: CGRect.init(x: 90, y: 150, width: 30, height: 30)) dotThree = generateImgeView(frame: CGRect.init(x: 130, y: 150, width: 30, height: 30)) view.addSubview(dotOne) view.addSubview(dotTwo) view.addSubview(dotThree) startAnimation() } func startAnimation() { dotOne.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) dotTwo.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) dotThree.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) UIView.animate(withDuration: 0.6, delay: 0.0, options: [.repeat, .autoreverse], animations: { self.dotOne.transform = CGAffineTransform.identity }, completion: nil) UIView.animate(withDuration: 0.6, delay: 0.2, options: [.repeat, .autoreverse], animations: { self.dotTwo.transform = CGAffineTransform.identity }, completion: nil) UIView.animate(withDuration: 0.6, delay: 0.4, options: [.repeat, .autoreverse], animations: { self.dotThree.transform = CGAffineTransform.identity }, completion: nil) } func generateImgeView(frame:CGRect) -> UIImageView { let view : UIImageView = UIImageView(frame: frame) view.image = #imageLiteral(resourceName: "dot") view.contentMode = .scaleAspectFit return view } }
7e35cc10e3b8c06f7b9bdd2784a4a77f
33.242424
125
0.626991
false
false
false
false
deyton/swift
refs/heads/master
stdlib/public/core/Character.swift
apache-2.0
4
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A single extended grapheme cluster that approximates a user-perceived /// character. /// /// The `Character` type represents a character made up of one or more Unicode /// scalar values, grouped by a Unicode boundary algorithm. Generally, a /// `Character` instance matches what the reader of a string will perceive as /// a single character. Strings are collections of `Character` instances, so /// the number of visible characters is generally the most natural way to /// count the length of a string. /// /// let greeting = "Hello! 🐥" /// print("Length: \(greeting.count)") /// // Prints "Length: 8" /// /// Because each character in a string can be made up of one or more Unicode /// code points, the number of characters in a string may not match the length /// of the Unicode code point representation or the length of the string in a /// particular binary representation. /// /// print("Unicode code point count: \(greeting.unicodeScalars.count)") /// // Prints "Unicode code point count: 15" /// /// print("UTF-8 representation count: \(greeting.utf8.count)") /// // Prints "UTF-8 representation count: 18" /// /// Every `Character` instance is composed of one or more Unicode code points /// that are grouped together as an *extended grapheme cluster*. The way these /// code points are grouped is defined by a canonical, localized, or otherwise /// tailored Unicode segmentation algorithm. /// /// For example, a country's Unicode flag character is made up of two regional /// indicator code points that correspond to that country's ISO 3166-1 alpha-2 /// code. The alpha-2 code for The United States is "US", so its flag /// character is made up of the Unicode code points `"\u{1F1FA}"` (REGIONAL /// INDICATOR SYMBOL LETTER U) and `"\u{1F1F8}"` (REGIONAL INDICATOR SYMBOL /// LETTER S). When placed next to each other in a Swift string literal, these /// two code points are combined into a single grapheme cluster, represented /// by a `Character` instance in Swift. /// /// let usFlag: Character = "\u{1F1FA}\u{1F1F8}" /// print(usFlag) /// // Prints "🇺🇸" /// /// For more information about the Unicode terms used in this discussion, see /// the [Unicode.org glossary][glossary]. In particular, this discussion /// mentions [extended grapheme clusters][clusters] and [Unicode scalar /// values][scalars]. /// /// [glossary]: http://www.unicode.org/glossary/ /// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster /// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value @_fixed_layout public struct Character : _ExpressibleByBuiltinUTF16ExtendedGraphemeClusterLiteral, ExpressibleByExtendedGraphemeClusterLiteral, Hashable { // Fundamentally, it is just a String, but it is optimized for the common case // where the UTF-16 representation fits in 63 bits. The remaining bit is used // to discriminate between small and large representations. Since a grapheme // cluster cannot have U+0000 anywhere but in its first scalar, we can store // zero in empty code units above the first one. @_versioned internal enum Representation { case smallUTF16(Builtin.Int63) case large(_StringBuffer._Storage) } /// Creates a character containing the given Unicode scalar value. /// /// - Parameter content: The Unicode scalar value to convert into a character. public init(_ content: Unicode.Scalar) { let content16 = UTF16.encode(content)._unsafelyUnwrappedUnchecked _representation = .smallUTF16( Builtin.zext_Int32_Int63(content16._storage._value)) } @effects(readonly) public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = Character( String._fromWellFormedCodeUnitSequence( UTF32.self, input: CollectionOfOne(UInt32(value)))) } // Inlining ensures that the whole constructor can be folded away to a single // integer constant in case of small character literals. @inline(__always) @effects(readonly) public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { let utf8 = UnsafeBufferPointer( start: UnsafePointer<Unicode.UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount)) if utf8.count == 1 { _representation = .smallUTF16( Builtin.zext_Int8_Int63(utf8.first._unsafelyUnwrappedUnchecked._value)) return } FastPath: repeat { var shift = 0 let maxShift = 64 - 16 var bits: UInt64 = 0 for s8 in Unicode._ParsingIterator( codeUnits: utf8.makeIterator(), parser: UTF8.ForwardParser()) { let s16 = UTF16.transcode(s8, from: UTF8.self)._unsafelyUnwrappedUnchecked for u16 in s16 { guard _fastPath(shift <= maxShift) else { break FastPath } bits |= UInt64(u16) &<< shift shift += 16 } } guard _fastPath(Int64(truncatingIfNeeded: bits) >= 0) else { break FastPath } _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) return } while false // For anything that doesn't fit in 63 bits, build the large // representation. self = Character(_largeRepresentationString: String( _builtinExtendedGraphemeClusterLiteral: start, utf8CodeUnitCount: utf8CodeUnitCount, isASCII: isASCII)) } // Inlining ensures that the whole constructor can be folded away to a single // integer constant in case of small character literals. @inline(__always) @effects(readonly) public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word ) { let utf16 = UnsafeBufferPointer( start: UnsafePointer<Unicode.UTF16.CodeUnit>(start), count: Int(utf16CodeUnitCount)) switch utf16.count { case 1: _representation = .smallUTF16(Builtin.zext_Int16_Int63(utf16[0]._value)) case 2: let bits = UInt32(utf16[0]) | UInt32(utf16[1]) &<< 16 _representation = .smallUTF16(Builtin.zext_Int32_Int63(bits._value)) case 3: let bits = UInt64(utf16[0]) | UInt64(utf16[1]) &<< 16 | UInt64(utf16[2]) &<< 32 _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) case 4 where utf16[3] < 0x8000: let bits = UInt64(utf16[0]) | UInt64(utf16[1]) &<< 16 | UInt64(utf16[2]) &<< 32 | UInt64(utf16[3]) &<< 48 _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) default: _representation = Character( _largeRepresentationString: String( _StringCore( baseAddress: UnsafeMutableRawPointer(start), count: utf16.count, elementShift: 1, hasCocoaBuffer: false, owner: nil) ))._representation } } /// Creates a character with the specified value. /// /// Do not call this initalizer directly. It is used by the compiler when /// you use a string literal to initialize a `Character` instance. For /// example: /// /// let oBreve: Character = "o\u{306}" /// print(oBreve) /// // Prints "ŏ" /// /// The assignment to the `oBreve` constant calls this initializer behind the /// scenes. public init(extendedGraphemeClusterLiteral value: Character) { self = value } /// Creates a character from a single-character string. /// /// The following example creates a new character from the uppercase version /// of a string that only holds one character. /// /// let a = "a" /// let capitalA = Character(a.uppercased()) /// /// - Parameter s: The single-character string to convert to a `Character` /// instance. `s` must contain exactly one extended grapheme cluster. public init(_ s: String) { _precondition( s._core.count != 0, "Can't form a Character from an empty String") _debugPrecondition( s.index(after: s.startIndex) == s.endIndex, "Can't form a Character from a String containing more than one extended grapheme cluster") if _fastPath(s._core.count <= 4) { let b = _UIntBuffer<UInt64, Unicode.UTF16.CodeUnit>(s._core) if _fastPath(Int64(truncatingIfNeeded: b._storage) >= 0) { _representation = .smallUTF16( Builtin.trunc_Int64_Int63(b._storage._value)) return } } self = Character(_largeRepresentationString: s) } /// Creates a Character from a String that is already known to require the /// large representation. /// /// - Note: `s` should contain only a single grapheme, but we can't require /// that formally because of grapheme cluster literals and the shifting /// sands of Unicode. https://bugs.swift.org/browse/SR-4955 @_versioned internal init(_largeRepresentationString s: String) { if let native = s._core.nativeBuffer, native.start == s._core._baseAddress!, native.usedCount == s._core.count { _representation = .large(native._storage) return } var nativeString = "" nativeString.append(s) _representation = .large(nativeString._core.nativeBuffer!._storage) } static func _smallValue(_ value: Builtin.Int63) -> UInt64 { return UInt64(Builtin.zext_Int63_Int64(value)) } /// The character's hash value. /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. public var hashValue: Int { // FIXME(performance): constructing a temporary string is extremely // wasteful and inefficient. return String(self).hashValue } typealias UTF16View = String.UTF16View var utf16: UTF16View { return String(self).utf16 } @_versioned internal var _representation: Representation } extension Character : CustomStringConvertible { public var description: String { return String(describing: self) } } extension Character : LosslessStringConvertible {} extension Character : CustomDebugStringConvertible { /// A textual representation of the character, suitable for debugging. public var debugDescription: String { return String(self).debugDescription } } extension Character { @_versioned internal var _smallUTF16 : _UIntBuffer<UInt64, Unicode.UTF16.CodeUnit>? { guard case .smallUTF16(let _63bits) = _representation else { return nil } _onFastPath() let bits = UInt64(Builtin.zext_Int63_Int64(_63bits)) let minBitWidth = type(of: bits).bitWidth - bits.leadingZeroBitCount return _UIntBuffer<UInt64, Unicode.UTF16.CodeUnit>( _storage: bits, _bitCount: UInt8( truncatingIfNeeded: 16 * Swift.max(1, (minBitWidth + 15) / 16)) ) } @_versioned internal var _largeUTF16 : _StringCore? { guard case .large(let storage) = _representation else { return nil } return _StringCore(_StringBuffer(storage)) } } extension String { /// Creates a string containing the given character. /// /// - Parameter c: The character to convert to a string. public init(_ c: Character) { if let utf16 = c._smallUTF16 { self = String(decoding: utf16, as: Unicode.UTF16.self) } else { self = String(c._largeUTF16!) } } } /// `.small` characters are stored in an Int63 with their UTF-8 representation, /// with any unused bytes set to 0xFF. ASCII characters will have all bytes set /// to 0xFF except for the lowest byte, which will store the ASCII value. Since /// 0x7FFFFFFFFFFFFF80 or greater is an invalid UTF-8 sequence, we know if a /// value is ASCII by checking if it is greater than or equal to /// 0x7FFFFFFFFFFFFF00. internal var _minASCIICharReprBuiltin: Builtin.Int63 { @inline(__always) get { let x: Int64 = 0x7FFFFFFFFFFFFF00 return Builtin.truncOrBitCast_Int64_Int63(x._value) } } extension Character : Equatable { @_inlineable @inline(__always) public static func == (lhs: Character, rhs: Character) -> Bool { let l0 = lhs._smallUTF16 if _fastPath(l0 != nil), let l = l0?._storage { let r0 = rhs._smallUTF16 if _fastPath(r0 != nil), let r = r0?._storage { if (l | r) < 0x300 { return l == r } if l == r { return true } } } // FIXME(performance): constructing two temporary strings is extremely // wasteful and inefficient. return String(lhs) == String(rhs) } } extension Character : Comparable { @_inlineable @inline(__always) public static func < (lhs: Character, rhs: Character) -> Bool { let l0 = lhs._smallUTF16 if _fastPath(l0 != nil), let l = l0?._storage { let r0 = rhs._smallUTF16 if _fastPath(r0 != nil), let r = r0?._storage { if (l | r) < 0x80 { return l < r } if l == r { return false } } } // FIXME(performance): constructing two temporary strings is extremely // wasteful and inefficient. return String(lhs) < String(rhs) } }
d047a84b68e7b29b258c04844f4d3cd0
34.944149
96
0.665557
false
false
false
false
markedwardmurray/Precipitate
refs/heads/master
Pods/SwiftySettings/Source/UI/OptionButtonCell.swift
mit
2
// // SettingsOptionButtonCell.swift // // SwiftySettings // Created by Tomasz Gebarowski on 07/08/15. // Copyright © 2015 codica Tomasz Gebarowski <gebarowski at gmail.com>. // All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import UIKit class OptionsButtonCell : SettingsCell { let selectedOptionLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupViews() } override func updateConstraints() { if !didSetupConstraints { selectedOptionLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addConstraints([ // Spacing Between Title and Selected UILabel NSLayoutConstraint(item: selectedOptionLabel, attribute: .Left, relatedBy: .GreaterThanOrEqual, toItem: textLabel!, attribute: .Right, multiplier: 1.0, constant: 15), // Selected Option UILabel - Horizontal Constraints NSLayoutConstraint(item: contentView, attribute: .Trailing, relatedBy: .Equal, toItem: selectedOptionLabel, attribute: .Trailing, multiplier: 1.0, constant: 5), // Selected Option UILabel - Vertical Constraints NSLayoutConstraint(item: contentView, attribute: .CenterY, relatedBy: .Equal, toItem: selectedOptionLabel, attribute: .CenterY, multiplier: 1.0, constant: 0) ]) } super.updateConstraints() } override func setupViews() { super.setupViews() textLabel?.setContentHuggingPriority(UILayoutPriorityDefaultHigh, forAxis: .Horizontal) selectedOptionLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh, forAxis: .Horizontal) contentView.addSubview(selectedOptionLabel) } override func configureAppearance() { super.configureAppearance() textLabel?.textColor = appearance?.cellTextColor selectedOptionLabel.textColor = appearance?.cellSecondaryTextColor contentView.backgroundColor = appearance?.cellBackgroundColor accessoryView?.backgroundColor = appearance?.cellBackgroundColor } func load(item: OptionsButton) { self.textLabel?.text = item.title self.selectedOptionLabel.text = item.selectedOptionTitle self.accessoryType = .DisclosureIndicator if let image = item.icon { self.imageView?.image = image } configureAppearance() setNeedsUpdateConstraints() } }
8755cfbaedd90670697dce8b47cd7e4c
38.54955
96
0.605377
false
false
false
false
rwash8347/desktop-apod
refs/heads/master
DesktopAPOD/DesktopAPOD/URLSession-Extension.swift
mit
1
// // URLSession-Extension.swift // APODDesktopImage // // Created by Richard Ash on 3/28/17. // Copyright © 2017 Richard. All rights reserved. // import Foundation enum URLSessionError: Error { case unknown(URLResponse?) } extension URLSession { func dataTask(with url: URL, completion: @escaping (Result<Data>) -> Void) -> URLSessionDataTask { return self.dataTask(with: url) { (data, response, error) in if let error = error, data == nil { completion(.failure(error)) } else if let data = data, error == nil { completion(.success(data)) } else { completion(.failure(URLSessionError.unknown(response))) } } } }
91448bf3fc72972a424c7199d04f8781
24.259259
100
0.646628
false
false
false
false
Bunn/macGist
refs/heads/master
macGist/LoginViewController.swift
mit
1
// // LoginViewController.swift // macGist // // Created by Fernando Bunn on 20/06/17. // Copyright © 2017 Fernando Bunn. All rights reserved. // import Cocoa class LoginViewController: NSViewController { @IBOutlet private weak var passwordTextField: NSSecureTextField! @IBOutlet private weak var usernameTextField: NSTextField! @IBOutlet private weak var spinner: NSProgressIndicator! @IBOutlet private weak var loginButton: NSButton! @IBOutlet private weak var githubClientIdTextField: NSTextField! @IBOutlet private weak var githubClientSecretTextField: NSTextField! @IBOutlet weak var errorLabel: NSTextField! weak var delegate: LoginViewControllerDelegate? private let githubAPI = GitHubAPI() override func viewDidLoad() { super.viewDidLoad() setupUI() setupCredentialsUI() } @IBAction private func loginButtonClicked(_ sender: NSButton) { setupUI() authenticate() } @IBAction private func cancelButtonClicked(_ sender: NSButton) { delegate?.didFinish(controller: self) } @IBAction func saveButtonClicked(_ sender: NSButton) { GitHubCredentialManager.clientId = githubClientIdTextField.stringValue GitHubCredentialManager.clientSecret = githubClientSecretTextField.stringValue } fileprivate func setupUI() { spinner.isHidden = true errorLabel.isHidden = true } private func showSpinner(show: Bool) { spinner.isHidden = !show loginButton.isHidden = show if show { spinner.startAnimation(nil) } else { spinner.stopAnimation(nil) } } fileprivate func displayError(message: String) { showSpinner(show: false) errorLabel.isHidden = false errorLabel.stringValue = message } private func openTwoFactorController() { let twoFactorController = TwoFactorViewController() twoFactorController.delegate = self presentAsSheet(twoFactorController) } fileprivate func authenticate(twoFactorCode: String? = nil) { showSpinner(show: true) githubAPI.authenticate(username: usernameTextField.stringValue, password: passwordTextField.stringValue, twoFactorCode: twoFactorCode) { (error: Error?) in print("Error \(String(describing: error))") DispatchQueue.main.async { if error != nil { if let apiError = error as? GitHubAPI.GitHubAPIError { switch apiError { case .twoFactorRequired: self.openTwoFactorController() return default: break } } self.displayError(message: "Bad username or password") } else { UserDefaults.standard.set(self.usernameTextField.stringValue, forKey: UserDefaultKeys.usernameKey.rawValue) self.delegate?.didFinish(controller: self) } } } } private func setupCredentialsUI() { githubClientIdTextField.stringValue = GitHubCredentialManager.clientId ?? "" githubClientSecretTextField.stringValue = GitHubCredentialManager.clientSecret ?? "" } } protocol LoginViewControllerDelegate: class { func didFinish(controller: LoginViewController) } extension LoginViewController: TwoFactorViewControllerDelegate { func didEnter(code: String, controller: TwoFactorViewController) { authenticate(twoFactorCode: code) controller.dismiss(nil) } func didCancel(controller: TwoFactorViewController) { setupUI() displayError(message: "Two-Factor cancelled") controller.dismiss(nil) } }
d96a3d00652cd330457f08c07b8fb095
32.612069
163
0.640934
false
false
false
false
ben-ng/swift
refs/heads/master
stdlib/public/core/Zip.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 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 // //===----------------------------------------------------------------------===// /// Creates a sequence of pairs built out of two underlying sequences. /// /// In the `Zip2Sequence` instance returned by this function, the elements of /// the *i*th pair are the *i*th elements of each underlying sequence. The /// following example uses the `zip(_:_:)` function to iterate over an array /// of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// If the two sequences passed to `zip(_:_:)` are different lengths, the /// resulting sequence is the same length as the shorter sequence. In this /// example, the resulting array is the same length as `words`: /// /// let naturalNumbers = 1...Int.max /// let zipped = Array(zip(words, naturalNumbers)) /// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)] /// /// - Parameters: /// - sequence1: The first sequence or collection to zip. /// - sequence2: The second sequence or collection to zip. /// - Returns: A sequence of tuple pairs, where the elements of each pair are /// corresponding elements of `sequence1` and `sequence2`. public func zip<Sequence1 : Sequence, Sequence2 : Sequence>( _ sequence1: Sequence1, _ sequence2: Sequence2 ) -> Zip2Sequence<Sequence1, Sequence2> { return Zip2Sequence(_sequence1: sequence1, _sequence2: sequence2) } /// An iterator for `Zip2Sequence`. public struct Zip2Iterator< Iterator1 : IteratorProtocol, Iterator2 : IteratorProtocol > : IteratorProtocol { /// The type of element returned by `next()`. public typealias Element = (Iterator1.Element, Iterator2.Element) /// Creates an instance around a pair of underlying iterators. internal init(_ iterator1: Iterator1, _ iterator2: Iterator2) { (_baseStream1, _baseStream2) = (iterator1, iterator2) } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. public mutating func next() -> Element? { // The next() function needs to track if it has reached the end. If we // didn't, and the first sequence is longer than the second, then when we // have already exhausted the second sequence, on every subsequent call to // next() we would consume and discard one additional element from the // first sequence, even though next() had already returned nil. if _reachedEnd { return nil } guard let element1 = _baseStream1.next(), let element2 = _baseStream2.next() else { _reachedEnd = true return nil } return (element1, element2) } internal var _baseStream1: Iterator1 internal var _baseStream2: Iterator2 internal var _reachedEnd: Bool = false } /// A sequence of pairs built out of two underlying sequences. /// /// In a `Zip2Sequence` instance, the elements of the *i*th pair are the *i*th /// elements of each underlying sequence. To create a `Zip2Sequence` instance, /// use the `zip(_:_:)` function. /// /// The following example uses the `zip(_:_:)` function to iterate over an /// array of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// - SeeAlso: `zip(_:_:)` public struct Zip2Sequence<Sequence1 : Sequence, Sequence2 : Sequence> : Sequence { public typealias Stream1 = Sequence1.Iterator public typealias Stream2 = Sequence2.Iterator /// A type whose instances can produce the elements of this /// sequence, in order. public typealias Iterator = Zip2Iterator<Stream1, Stream2> @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator /// Creates an instance that makes pairs of elements from `sequence1` and /// `sequence2`. public // @testable init(_sequence1 sequence1: Sequence1, _sequence2 sequence2: Sequence2) { (_sequence1, _sequence2) = (sequence1, sequence2) } /// Returns an iterator over the elements of this sequence. public func makeIterator() -> Iterator { return Iterator( _sequence1.makeIterator(), _sequence2.makeIterator()) } internal let _sequence1: Sequence1 internal let _sequence2: Sequence2 } extension Zip2Sequence { @available(*, unavailable, message: "use zip(_:_:) free function instead") public init(_ sequence1: Sequence1, _ sequence2: Sequence2) { Builtin.unreachable() } }
ddf3c213c8c249c738de0998e7d4523f
35.175676
80
0.644565
false
false
false
false
Jaeandroid/actor-platform
refs/heads/master
actor-apps/app-ios/Actor/Controllers/User/UserViewController.swift
mit
31
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import UIKit class UserViewController: AATableViewController { private let UserInfoCellIdentifier = "UserInfoCellIdentifier" private let TitledCellIdentifier = "TitledCellIdentifier" let uid: Int var user: AMUserVM? var phones: JavaUtilArrayList? var binder = Binder() var tableData: UATableData! init(uid: Int) { self.uid = uid super.init(style: UITableViewStyle.Plain) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - override func viewDidLoad() { super.viewDidLoad() user = MSG.getUserWithUid(jint(uid)) self.edgesForExtendedLayout = UIRectEdge.Top self.automaticallyAdjustsScrollViewInsets = false tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.backgroundColor = MainAppTheme.list.backyardColor tableView.clipsToBounds = false tableView.tableFooterView = UIView() tableData = UATableData(tableView: tableView) tableData.registerClass(UserPhotoCell.self, forCellReuseIdentifier: UserInfoCellIdentifier) tableData.registerClass(TitledCell.self, forCellReuseIdentifier: TitledCellIdentifier) tableData.tableScrollClosure = { (tableView: UITableView) -> () in self.applyScrollUi(tableView) } // Avatar tableData.addSection().addCustomCell { (tableView, indexPath) -> UITableViewCell in var cell: UserPhotoCell = tableView.dequeueReusableCellWithIdentifier(self.UserInfoCellIdentifier, forIndexPath: indexPath) as! UserPhotoCell cell.contentView.superview?.clipsToBounds = false if self.user != nil { cell.setUsername(self.user!.getNameModel().get()) } cell.setLeftInset(15.0) self.applyScrollUi(tableView, cell: cell) return cell }.setHeight(Double(avatarHeight)) // Send Message if (!user!.isBot().boolValue) { tableData.addSection() .addActionCell("ProfileSendMessage", actionClosure: { () -> () in self.navigateDetail(ConversationViewController(peer: AMPeer.userWithInt(jint(self.uid)))) self.popover?.dismissPopoverAnimated(true) }) .showTopSeparator(0) .showBottomSeparator(15) } // Phones tableData.addSection() .setFooterHeight(15) .addCustomCells(55, countClosure: { () -> Int in if (self.phones != nil) { return Int(self.phones!.size()) } return 0 }) { (tableView, index, indexPath) -> UITableViewCell in var cell: TitledCell = tableView.dequeueReusableCellWithIdentifier(self.TitledCellIdentifier, forIndexPath: indexPath) as! TitledCell cell.setLeftInset(15.0) if let phone = self.phones!.getWithInt(jint(index)) as? AMUserPhone { cell.setTitle(phone.getTitle(), content: "+\(phone.getPhone())") } cell.hideTopSeparator() cell.showBottomSeparator() var phonesCount = Int(self.phones!.size()); if index == phonesCount - 1 { cell.setBottomSeparatorLeftInset(0.0) } else { cell.setBottomSeparatorLeftInset(15.0) } return cell }.setAction { (index) -> () in var phoneNumber = (self.phones?.getWithInt(jint(index)).getPhone())! var hasPhone = UIApplication.sharedApplication().canOpenURL(NSURL(string: "tel://")!) if (!hasPhone) { UIPasteboard.generalPasteboard().string = "+\(phoneNumber)" self.alertUser("NumberCopied") } else { self.showActionSheet(["CallNumber", "CopyNumber"], cancelButton: "AlertCancel", destructButton: nil, sourceView: self.view, sourceRect: self.view.bounds, tapClosure: { (index) -> () in if (index == 0) { UIApplication.sharedApplication().openURL(NSURL(string: "tel://+\(phoneNumber)")!) } else if index == 1 { UIPasteboard.generalPasteboard().string = "+\(phoneNumber)" self.alertUser("NumberCopied") } }) } } tableData.addSection() .setHeaderHeight(15) .setFooterHeight(15) .addCommonCell { (cell) -> () in let peer = AMPeer.userWithInt(jint(self.uid)) cell.setSwitcherOn(MSG.isNotificationsEnabledWithPeer(peer)) cell.switchBlock = { (on: Bool) -> () in if !on && !self.user!.isBot().boolValue { self.confirmAlertUser("ProfileNotificationsWarring", action: "ProfileNotificationsWarringAction", tapYes: { () -> () in MSG.changeNotificationsEnabledWithPeer(peer, withValue: false) }, tapNo: { () -> () in cell.setSwitcherOn(true, animated: true) }) return } MSG.changeNotificationsEnabledWithPeer(peer, withValue: on) } } .setContent("ProfileNotifications") .setStyle(.Switch) var contactSection = tableData.addSection() .setHeaderHeight(15) .setFooterHeight(15) contactSection .addCommonCell { (cell) -> () in if (self.user!.isContactModel().get().booleanValue()) { cell.setContent(NSLocalizedString("ProfileRemoveFromContacts", comment: "Remove From Contacts")) cell.style = .Destructive } else { cell.setContent(NSLocalizedString("ProfileAddToContacts", comment: "Add To Contacts")) cell.style = .Blue } } .setAction { () -> () in if (self.user!.isContactModel().get().booleanValue()) { self.execute(MSG.removeContactCommandWithUid(jint(self.uid))) } else { self.execute(MSG.addContactCommandWithUid(jint(self.uid))) } } .hideBottomSeparator() // Rename contactSection .addActionCell("ProfileRename", actionClosure: { () -> () in if (!MSG.isRenameHintShown()) { self.confirmAlertUser("ProfileRenameMessage", action: "ProfileRenameAction", tapYes: { () -> () in self.renameUser() }) } else { self.renameUser() } }) .showTopSeparator(15) // Binding data tableView.reloadData() binder.bind(user!.getAvatarModel(), closure: { (value: AMAvatar?) -> () in if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell { cell.userAvatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), avatar: value) } }) binder.bind(user!.getNameModel(), closure: { ( name: String?) -> () in if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell { cell.setUsername(name!) } self.title = name! }) binder.bind(user!.getPresenceModel(), closure: { (presence: AMUserPresence?) -> () in var presenceText = MSG.getFormatter().formatPresence(presence, withSex: self.user!.getSex()) if presenceText != nil { if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell { cell.setPresence(presenceText) } } }) binder.bind(user!.getPhonesModel(), closure: { (phones: JavaUtilArrayList?) -> () in if phones != nil { self.phones = phones self.tableView.reloadData() } }) binder.bind(user!.isContactModel(), closure: { (contect: AMValueModel?) -> () in self.tableView.reloadSections(NSIndexSet(index: contactSection.index), withRowAnimation: UITableViewRowAnimation.None) }) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) applyScrollUi(tableView) navigationController?.navigationBar.shadowImage = UIImage() MSG.onProfileOpenWithUid(jint(uid)) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) MSG.onProfileClosedWithUid(jint(uid)) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) navigationController?.navigationBar.lt_reset() } func renameUser() { textInputAlert("ProfileEditHeader", content: self.user!.getNameModel().get(), action: "AlertSave", tapYes: { (nval) -> () in if count(nval) > 0 { self.execute(MSG.editNameCommandWithUid(jint(self.uid), withName: nval)) } }) } }
5d4842527b306682cd4bd7b1690937e0
39.876984
153
0.524609
false
false
false
false
EvsenevDev/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Modules/Columns/ColumnsInteractor.swift
agpl-3.0
2
// // ColumnsInteractor.swift // SmartReceipts // // Created by Bogdan Evsenev on 12/07/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import Foundation import Viperit import RxSwift class ColumnsInteractor: Interactor { func columns(forCSV: Bool) -> Observable<[Column]> { let columns = forCSV ? Database.sharedInstance().allCSVColumns() : Database.sharedInstance().allPDFColumns() for (idx, column) in columns!.enumerated() { let col = column as! Column col.uniqueIdentity = "\(idx)" } return Observable<[Column]>.just(columns as! [Column]) } func addColumn(_ column: Column, isCSV: Bool) { let db = Database.sharedInstance() let orderId = isCSV ? db.nextCustomOrderIdForCSVColumn() : db.nextCustomOrderIdForPDFColumn() column.customOrderId = orderId let result = isCSV ? db.addCSVColumn(column) : db.addPDFColumn(column) Logger.info("Add Column '\(column.name!)'. Result: \(result)") } func removeColumn(_ column: Column, isCSV: Bool) { let db = Database.sharedInstance() let result = isCSV ? db.removeCSVColumn(column) : db.removePDFColumn(column) Logger.info("Remove Column '\(column.name!)'. Result: \(result)") } func reorder(columnLeft: Column, columnRight: Column, isCSV: Bool) { let db = Database.sharedInstance() let result = isCSV ? db.reorderCSVColumn(columnLeft, withCSVColumn: columnRight) : db.reorderPDFColumn(columnLeft, withPDFColumn: columnRight) Logger.info("Reorder columns. Result: \(result)") } } // MARK: - VIPER COMPONENTS API (Auto-generated code) private extension ColumnsInteractor { var presenter: ColumnsPresenter { return _presenter as! ColumnsPresenter } }
4e730f1de5d9dc43ff9b8f517d80e278
34.576923
116
0.654595
false
false
false
false
anotheren/TrafficPolice
refs/heads/master
Source/TrafficManager.swift
mit
1
// // TrafficManager.swift // TrafficPolice // // Created by 刘栋 on 2016/11/17. // Copyright © 2016年 anotheren.com. All rights reserved. // import Foundation import SwiftTimer public class TrafficManager { public static let shared = TrafficManager() public private(set) var interval: Double public weak var delegate: TrafficManagerDelegate? private lazy var timer: SwiftTimer = { let timer = SwiftTimer.repeaticTimer(interval: .fromSeconds(self.interval)) {[weak self] timer in self?.updateSummary() } return timer }() private var counter: TrafficCounter = TrafficCounter() private var summary: TrafficSummary? private init(interval: Double = 1.0) { self.interval = interval } public func reset() { summary = nil } public func start() { timer.start() } public func cancel() { timer.suspend() } private func updateSummary() { let newSummary: TrafficSummary = { if let summary = self.summary { return summary.update(by: counter.usage, time: interval) } else { return TrafficSummary(origin: counter.usage) } }() delegate?.post(summary: newSummary) summary = newSummary } } public protocol TrafficManagerDelegate: class { func post(summary: TrafficSummary) }
10565fc7031ab68dd6472dd92fb58bec
22.126984
105
0.601235
false
false
false
false
RoverPlatform/rover-ios
refs/heads/master
Sources/Experiences/Extensions/DateFormatter.swift
apache-2.0
2
// // DateFormatter.swift // Rover // // Created by Sean Rucker on 2019-05-10. // Copyright © 2019 Rover Labs Inc. All rights reserved. // import Foundation extension DateFormatter { public static let rfc3339: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" formatter.calendar = Calendar(identifier: .iso8601) formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.locale = Locale(identifier: "en_US_POSIX") return formatter }() }
23c5eb359c9084e662829bf40bc1a4c8
26.75
63
0.668468
false
false
false
false
ilhanadiyaman/firefox-ios
refs/heads/master
Utils/Functions.swift
mpl-2.0
3
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // Pipelining. infix operator |> { associativity left } public func |> <T, U>(x: T, f: T -> U) -> U { return f(x) } // Basic currying. public func curry<A, B>(f: (A) -> B) -> A -> B { return { a in return f(a) } } public func curry<A, B, C>(f: (A, B) -> C) -> A -> B -> C { return { a in return { b in return f(a, b) } } } public func curry<A, B, C, D>(f: (A, B, C) -> D) -> A -> B -> C -> D { return { a in return { b in return { c in return f(a, b, c) } } } } public func curry<A, B, C, D, E>(f: (A, B, C, D) -> E) -> (A, B, C) -> D -> E { return { (a, b, c) in return { d in return f(a, b, c, d) } } } // Function composition. infix operator • {} public func •<T, U, V>(f: T -> U, g: U -> V) -> T -> V { return { t in return g(f(t)) } } public func •<T, V>(f: T -> (), g: () -> V) -> T -> V { return { t in f(t) return g() } } public func •<V>(f: () -> (), g: () -> V) -> () -> V { return { f() return g() } } // Why not simply provide an override for ==? Well, that's scary, and can accidentally recurse. // This is enough to catch arrays, which Swift will delegate to element-==. public func optArrayEqual<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool { switch (lhs, rhs) { case (.None, .None): return true case (.None, _): return false case (_, .None): return false default: // This delegates to Swift's own array '==', which calls T's == on each element. return lhs! == rhs! } } /** * Given an array, return an array of slices of size `by` (possibly excepting the last slice). * * If `by` is longer than the input, returns a single chunk. * If `by` is less than 1, acts as if `by` is 1. * If the length of the array isn't a multiple of `by`, the final slice will * be smaller than `by`, but never empty. * * If the input array is empty, returns an empty array. */ public func chunk<T>(arr: [T], by: Int) -> [ArraySlice<T>] { let count = arr.count let step = max(1, by) // Handle out-of-range 'by'. let s = 0.stride(to: count, by: step) return s.map { arr[$0..<$0.advancedBy(step, limit: count)] } } public func optDictionaryEqual<K: Equatable, V: Equatable>(lhs: [K: V]?, rhs: [K: V]?) -> Bool { switch (lhs, rhs) { case (.None, .None): return true case (.None, _): return false case (_, .None): return false default: return lhs! == rhs! } } /** * Return members of `a` that aren't nil, changing the type of the sequence accordingly. */ public func optFilter<T>(a: [T?]) -> [T] { return a.flatMap { $0 } } /** * Return a new map with only key-value pairs that have a non-nil value. */ public func optFilter<K, V>(source: [K: V?]) -> [K: V] { var m = [K: V]() for (k, v) in source { if let v = v { m[k] = v } } return m } /** * Map a function over the values of a map. */ public func mapValues<K, T, U>(source: [K: T], f: (T -> U)) -> [K: U] { var m = [K: U]() for (k, v) in source { m[k] = f(v) } return m } /** * Find the first matching item in the array and return it. * Unlike map/filter approaches, this is lazy. */ public func find<T>(arr: [T], f: T -> Bool) -> T? { for x in arr { if f(x) { return x } } return nil } public func findOneValue<K, V>(map: [K: V], f: V -> Bool) -> V? { for v in map.values { if f(v) { return v } } return nil } /** * Take a JSON array, returning the String elements as an array. * It's usually convenient for this to accept an optional. */ public func jsonsToStrings(arr: [JSON]?) -> [String]? { if let arr = arr { return optFilter(arr.map { j in return j.asString }) } return nil } // Encapsulate a callback in a way that we can use it with NSTimer. private class Callback { private let handler:()->() init(handler:()->()) { self.handler = handler } @objc func go() { handler() } } /** * Taken from http://stackoverflow.com/questions/27116684/how-can-i-debounce-a-method-call * Allows creating a block that will fire after a delay. Resets the timer if called again before the delay expires. **/ public func debounce(delay:NSTimeInterval, action:()->()) -> ()->() { let callback = Callback(handler: action) var timer: NSTimer? return { // If calling again, invalidate the last timer. if let timer = timer { timer.invalidate() } timer = NSTimer(timeInterval: delay, target: callback, selector: "go", userInfo: nil, repeats: false) NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSDefaultRunLoopMode) } }
e3736b153ebd84d7d024f11a797f2f49
23.652381
115
0.536025
false
false
false
false
AgaKhanFoundation/WCF-iOS
refs/heads/develop
Example/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift
apache-2.0
19
// // Driver+Subscription.swift // RxCocoa // // Created by Krunoslav Zaher on 9/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import RxRelay private let errorMessage = "`drive*` family of methods can be only called from `MainThread`.\n" + "This is required to ensure that the last replayed `Driver` element is delivered on `MainThread`.\n" extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { /** Creates new subscription and sends elements to observer. This method can be only called from `MainThread`. In this form it's equivalent to `subscribe` method, but it communicates intent better. - parameter observer: Observer that receives events. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public func drive<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) return self.asSharedSequence().asObservable().subscribe(observer) } /** Creates new subscription and sends elements to observer. This method can be only called from `MainThread`. In this form it's equivalent to `subscribe` method, but it communicates intent better. - parameter observer: Observer that receives events. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public func drive<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element? { MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) return self.asSharedSequence().asObservable().map { $0 as Element? }.subscribe(observer) } /** Creates new subscription and sends elements to `BehaviorRelay`. This method can be only called from `MainThread`. - parameter relay: Target relay for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func drive(_ relay: BehaviorRelay<Element>) -> Disposable { MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) return self.drive(onNext: { e in relay.accept(e) }) } /** Creates new subscription and sends elements to `BehaviorRelay`. This method can be only called from `MainThread`. - parameter relay: Target relay for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func drive(_ relay: BehaviorRelay<Element?>) -> Disposable { MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) return self.drive(onNext: { e in relay.accept(e) }) } /** Subscribes to observable sequence using custom binder function. This method can be only called from `MainThread`. - parameter with: Function used to bind elements from `self`. - returns: Object representing subscription. */ public func drive<Result>(_ transformation: (Observable<Element>) -> Result) -> Result { MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) return transformation(self.asObservable()) } /** Subscribes to observable sequence using custom binder function and final parameter passed to binder function after `self` is passed. public func drive<R1, R2>(with: Self -> R1 -> R2, curriedArgument: R1) -> R2 { return with(self)(curriedArgument) } This method can be only called from `MainThread`. - parameter with: Function used to bind elements from `self`. - parameter curriedArgument: Final argument passed to `binder` to finish binding process. - returns: Object representing subscription. */ public func drive<R1, R2>(_ with: (Observable<Element>) -> (R1) -> R2, curriedArgument: R1) -> R2 { MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) return with(self.asObservable())(curriedArgument) } /** Subscribes an element handler, a completion handler and disposed handler to an observable sequence. This method can be only called from `MainThread`. Error callback is not exposed because `Driver` can't error out. - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. gracefully completed, errored, or if the generation is canceled by disposing subscription) - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is canceled by disposing subscription) - returns: Subscription object used to unsubscribe from the observable sequence. */ public func drive(onNext: ((Element) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable { MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) } }
0784ed5d2a584859cb525d086c497ce8
42.557377
140
0.711329
false
false
false
false
ben-ng/swift
refs/heads/master
test/SILGen/default_constructor.swift
apache-2.0
1
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -primary-file %s | %FileCheck %s struct B { var i : Int, j : Float var c : C } struct C { var x : Int init() { x = 17 } } struct D { var (i, j) : (Int, Double) = (2, 3.5) } // CHECK-LABEL: sil hidden [transparent] @_TIvV19default_constructor1D1iSii : $@convention(thin) () -> (Int, Double) // CHECK: [[FN:%.*]] = function_ref @_TFSiCfT22_builtinIntegerLiteralBi2048__Si : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Int.Type // CHECK-NEXT: [[VALUE:%.*]] = integer_literal $Builtin.Int2048, 2 // CHECK-NEXT: [[LEFT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int // CHECK: [[FN:%.*]] = function_ref @_TFSdCfT20_builtinFloatLiteralBf{{64|80}}__Sd : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Double.Type // CHECK-NEXT: [[VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x400C000000000000|0x4000E000000000000000}} // CHECK-NEXT: [[RIGHT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Double) // CHECK-NEXT: return [[RESULT]] : $(Int, Double) // CHECK-LABEL: sil hidden @_TFV19default_constructor1DC{{.*}} : $@convention(method) (@thin D.Type) -> D // CHECK: [[THISBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <D> // CHECK: [[THIS:%[0-9]+]] = mark_uninit // CHECK: [[INIT:%[0-9]+]] = function_ref @_TIvV19default_constructor1D1iSii // CHECK: [[RESULT:%[0-9]+]] = apply [[INIT]]() // CHECK: [[INTVAL:%[0-9]+]] = tuple_extract [[RESULT]] : $(Int, Double), 0 // CHECK: [[FLOATVAL:%[0-9]+]] = tuple_extract [[RESULT]] : $(Int, Double), 1 // CHECK: [[IADDR:%[0-9]+]] = struct_element_addr [[THIS]] : $*D, #D.i // CHECK: assign [[INTVAL]] to [[IADDR]] // CHECK: [[JADDR:%[0-9]+]] = struct_element_addr [[THIS]] : $*D, #D.j // CHECK: assign [[FLOATVAL]] to [[JADDR]] class E { var i = Int64() } // CHECK-LABEL: sil hidden [transparent] @_TIvC19default_constructor1E1iVs5Int64i : $@convention(thin) () -> Int64 // CHECK: [[FN:%.*]] = function_ref @_TFVs5Int64CfT_S_ : $@convention(method) (@thin Int64.Type) -> Int64 // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Int64.Type // CHECK-NEXT: [[VALUE:%.*]] = apply [[FN]]([[METATYPE]]) : $@convention(method) (@thin Int64.Type) -> Int64 // CHECK-NEXT: return [[VALUE]] : $Int64 // CHECK-LABEL: sil hidden @_TFC19default_constructor1Ec{{.*}} : $@convention(method) (@owned E) -> @owned E // CHECK: bb0([[SELFIN:%[0-9]+]] : $E) // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized // CHECK: [[INIT:%[0-9]+]] = function_ref @_TIvC19default_constructor1E1iVs5Int64i : $@convention(thin) () -> Int64 // CHECK-NEXT: [[VALUE:%[0-9]+]] = apply [[INIT]]() : $@convention(thin) () -> Int64 // CHECK-NEXT: [[IREF:%[0-9]+]] = ref_element_addr [[SELF]] : $E, #E.i // CHECK-NEXT: assign [[VALUE]] to [[IREF]] : $*Int64 // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: destroy_value [[SELF]] // CHECK-NEXT: return [[SELF_COPY]] : $E class F : E { } // CHECK-LABEL: sil hidden @_TFC19default_constructor1Fc{{.*}} : $@convention(method) (@owned F) -> @owned F // CHECK: bb0([[ORIGSELF:%[0-9]+]] : $F) // CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <F> // CHECK-NEXT: project_box [[SELF_BOX]] // CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [derivedself] // CHECK-NEXT: store [[ORIGSELF]] to [init] [[SELF]] : $*F // SEMANTIC ARC TODO: This is incorrect. Why are we doing a +0 produce and passing off to a +1 consumer. This should be a copy. Or a mutable borrow perhaps? // CHECK-NEXT: [[SELFP:%[0-9]+]] = load_borrow [[SELF]] : $*F // CHECK-NEXT: [[E:%[0-9]]] = upcast [[SELFP]] : $F to $E // CHECK: [[E_CTOR:%[0-9]+]] = function_ref @_TFC19default_constructor1EcfT_S0_ : $@convention(method) (@owned E) -> @owned E // CHECK-NEXT: [[ESELF:%[0-9]]] = apply [[E_CTOR]]([[E]]) : $@convention(method) (@owned E) -> @owned E // CHECK-NEXT: [[ESELFW:%[0-9]+]] = unchecked_ref_cast [[ESELF]] : $E to $F // CHECK-NEXT: store [[ESELFW]] to [init] [[SELF]] : $*F // CHECK-NEXT: [[SELFP:%[0-9]+]] = load [copy] [[SELF]] : $*F // CHECK-NEXT: destroy_value [[SELF_BOX]] : $<τ_0_0> { var τ_0_0 } <F> // CHECK-NEXT: return [[SELFP]] : $F // <rdar://problem/19780343> Default constructor for a struct with optional doesn't compile // This shouldn't get a default init, since it would be pointless (bar can never // be reassigned). It should get a memberwise init though. struct G { let bar: Int32? } // CHECK-NOT: default_constructor.G.init () // CHECK-LABEL: default_constructor.G.init (bar : Swift.Optional<Swift.Int32>) // CHECK-NEXT: sil hidden @_TFV19default_constructor1GC // CHECK-NOT: default_constructor.G.init ()
eeb552d9b1af27c1e9a263de1223c69f
51.210526
165
0.609073
false
false
false
false
hisui/ReactiveSwift
refs/heads/master
ReactiveSwift/UITableView+Subject.swift
mit
1
// Copyright (c) 2014 segfault.jp. All rights reserved. import UIKit private var selectionSubjectKey = "selectionSubjectKey" public extension UITableView { public var selectionSubject: SetCollection<NSIndexPath> { return getAdditionalFieldOrUpdate(&selectionSubjectKey) { TableViewSelectionSubject<()>(self) } } public func setDataSource<T, C: UITableViewCell>(model: SeqCollection<T>, prototypeCell: String, _ f: (T, C) -> ()) -> Stream<()> { return setDataSource(model) { [weak self] (e, i) in let (cell) = self!.dequeueReusableCellWithIdentifier(prototypeCell) as! C f(e, cell) return cell } } public func setDataSource<T, C: UITableViewCell>(model: SeqView<T>, prototypeCell: String, _ f: (T, C) -> ()) -> Stream<()> { return setDataSource(model) { [weak self] (e, i) in let (cell) = self!.dequeueReusableCellWithIdentifier(prototypeCell) as! C f(e, cell) return cell } } public func setDataSource<T>(model: SeqCollection<T>, _ f: (T, Int) -> UITableViewCell) -> Stream<()> { return setDataSource(MutableTableViewDataSource(SeqViewErasure(model, f)), model) } public func setDataSource<T>(model: SeqView<T>, _ f: (T, Int) -> UITableViewCell) -> Stream<()> { return setDataSource(TableViewDataSource(SeqViewErasure(model, f)), model) } private func setDataSource<X>(source: TableViewDataSource, _ model: SeqView<X>) -> Stream<()> { dataSource = source reloadData() return mix([Streams.pure(()) , model.skip(1) .foreach { [weak self] e -> () in self?.update(e, source.model); () } .onClose { [weak self] _ -> () in self?.dataSource = nil self?.reloadData() } .nullify()]) } private func update<E>(update: SeqView<E>.UpdateType, _ `guard`: AnyObject) { if update.sender === `guard` { return } beginUpdates() for e in update.detail { deleteRowsAtIndexPaths(e.deletes, withRowAnimation: .None) insertRowsAtIndexPaths(e.inserts, withRowAnimation: .None) } endUpdates() } } private class TableViewSelectionSubject<T>: SetCollection<NSIndexPath> { private weak var table: UITableView! private var observer: NotificationObserver? = nil init(_ table: UITableView) { self.table = table super.init() observer = NotificationObserver(nil, UITableViewSelectionDidChangeNotification, nil) { [weak self] e in if (e.object === self?.table) { self!.assign(self!.table.indexPathsForSelectedRows ?? [], sender: table) } } } override func commit(update: UpdateType) { if update.sender !== table { for e in update.detail.insert { table.selectRowAtIndexPath(e, animated: false, scrollPosition: .None) } for e in update.detail.delete { table.deselectRowAtIndexPath(e, animated: false) } } super.commit(update) } } internal protocol SeqViewBridge: NSObjectProtocol { var count: Int { get } func viewForIndex(path: NSIndexPath) -> UIView func removeAt(index: NSIndexPath) func move(from: NSIndexPath, to: NSIndexPath) } internal class SeqViewErasure<T, V: UIView>: NSObject, SeqViewBridge { private let a: SeqView<T> private let f: (T, Int) -> V init(_ a: SeqView<T>, _ f: (T, Int) -> V) { self.a = a self.f = f } var count: Int { return Int(a.count) } var mutable: SeqCollection<T> { return a as! SeqCollection<T> } func viewForIndex(path: NSIndexPath) -> UIView { return f(a[path.row]!, path.row) } func removeAt(index: NSIndexPath) { mutable.removeAt(index.row) } func move(from: NSIndexPath, to: NSIndexPath) { mutable.move(from.row, to: to.row, sender: self) } } private class TableViewDataSource: NSObject, UITableViewDataSource { let model: SeqViewBridge required init (_ model: SeqViewBridge) { self.model = model } @objc func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return model.count } @objc func tableView(_: UITableView, cellForRowAtIndexPath path: NSIndexPath) -> UITableViewCell { return model.viewForIndex(path) as! UITableViewCell } } private class MutableTableViewDataSource: TableViewDataSource { @objc func tableView(_: UITableView, canEditRowAtIndexPath _: NSIndexPath) -> Bool { return true } @objc func tableView(_: UITableView, commitEditingStyle style: UITableViewCellEditingStyle, forRowAtIndexPath path: NSIndexPath) { if style == .Delete { model.removeAt(path) } } @objc func tableView(_: UITableView, canMoveRowAtIndexPath _: NSIndexPath) -> Bool { return true } @objc func tableView(_: UITableView, moveRowAtIndexPath src: NSIndexPath, toIndexPath dest: NSIndexPath) { model.move(src, to: dest) } } internal extension SeqDiff { var deletes: [NSIndexPath] { return indexPathsInRange(offset ..< (offset+delete)) } var inserts: [NSIndexPath] { return indexPathsInRange(offset ..< (offset+UInt(insert.count))) } } private func indexPathsInRange(range: Range<UInt>) -> [NSIndexPath] { var a = [NSIndexPath]() for i in range { a.append(NSIndexPath(forRow: Int(i), inSection: 0)) } return a }
e42375227f66d52f1bd4f5e1bc97a293
29.728723
135
0.603947
false
false
false
false
chengxianghe/MissGe
refs/heads/master
MissGe/MissGe/Class/Project/Request/Mine/MLMineRequest.swift
mit
1
// // MLMineQuestionRequest.swift // MissLi // // Created by chengxianghe on 16/7/28. // Copyright © 2016年 cn. All rights reserved. // import UIKit import TUNetworking //我的提问 //http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=post&a=myThemePostList&pg=1&size=20&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&uid=19793&orderby=add_date&orderway=desc class MLMineQuestionRequest: MLBaseRequest { var page = 1 //c=post&a=myThemePostList&pg=1&size=20&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU& uid=19793&orderby=add_date&orderway=desc override func requestParameters() -> [String : Any]? { let dict: [String : String] = ["c":"post","a":"myThemePostList","uid":MLNetConfig.shareInstance.userId,"token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20","orderby":"add_date","orderway":"desc"] return dict } override func requestHandleResult() { print("requestHandleResult -- \(self.classForCoder)") } } //我的回复 //http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=post&a=myRethemepostList&pg=1&size=20& token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU& orderby=add_date&orderway=desc class MLMineAnswerRequest: MLBaseRequest { var page = 1 //c=post&a=myRethemepostList&pg=1&size=20&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&orderby=add_date&orderway=desc override func requestParameters() -> [String : Any]? { //"uid":MLNetConfig.shareInstance.userId, let dict: [String : String] = ["c":"post","a":"myRethemepostList","token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20","orderby":"add_date","orderway":"desc"] return dict } override func requestHandleResult() { print("requestHandleResult -- \(self.classForCoder)") } } //我的收藏 //http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=article&a=getcollect&token=XPdcOIKGqf7nmgZSoqA9eshEbpWRSs7%252B%252BkqAtMdIf5uoyjo&page=0&size=20&orderby=add_date class MLMineFavoriteRequest: MLBaseRequest { var page = 1 //c=article&a=getcollect&token=XPdcOIKGqf7nmgZSoqA9eshEbpWRSs7%252B%252BkqAtMdIf5uoyjo&page=0&size=20 override func requestParameters() -> [String : Any]? { //,"orderby":"add_date","orderway":"desc" let dict: [String : String] = ["c":"article","a":"getcollect","token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20"] return dict } override func requestHandleResult() { print("requestHandleResult -- \(self.classForCoder)") } override func requestVerifyResult() -> Bool { guard let dict = self.responseObject as? NSDictionary else { return false } return (dict["result"] as? String) == "200" } } //我的评论 //http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=user&a=comlist&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&page=0&size=20 class MLMineCommentRequest: MLBaseRequest { var page = 1 //c=user&a=comlist&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&page=0&size=20 override func requestParameters() -> [String : Any]? { //,"orderby":"add_date","orderway":"desc" let dict: [String : String] = ["c":"user","a":"comlist","token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20"] return dict } override func requestHandleResult() { print("requestHandleResult -- \(self.classForCoder)") } } //圈儿消息 //http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=user&a=replylistV2&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&pg=1&size=20 class MLMineSquareMessageRequest: MLBaseRequest { var page = 1 //c=user&a=replylistV2&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&pg=1&size=20 override func requestParameters() -> [String : Any]? { //,"orderby":"add_date","orderway":"desc" let dict: [String : String] = ["c":"user","a":"replylistV2","token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20"] return dict } override func requestHandleResult() { print("requestHandleResult -- \(self.classForCoder)") } } //文章评论 //http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=user&a=commelist&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&pg=1&size=20 class MLMineArticleCommentRequest: MLBaseRequest { var page = 1 //c=user&a=commelist&token=W6FXbNLV9fnnmgZSoqA9eshEbpWRSs7%252B%252BkqAtMZAf5ijyTU&pg=1&size=20 override func requestParameters() -> [String : Any]? { //,"orderby":"add_date","orderway":"desc" let dict: [String : String] = ["c":"user","a":"commelist","token":MLNetConfig.shareInstance.token,"pg":"\(page)","size":"20"] return dict } override func requestHandleResult() { print("requestHandleResult -- \(self.classForCoder)") } }
29bb768cc51a2ac861a41922e2d659f4
41.302326
273
0.702034
false
true
false
false
tdgunes/TDGMessageKit
refs/heads/master
Example/Example/ViewController.swift
mit
1
// // ViewController.swift // Example // // Created by Taha Doğan Güneş on 10/07/15. // Copyright (c) 2015 Taha Doğan Güneş. All rights reserved. // import UIKit import TDGMessageKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var upperMessageBox = TDGMessageBox(orientation: .Bottom) upperMessageBox.titleLabel.text = "TitleLabel Example Text" upperMessageBox.bodyLabel.text = "BodyLabel Example Text" upperMessageBox.view.alpha = 0.8 upperMessageBox.addTo(self.view) upperMessageBox.toggle() var bottomMessageBox = TDGMessageBox(orientation: .Top) bottomMessageBox.titleLabel.text = "TitleLabel Example Text" bottomMessageBox.bodyLabel.text = "BodyLabel Example Text" bottomMessageBox.addTo(self.view) bottomMessageBox.toggle() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
4e3c29738342ec7d089c2a0e596cbb58
27.675
80
0.681779
false
false
false
false
SandroMachado/SwiftClient
refs/heads/master
SwiftClient/Request.swift
mit
2
// // SwiftClient.swift // SwiftClient // // Created by Adam Nalisnick on 10/25/14. // Copyright (c) 2014 Adam Nalisnick. All rights reserved. // import Foundation private let errorHandler = {(error:NSError) -> Void in }; /// Class for handling request building and sending public class Request { var data:AnyObject?; var headers: [String : String]; public var url:String; let method: String; var delegate: NSURLSessionDelegate?; var timeout:Double; var transformer:(Response) -> Response = {$0}; var query:[String] = Array(); var errorHandler:((NSError) -> Void); var formData:FormData?; internal init(_ method: String, _ url: String, _ errorHandler:(NSError) -> Void){ self.method = method; self.url = url; self.headers = Dictionary(); self.timeout = 60; self.errorHandler = errorHandler; } /// Sets headers on the request from a dictionary public func set(headers: [String:String]) -> Request{ for(key, value) in headers { self.set(key, value); } return self; } /// Sets headers on the request from a key and value public func set(key: String, _ value: String) -> Request{ self.headers[key] = value; return self; } /// Executs a middleware function on the request public func use(middleware: (Request) -> Request) -> Request{ return middleware(self); } /// Stores a response transformer to be used on the received HTTP response public func transform(transformer: (Response) -> Response) -> Request{ var oldTransformer = self.transformer; self.transformer = {(response:Response) -> Response in return transformer(oldTransformer(response)); } return self; } /// Sets the content-type. Can be set using shorthand. /// ex: json, html, form, urlencoded, form, form-data, xml /// /// When not using shorthand, the value is used directory. public func type(type:String) -> Request { self.set("content-type", (types[type] ?? type)); return self; } /// Gets the header value for the case insensitive key passed public func getHeader(header:String) -> String? { return self.headers[header.lowercaseString]; } /// Gets the content-type of the request private func getContentType() -> String?{ return getHeader("content-type"); } /// Sets the type if not set private func defaultToType(type:String){ if self.getContentType() == nil { self.type(type); } } /// Adds query params on the URL from a dictionary public func query(query:[String : String]) -> Request{ for (key,value) in query { self.query.append(queryPair(key, value)); } return self; } /// Adds query params on the URL from a key and value public func query(query:String) -> Request{ self.query.append(query); return self; } /// Handles adding a single key and value to the request body private func _send(key: String, _ value: AnyObject) -> Request{ if var dict = self.data as? [String : AnyObject] { dict[key] = value; self.data = dict; } else{ self.data = [key : value]; } return self; } /// Adds a string to the request body. If the body already contains /// a string and the content type is form, & is also appended. If the body /// is a string and the content-type is not a form, the string is merely appended. /// Otherwise, the body is set to the string. public func send(data:String) -> Request{ defaultToType("form"); if self.getContentType() == types["form"] { var oldData = ""; if let stringData = self.data as? String { oldData = stringData + "&"; } self.data = oldData + data; } else{ var oldData = self.data as? String ?? ""; self.data = oldData + data; } return self; } /// Sets the body of the request. If the body is a Dictionary, /// and a dictionary is passed in, the two are merged. Otherwise, /// the body is set directly to the passed data. public func send(data:AnyObject) -> Request{ if let entries = data as? [String : AnyObject] { defaultToType("json"); for (key, value) in entries { self._send(key, value); } } else{ self.data = data; } return self; } /// Sets the request's timeout interval public func timeout(timeout:Double) -> Request { self.timeout = timeout; return self; } /// Sets the delegate on the request public func delegate(delegate:NSURLSessionDelegate) -> Request { self.delegate = delegate; return self; } /// Sets the error handler on the request public func onError(errorHandler:(NSError) -> Void) -> Request { self.errorHandler = errorHandler; return self; } /// Adds Basic HTTP Auth to the request public func auth(username:String, _ password:String) -> Request { let authString = base64Encode(username + ":" + password); self.set("authorization", "Basic \(authString)") return self; } private func getFormData() -> FormData { if(self.formData == nil) { self.formData = FormData(); } return self.formData!; } /// Adds a field to a multipart request public func field(name:String, _ value:String) -> Request { self.getFormData().append(name, value); return self; } /// Attached a file to a multipart request. If the mimeType isnt given, it will be inferred. public func attach(name:String, _ data:NSData, _ filename:String, withMimeType mimeType:String? = nil) -> Request { self.getFormData().append(name, data, filename, mimeType) return self } /// Attached a file to a multipart request. If the mimeType isnt given, it will be inferred. /// If the filename isnt given it will be pulled from the path public func attach(name:String, _ path:String, _ filename:String? = nil, withMimeType mimeType:String? = nil) -> Request { var basename:String! = filename; if(filename == nil){ basename = path.lastPathComponent; } let data = NSData(contentsOfFile: path) self.getFormData().append(name, data ?? NSData(), basename, mimeType) return self } /// Sends the request using the passed in completion handler and the optional error handler public func end(done: (Response) -> Void, onError errorHandler: ((NSError) -> Void)? = nil) { if(self.query.count > 0){ if let queryString = queryString(self.query){ self.url += self.url.rangeOfString("?") != nil ? "&" : "?"; self.url += queryString; } } let queue = NSOperationQueue(); let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self.delegate, delegateQueue: queue); var request = NSMutableURLRequest(URL: NSURL(string: self.url)!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: NSTimeInterval(self.timeout)); request.HTTPMethod = self.method; if(self.method != "GET" && self.method != "HEAD") { if(self.formData != nil) { request.HTTPBody = self.formData!.getBody(); self.type(self.formData!.getContentType()); self.set("Content-Length", toString(request.HTTPBody?.length)); } else if(self.data != nil){ if let data = self.data! as? NSData { request.HTTPBody = data; } else if let type = self.getContentType(){ if let serializer = serializers[type]{ request.HTTPBody = serializer(self.data!) } else { request.HTTPBody = stringToData(toString(self.data!)) } } } } for (key, value) in self.headers { request.setValue(value, forHTTPHeaderField: key); } let task = session.dataTaskWithRequest(request, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError!) -> Void in if let response = response as? NSHTTPURLResponse { done(self.transformer(Response(response, self, data))); } else if errorHandler != nil { errorHandler!(error); } else { self.errorHandler(error); } } ); task.resume(); } }
feebb77a699bc6d798f03c21da167c87
33.412639
181
0.56649
false
false
false
false
lyb5834/YBAttributeTextTapForSwfit
refs/heads/master
YBAttributeTextTapForSwfit-Demo/YBAttributeTextTapForSwfit/YBAttributeTextTapForSwfit.swift
mit
2
// // YBAttributeTextTapForSwfit.swift // YBAttributeTextTapForSwfit // // Created by LYB on 16/7/7. // Copyright © 2016年 LYB. All rights reserved. // import UIKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } private var isTapAction : Bool? private var attributeStrings : [YBAttributeModel]? private var tapBlock : ((_ str : String ,_ range : NSRange ,_ index : Int) -> Void)? private var isTapEffect : Bool = true private var effectDic : Dictionary<String , NSAttributedString>? extension UILabel { // MARK: - Objects /// 是否打开点击效果,默认是打开 var enabledTapEffect : Bool { set { isTapEffect = newValue } get { return isTapEffect } } // MARK: - mainFunction /** 给文本添加点击事件 - parameter strings: 需要点击的字符串数组 - parameter tapAction: 点击事件回调 */ func yb_addAttributeTapAction( _ strings : [String] , tapAction : @escaping ((String , NSRange , Int) -> Void)) -> Void { yb_getRange(strings) tapBlock = tapAction } // MARK: - touchActions open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if isTapAction == false { return } let touch = touches.first let point = touch?.location(in: self) yb_getTapFrame(point!) { (String, NSRange, Int) -> Void in if tapBlock != nil { tapBlock! (String, NSRange , Int) } if isTapEffect { self.yb_saveEffectDicWithRange(NSRange) self.yb_tapEffectWithStatus(true) } } } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if isTapEffect { self.performSelector(onMainThread: #selector(self.yb_tapEffectWithStatus(_:)), with: nil, waitUntilDone: false) } } open override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) { if isTapEffect { self.performSelector(onMainThread: #selector(self.yb_tapEffectWithStatus(_:)), with: nil, waitUntilDone: false) } } override open func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if isTapAction == true { let result = yb_getTapFrame(point, result: { ( String, NSRange, Int) -> Void in }) if result == true { return self } } return super.hitTest(point, with: event) } // MARK: - getTapFrame @discardableResult fileprivate func yb_getTapFrame(_ point : CGPoint , result : ((_ str : String ,_ range : NSRange ,_ index : Int) -> Void)) -> Bool { let framesetter = CTFramesetterCreateWithAttributedString(self.attributedText!) var path = CGMutablePath() path.addRect(self.bounds, transform: CGAffineTransform.identity) var frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil) let range = CTFrameGetVisibleStringRange(frame) if self.attributedText?.length > range.length { var m_font : UIFont let n_font = self.attributedText?.attribute(NSAttributedString.Key.font, at: 0, effectiveRange: nil) if n_font != nil { m_font = n_font as! UIFont }else if (self.font != nil) { m_font = self.font }else { m_font = UIFont.systemFont(ofSize: 17) } path = CGMutablePath() path.addRect(CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height + m_font.lineHeight), transform: CGAffineTransform.identity) frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil) } let lines = CTFrameGetLines(frame) if lines == [] as CFArray { return false } let count = CFArrayGetCount(lines) var origins = [CGPoint](repeating: CGPoint.zero, count: count) CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), &origins) let transform = CGAffineTransform(translationX: 0, y: self.bounds.size.height).scaledBy(x: 1.0, y: -1.0); let verticalOffset = 0.0 for i : CFIndex in 0..<count { let linePoint = origins[i] let line = CFArrayGetValueAtIndex(lines, i) let lineRef = unsafeBitCast(line,to: CTLine.self) let flippedRect : CGRect = yb_getLineBounds(lineRef , point: linePoint) var rect = flippedRect.applying(transform) rect = rect.insetBy(dx: 0, dy: 0) rect = rect.offsetBy(dx: 0, dy: CGFloat(verticalOffset)) let style = self.attributedText?.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: nil) var lineSpace : CGFloat = 0.0 if (style != nil) { lineSpace = (style as! NSParagraphStyle).lineSpacing }else { lineSpace = 0.0 } let lineOutSpace = (CGFloat(self.bounds.size.height) - CGFloat(lineSpace) * CGFloat(count - 1) - CGFloat(rect.size.height) * CGFloat(count)) / 2 rect.origin.y = lineOutSpace + rect.size.height * CGFloat(i) + lineSpace * CGFloat(i) if rect.contains(point) { let relativePoint = CGPoint(x: point.x - rect.minX, y: point.y - rect.minY) var index = CTLineGetStringIndexForPosition(lineRef, relativePoint) var offset : CGFloat = 0.0 CTLineGetOffsetForStringIndex(lineRef, index, &offset) if offset > relativePoint.x { index = index - 1 } let link_count = attributeStrings?.count for j in 0 ..< link_count! { let model = attributeStrings![j] let link_range = model.range if NSLocationInRange(index, link_range!) { result(model.str!,model.range!,j) return true } } } } return false } fileprivate func yb_getLineBounds(_ line : CTLine , point : CGPoint) -> CGRect { var ascent : CGFloat = 0.0; var descent : CGFloat = 0.0; var leading : CGFloat = 0.0; let width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading) let height = ascent + fabs(descent) + leading return CGRect.init(x: point.x, y: point.y , width: CGFloat(width), height: height) } // MARK: - getRange fileprivate func yb_getRange(_ strings : [String]) -> Void { if self.attributedText?.length == 0 { return; } self.isUserInteractionEnabled = true isTapAction = true var totalString = self.attributedText?.string attributeStrings = []; for str : String in strings { let range = totalString?.range(of: str) if (range?.lowerBound != nil) { totalString = totalString?.replacingCharacters(in: range!, with: self.yb_getString(str.characters.count)) let model = YBAttributeModel() model.range = totalString?.nsRange(from: range!) model.str = str attributeStrings?.append(model) } } } fileprivate func yb_getString(_ count : Int) -> String { var string = "" for _ in 0 ..< count { string = string + " " } return string } // MARK: - tapEffect fileprivate func yb_saveEffectDicWithRange(_ range : NSRange) -> Void { effectDic = [:] let subAttribute = self.attributedText?.attributedSubstring(from: range) _ = effectDic?.updateValue(subAttribute!, forKey: NSStringFromRange(range)) } @objc fileprivate func yb_tapEffectWithStatus(_ status : Bool) -> Void { if isTapEffect { let attStr = NSMutableAttributedString.init(attributedString: self.attributedText!) let subAtt = NSMutableAttributedString.init(attributedString: (effectDic?.values.first)!) let range = NSRangeFromString(effectDic!.keys.first!) if status { subAtt.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.lightGray, range: NSMakeRange(0, subAtt.length)) attStr.replaceCharacters(in: range, with: subAtt) }else { attStr.replaceCharacters(in: range, with: subAtt) } self.attributedText = attStr } } } private class YBAttributeModel: NSObject { var range : NSRange? var str : String? } private extension String { func nsRange(from range: Range<String.Index>) -> NSRange { return NSRange(range,in : self) } func range(from nsRange: NSRange) -> Range<String.Index>? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex), let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) else { return nil } return from ..< to } }
f3ad2e9cba7334d022fb0c0dd7e50afc
31.884848
167
0.53861
false
false
false
false
DavidMoritz/spiel
refs/heads/master
CardsAgainst/Helpers/Colors.swift
mit
3
// // Colors.swift // CardsAgainst // // Created by JP Simard on 10/25/14. // Copyright (c) 2014 JP Simard. All rights reserved. // import UIKit let navBarColor = UIColor(white: 0.33, alpha: 1) let darkColor = UIColor(white: 0.1, alpha: 1) let lightColor = UIColor.whiteColor() let appTintColor = UIColor(red: 102/255, green: 176/255, blue: 1, alpha: 1) let appBackgroundColor = darkColor
5f264286c78847460b2080c9a060dc92
25.333333
75
0.703797
false
false
false
false
pkc456/Roastbook
refs/heads/master
Roastbook/Roastbook/Business Layer/FeedBusinessLayer.swift
mit
1
// // FeedBusinessLayer.swift // Roastbook // // Created by Pradeep Choudhary on 4/8/17. // Copyright © 2017 Pardeep chaudhary. All rights reserved. // import Foundation class FeedBusinessLayer: NSObject { class var sharedInstance: FeedBusinessLayer { struct Static { static let instance: FeedBusinessLayer = FeedBusinessLayer() } return Static.instance } func parseArrayJsonData(data: NSArray) -> [Feed] { let modelObject = Feed.modelsFromDictionaryArray(array: data) return modelObject } //Methods to get dummy data func getFeedInformationDataArray() -> [Feed] { let feedDictionary = getFeedListData() let arrayOfMusicData = Feed.modelsFromDictionaryArray(array: [feedDictionary]) return arrayOfMusicData } private func getFeedListData() -> NSMutableDictionary{ let data : NSMutableDictionary = NSMutableDictionary() data.setValue("I am rockstar. I am rockstar. I am rockstar What are your views. I am waiting. Slide across the down button. Show me! Can you I am rockstar. I am rockstar. I am rockstar What are your views. I am waiting. Slide across the down button. Show me! Can you. Testing", forKey: KKEY_FEED) data.setValue("Pardeep", forKey: KKEY_FEED_NAME) return data } }
20e9eb2bde2253694757de5d8b46d22d
33.1
304
0.673754
false
false
false
false
andreamazz/AMPopTip
refs/heads/main
Demo/Pods/Nimble-Snapshots/Nimble_Snapshots/DynamicSize/DynamicSizeSnapshot.swift
mit
1
import Foundation import Nimble import QuartzCore import UIKit public enum ResizeMode { case frame case constrains case block(resizeBlock: (UIView, CGSize) -> Void) case custom(viewResizer: ViewResizer) func viewResizer() -> ViewResizer { switch self { case .frame: return FrameViewResizer() case .constrains: return ConstraintViewResizer() case .block(resizeBlock: let block): return BlockViewResizer(block: block) case .custom(viewResizer: let resizer): return resizer } } } public protocol ViewResizer { func resize(view: UIView, for size: CGSize) } struct FrameViewResizer: ViewResizer { func resize(view: UIView, for size: CGSize) { view.frame = CGRect(origin: .zero, size: size) view.layoutIfNeeded() } } struct BlockViewResizer: ViewResizer { let resizeBlock: (UIView, CGSize) -> Void init(block: @escaping (UIView, CGSize) -> Void) { self.resizeBlock = block } func resize(view: UIView, for size: CGSize) { self.resizeBlock(view, size) } } class ConstraintViewResizer: ViewResizer { typealias SizeConstrainsWrapper = (heightConstrain: NSLayoutConstraint, widthConstrain: NSLayoutConstraint) func resize(view: UIView, for size: CGSize) { let sizesConstrains = findConstrains(of: view) sizesConstrains.heightConstrain.constant = size.height sizesConstrains.widthConstrain.constant = size.width NSLayoutConstraint.activate([sizesConstrains.heightConstrain, sizesConstrains.widthConstrain]) view.layoutIfNeeded() // iOS 9+ BUG: Before the first draw, iOS will not calculate the layout, // it add a _UITemporaryLayoutWidth equals to its bounds and create a conflict. // So to it do all the layout we create a Window and add it as subview if view.bounds.width != size.width || view.bounds.height != size.height { let window = UIWindow(frame: CGRect(origin: .zero, size: size)) let viewController = UIViewController() viewController.view = UIView() viewController.view.addSubview(view) window.rootViewController = viewController window.makeKeyAndVisible() view.setNeedsLayout() view.layoutIfNeeded() } } func findConstrains(of view: UIView) -> SizeConstrainsWrapper { var height: NSLayoutConstraint! // swiftlint:disable:this implicitly_unwrapped_optional var width: NSLayoutConstraint! // swiftlint:disable:this implicitly_unwrapped_optional #if swift(>=4.2) let heightLayout = NSLayoutConstraint.Attribute.height let widthLayout = NSLayoutConstraint.Attribute.width let equalRelation = NSLayoutConstraint.Relation.equal #else let heightLayout = NSLayoutAttribute.height let widthLayout = NSLayoutAttribute.width let equalRelation = NSLayoutRelation.equal #endif for constrain in view.constraints { if constrain.firstAttribute == heightLayout && constrain.relation == equalRelation && constrain.secondItem == nil { height = constrain } if constrain.firstAttribute == widthLayout && constrain.relation == equalRelation && constrain.secondItem == nil { width = constrain } } if height == nil { height = NSLayoutConstraint(item: view, attribute: heightLayout, relatedBy: equalRelation, toItem: nil, attribute: heightLayout, multiplier: 1, constant: 0) view.addConstraint(height) } if width == nil { width = NSLayoutConstraint(item: view, attribute: widthLayout, relatedBy: equalRelation, toItem: nil, attribute: widthLayout, multiplier: 1, constant: 0) view.addConstraint(width) } return (height, width) } } public struct DynamicSizeSnapshot { let name: String? let identifier: String? let record: Bool let sizes: [String: CGSize] let resizeMode: ResizeMode init(name: String?, identifier: String?, record: Bool, sizes: [String: CGSize], resizeMode: ResizeMode) { self.name = name self.identifier = identifier self.record = record self.sizes = sizes self.resizeMode = resizeMode } } public func snapshot(_ name: String? = nil, identifier: String? = nil, sizes: [String: CGSize], resizeMode: ResizeMode = .frame) -> DynamicSizeSnapshot { return DynamicSizeSnapshot(name: name, identifier: identifier, record: false, sizes: sizes, resizeMode: resizeMode) } public func haveValidDynamicSizeSnapshot(named name: String? = nil, identifier: String? = nil, sizes: [String: CGSize], isDeviceAgnostic: Bool = false, usesDrawRect: Bool = false, pixelTolerance: CGFloat? = nil, tolerance: CGFloat? = nil, resizeMode: ResizeMode = .frame, shouldIgnoreScale: Bool = false) -> Predicate<Snapshotable> { return Predicate { actualExpression in return performDynamicSizeSnapshotTest(name, identifier: identifier, sizes: sizes, isDeviceAgnostic: isDeviceAgnostic, usesDrawRect: usesDrawRect, actualExpression: actualExpression, tolerance: tolerance, pixelTolerance: pixelTolerance, isRecord: false, resizeMode: resizeMode, shouldIgnoreScale: shouldIgnoreScale) } } func performDynamicSizeSnapshotTest(_ name: String?, identifier: String? = nil, sizes: [String: CGSize], isDeviceAgnostic: Bool = false, usesDrawRect: Bool = false, actualExpression: Expression<Snapshotable>, tolerance: CGFloat? = nil, pixelTolerance: CGFloat? = nil, isRecord: Bool, resizeMode: ResizeMode, shouldIgnoreScale: Bool = false) -> PredicateResult { // swiftlint:disable:next force_try force_unwrapping let instance = try! actualExpression.evaluate()! let testFileLocation = actualExpression.location.file let referenceImageDirectory = getDefaultReferenceDirectory(testFileLocation) let snapshotName = sanitizedTestName(name) let tolerance = tolerance ?? getTolerance() let pixelTolerance = pixelTolerance ?? getPixelTolerance() let resizer = resizeMode.viewResizer() let result = sizes.map { sizeName, size -> Bool in // swiftlint:disable:next force_unwrapping let view = instance.snapshotObject! let finalSnapshotName: String if let identifier = identifier { finalSnapshotName = "\(snapshotName)_\(identifier)_\(sizeName)" } else { finalSnapshotName = "\(snapshotName)_\(sizeName)" } resizer.resize(view: view, for: size) let filename = "\(actualExpression.location.file)" return FBSnapshotTest.compareSnapshot(instance, isDeviceAgnostic: isDeviceAgnostic, usesDrawRect: usesDrawRect, snapshot: finalSnapshotName, record: isRecord, referenceDirectory: referenceImageDirectory, tolerance: tolerance, perPixelTolerance: pixelTolerance, filename: filename, identifier: nil, shouldIgnoreScale: shouldIgnoreScale) } if isRecord { var message: String = "" let name = name ?? snapshotName if result.filter({ !$0 }).isEmpty { message = "snapshot \(name) successfully recorded, replace recordSnapshot with a check" } else { message = "expected to record a snapshot in \(name)" } return PredicateResult(status: PredicateStatus(bool: false), message: .fail(message)) } else { var message: String = "" if !result.filter({ !$0 }).isEmpty { message = "expected a matching snapshot in \(snapshotName)" return PredicateResult(status: PredicateStatus(bool: false), message: .fail(message)) } return PredicateResult(status: PredicateStatus(bool: true), message: .fail(message)) } } public func recordSnapshot(_ name: String? = nil, identifier: String? = nil, sizes: [String: CGSize], resizeMode: ResizeMode = .frame) -> DynamicSizeSnapshot { return DynamicSizeSnapshot(name: name, identifier: identifier, record: true, sizes: sizes, resizeMode: resizeMode) } public func recordDynamicSizeSnapshot(named name: String? = nil, identifier: String? = nil, sizes: [String: CGSize], isDeviceAgnostic: Bool = false, usesDrawRect: Bool = false, resizeMode: ResizeMode = .frame, shouldIgnoreScale: Bool = false) -> Predicate<Snapshotable> { return Predicate { actualExpression in return performDynamicSizeSnapshotTest(name, identifier: identifier, sizes: sizes, isDeviceAgnostic: isDeviceAgnostic, usesDrawRect: usesDrawRect, actualExpression: actualExpression, isRecord: true, resizeMode: resizeMode, shouldIgnoreScale: shouldIgnoreScale) } } public func == (lhs: Expectation<Snapshotable>, rhs: DynamicSizeSnapshot) { if rhs.record { lhs.to(recordDynamicSizeSnapshot(named: rhs.name, identifier: rhs.identifier, sizes: rhs.sizes, resizeMode: rhs.resizeMode)) } else { lhs.to(haveValidDynamicSizeSnapshot(named: rhs.name, identifier: rhs.identifier, sizes: rhs.sizes, resizeMode: rhs.resizeMode)) } }
18dd507e2fb9c0e7bcb04061ed12863b
41.150538
119
0.53648
false
false
false
false
snazzware/HexMatch
refs/heads/master
HexMatch/Scenes/GameScene.swift
gpl-3.0
2
// // GameScene.swift // HexMatch // // Created by Josh McKee on 1/11/16. // Copyright (c) 2016 Josh McKee. All rights reserved. // import SpriteKit import CoreData import SNZSpriteKitUI import GameKit class GameScene: SNZScene { var gameboardLayer = SKNode() var guiLayer = SKNode() var currentPieceLabel: SKLabelNode? var currentPieceHome = CGPoint(x: 0,y: 0) var currentPieceSprite: SKSpriteNode? var currentPieceSpriteProgressionLeft: SKSpriteNode? var currentPieceSpriteProgressionRight: SKSpriteNode? var currentPieceSpriteProgressionArrow: SKSpriteNode? var currentPieceCaption: SKShapeNode? var currentPieceCaptionText: String = "" var stashPieceLabel: SKLabelNode? var stashPieceHome = CGPoint(x: 0,y: 0) var stashBox: SKShapeNode? var menuButton: SNZTextureButtonWidget? var undoButton: SNZTextureButtonWidget? var gameOverLabel: SKLabelNode? var bankButton: BankButtonWidget? var stashButton: SNZButtonWidget? var currentButton: SNZButtonWidget? var statsButton: SNZButtonWidget? var highScoreButton: SNZButtonWidget? var uiTextScale:CGFloat = 1.0 var scoreDisplay: SKLabelNode? var scoreLabel: SKLabelNode? var goalScoreDisplay: SKLabelNode? var goalScoreLabel: SKLabelNode? var bankPointsDisplay: SKLabelNode? var bankPointsLabel: SKLabelNode? var highScoreDisplay: SKLabelNode? var highScoreLabel: SKLabelNode? var mergingPieces: [HexPiece] = Array() var mergedPieces: [HexPiece] = Array() var lastPlacedPiece: HexPiece? var lastPointsAwarded = 0 var mergesCurrentTurn = 0 var hexMap: HexMap? var undoState: Data? var debugShape: SKShapeNode? let lock = Spinlock() var _score = 0 var score: Int { get { return self._score } set { self._score = newValue self.updateScore() // Update score in state GameState.instance!.score = self._score // Update overall high score if (self._score > GameState.instance!.highScore) { GameState.instance!.highScore = self._score self.updateHighScore() } // Update level mode specific high score if (self._score > GameStats.instance!.getIntForKey("highscore_"+String(LevelHelper.instance.mode.rawValue))) { GameStats.instance!.setIntForKey("highscore_"+String(LevelHelper.instance.mode.rawValue), self._score) } } } var _bankPoints = 0 var bankPoints: Int { get { return self._bankPoints } set { self._bankPoints = newValue self.updateBankPoints() // Update score in state GameState.instance!.bankPoints = self._bankPoints } } override func didMove(to view: SKView) { super.didMove(to: view) if (GameStateMachine.instance!.currentState is GameSceneInitialState) { // Set up GUI, etc. self.initGame() // If hexMap is blank, enter restart state to set up new game if (GameState.instance!.hexMap.isBlank) { GameStateMachine.instance!.enter(GameSceneRestartState.self) } else { GameStateMachine.instance!.enter(GameScenePlayingState.self) } } self.updateGuiPositions() } func initGame() { // Set background self.backgroundColor = UIColor(red: 0x69/255, green: 0x65/255, blue: 0x6f/255, alpha: 1.0) // Calculate font scale factor self.initScaling() // Add guiLayer to scene addChild(self.guiLayer) // Get the hex map and render it self.renderFromState() // Build progression sprites self.buildProgression() // Generate proxy sprite for current piece self.updateCurrentPieceSprite() // Add gameboardLayer to scene addChild(self.gameboardLayer) // Init bank points self.bankPoints = GameState.instance!.bankPoints // Init guiLayer self.initGuiLayer() // Check to see if we are already out of open cells, and change to end game state if so // e.g. in case state was saved during end game. if (HexMapHelper.instance.hexMap!.getOpenCells().count==0) { GameStateMachine.instance!.enter(GameSceneGameOverState.self) } // Update game center, just in case we missed anything (crash, kill, etc) GameStats.instance!.updateGameCenter() } func renderFromState() { // Init HexMap self.hexMap = GameState.instance!.hexMap // Init score self._score = GameState.instance!.score // Init level HexMapHelper.instance.hexMap = self.hexMap! // Render our hex map to the gameboardLayer HexMapHelper.instance.renderHexMap(gameboardLayer); } /** Reset game state. This includes clearing current score, stashed piece, current piece, and regenerating hexmap with a new random starting layout. */ func resetLevel() { // Remove current piece, stash piece sprites self.removeTransientGuiSprites() // Make sure that Game Over label is no longer displayed self.hideGameOver() // Clear the board HexMapHelper.instance.clearHexMap(self.gameboardLayer) // Clear the hexmap self.hexMap?.clear() // Generate level LevelHelper.instance.initLevel(self.hexMap!) // Generate new current piece self.generateCurrentPiece() // Generate proxy sprite for current piece self.updateCurrentPieceSprite() // Reset buyables GameState.instance!.resetBuyablePieces() // Clear stash if (GameState.instance!.stashPiece != nil) { if (GameState.instance!.stashPiece!.sprite != nil) { GameState.instance!.stashPiece!.sprite!.removeFromParent() } GameState.instance!.stashPiece = nil } // Render game board HexMapHelper.instance.renderHexMap(gameboardLayer); // Reset score self.score = 0 // Reset merges counter self.mergesCurrentTurn = 0 // Update GUI self.updateGuiLayer() // Clear undo self.undoButton!.hidden = true self.undoState = nil // Update game center GameStats.instance!.updateGameCenter() } /** Handles touch begin and move events. Updates animations for any pieces which would be merged if the player were to end the touch event in the cell being touched, if any. */ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if (self.widgetTouchesBegan(touches, withEvent: event)) { return } let location = touches.first?.location(in: self) if (location != nil) { let nodes = self.nodes(at: location!) for node in nodes { if (node.name == "hexMapCell") { // Get cell using stord position from node's user data let x = node.userData!.value(forKey: "hexMapPositionX") as! Int let y = node.userData!.value(forKey: "hexMapPositionY") as! Int let cell = HexMapHelper.instance.hexMap!.cell(x,y) // If we have a Remove piece, move it to the target cell regardless of contents if (GameState.instance!.currentPiece != nil && GameState.instance!.currentPiece is RemovePiece) { currentPieceSprite!.position = node.position } else // Otherwise, check to see if the cell will accept the piece if (cell!.willAccept(GameState.instance!.currentPiece!)) { self.updateMergingPieces(cell!) // Move to touched point currentPieceSprite!.removeAction(forKey: "moveAnimation") currentPieceSprite!.position = node.position } } } } } /** touchesMoved override. We just call touchesBegan for this game, since the logic is the same. */ override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { self.touchesBegan(touches, with: event) } /** touchesEnded override. Widgets first, then our own local game nodes. */ override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if (self.widgetTouchesEnded(touches, withEvent: event) || touches.first == nil) { return } let location = touches.first?.location(in: self) if ((location != nil) && (GameStateMachine.instance!.currentState is GameScenePlayingState)) { for node in self.nodes(at: location!) { if (self.nodeWasTouched(node)) { break; } } } if (GameStateMachine.instance!.currentState is GameSceneGameOverState && self.gameOverLabel?.parent != nil) { self.scene!.view?.presentScene(SceneHelper.instance.levelScene, transition: SKTransition.push(with: SKTransitionDirection.up, duration: 0.4)) } } /** Handle a node being touched. Place piece, merge, collect, etc. */ func nodeWasTouched(_ node: SKNode) -> Bool { var handled = false if (node.name == "hexMapCell") { let x = node.userData!.value(forKey: "hexMapPositionX") as! Int let y = node.userData!.value(forKey: "hexMapPositionY") as! Int let cell = HexMapHelper.instance.hexMap!.cell(x,y) // Refresh merging pieces self.updateMergingPieces(cell!) // Do we have a Remove piece? if (GameState.instance!.currentPiece != nil && GameState.instance!.currentPiece is RemovePiece) { // Capture state for undo self.captureState() // Process the removal self.playRemovePiece(cell!) } else // Does the cell contain a collectible hex piece? if (cell!.hexPiece != nil && cell!.hexPiece!.isCollectible) { // Capture state for undo self.captureState() // Let the piece know it was collected cell!.hexPiece!.wasCollected() // Clear out the hex cell cell!.hexPiece = nil } else // Will the target cell accept our current piece, and will the piece either allow placement // without a merge, or if not, do we have a merge? if (cell!.willAccept(GameState.instance!.currentPiece!) && (GameState.instance!.currentPiece!.canPlaceWithoutMerge() || self.mergingPieces.count>0)) { // Capture state for undo self.captureState() // Store last placed piece, prior to any merging GameState.instance!.lastPlacedPiece = GameState.instance!.currentPiece // Place the current piece self.placeCurrentPiece(cell!) } handled = true } return handled } /** Handle the merging of pieces */ func handleMerge(_ cell: HexCell) { // Are we merging pieces? if (self.mergingPieces.count>0) { var maxValue = 0 var minValue = 10000 // Remove animations from merging pieces, and find the maximum value for hexPiece in self.mergingPieces { hexPiece.sprite!.removeAction(forKey: "mergeAnimation") hexPiece.sprite!.setScale(1.0) if (hexPiece.value > maxValue) { maxValue = hexPiece.value } if (hexPiece.value < minValue) { minValue = hexPiece.value } } // Let piece know it was placed w/ merge GameState.instance!.currentPiece = GameState.instance!.currentPiece!.wasPlacedWithMerge(minValue, mergingPieces: self.mergingPieces) self.mergesCurrentTurn += 1 // Store merged pieces, if any self.mergedPieces = self.mergingPieces // Block while we merge self.lock.around { GameStateMachine.instance!.blocked = true } // Create merge animation let moveAction = SKAction.move(to: HexMapHelper.instance.hexMapToScreen(cell.position), duration: 0.25) let moveSequence = SKAction.sequence([moveAction, SKAction.removeFromParent(), SKAction.run({self.lock.around { GameStateMachine.instance!.blocked = false }})]) // Remove merged pieces from board for hexPiece in self.mergingPieces { if (hexPiece.value == minValue) { hexPiece.sprite!.run(moveSequence) hexPiece.hexCell?.hexPiece = nil } } } else { // let piece know we are placing it GameState.instance!.currentPiece!.wasPlacedWithoutMerge() } } /** Take the current piece and place it in a given cell. */ func placeCurrentPiece(_ cell: HexCell) { // Handle merging, if any self.handleMerge(cell) // Place the piece cell.hexPiece = GameState.instance!.currentPiece // Record statistic GameStats.instance!.incIntForKey(cell.hexPiece!.getStatsKey()) // Move sprite from GUI to gameboard layer GameState.instance!.currentPiece!.sprite!.move(toParent: self.gameboardLayer) // Position on gameboard GameState.instance!.currentPiece!.sprite!.position = HexMapHelper.instance.hexMapToScreen(cell.position) // Remove animation self.currentPieceSprite!.removeAllActions() self.currentPieceSprite!.isHidden = true // Award points self.awardPointsForPiece(GameState.instance!.currentPiece!) self.scrollPoints(self.lastPointsAwarded, position: GameState.instance!.currentPiece!.sprite!.position) // End turn self.turnDidEnd() } /** Use a "remove" piece on a given cell. This causes the piece currently in the cell to be removed from play. */ func playRemovePiece(_ cell: HexCell) { if (cell.hexPiece != nil) { // Let the piece know it was collected cell.hexPiece!.wasRemoved() // Clear out the hex cell cell.hexPiece = nil // Remove sprite GameState.instance!.currentPiece!.sprite!.removeFromParent() // End turn self.turnDidEnd() } } /** Captures state for undo. */ func captureState() { self.undoState = NSKeyedArchiver.archivedData(withRootObject: GameState.instance!) // Show undo button self.undoButton!.hidden = false } /** Restores the previous state from undo. */ func restoreState() { if (self.undoState != nil) { // Remove current piece, stash piece sprites self.removeTransientGuiSprites() // Clear piece sprites from rendered hexmap HexMapHelper.instance.clearHexMap(self.gameboardLayer) // Load undo state GameState.instance = (NSKeyedUnarchiver.unarchiveObject(with: self.undoState!) as? GameState)! // Get the hex map and render it self.renderFromState() // Restore bank points self.bankPoints = GameState.instance!.bankPoints // Update gui self.updateGuiLayer() // Clear undo state self.undoState = nil } } /** Called after player has placed a piece. Processes moves for mobile pieces, checks for end game state. */ func turnDidEnd() { GameStateMachine.instance!.enter(GameSceneMergingState.self) // Get all occupied cells let occupiedCells = HexMapHelper.instance.hexMap!.getOccupiedCells() // tell each piece to get ready to take a turn for occupiedCell in occupiedCells { occupiedCell.hexPiece?.preTakeTurn() } } func doMerges() { // Look for merges resulting from hexpiece turns var merges = HexMapHelper.instance.getFirstMerge(); if (merges.count>0) { var mergeFocus: HexPiece? var highestAdded = -1 var maxValue = 0 var minValue = 10000 for merged in merges { if (merged.added > highestAdded) { highestAdded = merged.added mergeFocus = merged } if (merged.value > maxValue) { maxValue = merged.value } if (merged.value < minValue) { minValue = merged.value } } // Set blocking flag self.lock.around { GameStateMachine.instance!.blocked = true } // Create merge animation let moveAction = SKAction.move(to: mergeFocus!.sprite!.position, duration: 0.25) let moveSequence = SKAction.sequence([moveAction, SKAction.removeFromParent(), SKAction.run({self.lock.around { GameStateMachine.instance!.blocked = false }})]) var actualMerged: [HexPiece] = Array() // Remove merged pieces from board for merged in merges { if (merged != mergeFocus && merged.value == minValue) { actualMerged.append(merged) merged.sprite!.run(moveSequence) merged.hexCell?.hexPiece = nil } } // add pieces which were not the merge focus to our list of pieces merged on the last turn self.mergedPieces += actualMerged // let merge focus know it was merged mergeFocus = mergeFocus!.wasPlacedWithMerge(minValue, mergingPieces: merges) self.mergesCurrentTurn += 1 // Award points self.awardPointsForPiece(mergeFocus!) self.scrollPoints(self.lastPointsAwarded, position: mergeFocus!.sprite!.position) // Record statistics GameStats.instance!.incIntForKey(mergeFocus!.getStatsKey()) // Get next merge merges = HexMapHelper.instance.getFirstMerge(); } else { GameStateMachine.instance!.enter(GameSceneEnemyState.self) } } func doAutonomousActions() { // Get all occupied cells let occupiedCells = HexMapHelper.instance.hexMap!.getOccupiedCells() // Give each piece a turn for occupiedCell in occupiedCells { occupiedCell.hexPiece?.takeTurn() } // Test for game over if (HexMapHelper.instance.hexMap!.getOpenCells().count==0) { GameStateMachine.instance!.enter(GameSceneGameOverState.self) } else { // Generate new piece self.generateCurrentPiece() // Update current piece sprite self.updateCurrentPieceSprite() // Reset merge counter self.mergesCurrentTurn = 0 // Return to playing state GameStateMachine.instance!.enter(GameScenePlayingState.self) } } override internal func update(_ currentTime: TimeInterval) { if (!GameStateMachine.instance!.blocked) { if (GameStateMachine.instance!.currentState is GameSceneMergingState) { self.doMerges() } else if (GameStateMachine.instance!.currentState is GameSceneEnemyState) { self.doAutonomousActions() } } } /** Rolls back the last move made. Places removed merged pieces back on the board, removes points awarded, and calls self.restoreLastPiece, which puts the last piece played back in the currentPiece property. */ func undoLastMove() { self.restoreState() // Hide undo button self.undoButton!.hidden = true } /** Stops merge animation on any current set of would-be merged pieces, then updates self.mergingPieces with any merges which would occur if self.curentPiece were to be placed in cell. Stats merge animation on the new set of merging pieces, if any. - Parameters: - cell: The cell to test for merging w/ the current piece */ func updateMergingPieces(_ cell: HexCell) { if (cell.willAccept(GameState.instance!.currentPiece!)) { // Stop animation on current merge set for hexPiece in self.mergingPieces { hexPiece.sprite!.removeAction(forKey: "mergeAnimation") hexPiece.sprite!.setScale(1.0) } self.mergingPieces = cell.getWouldMergeWith(GameState.instance!.currentPiece!) // Start animation on new merge set for hexPiece in self.mergingPieces { hexPiece.sprite!.removeAction(forKey: "mergeAnimation") hexPiece.sprite!.setScale(1.2) } } } func initScaling() { let width = (self.frame.width < self.frame.height) ? self.frame.width : self.frame.height if (width >= 375) { self.uiTextScale = 1.0 } else { self.uiTextScale = width / 375 } } /** Initializes GUI layer components, sets up labels, buttons, etc. */ func initGuiLayer() { // Calculate size of upper UI let upperUsableArea = (self.frame.height < self.frame.width ? self.frame.height : self.frame.width) - SNZSpriteKitUITheme.instance.uiOuterMargins.horizontal var bankButtonWidth = (upperUsableArea / 2) - (SNZSpriteKitUITheme.instance.uiInnerMargins.horizontal / 3) var currentButtonWidth = (upperUsableArea / 4) - (SNZSpriteKitUITheme.instance.uiInnerMargins.horizontal / 3) var stashButtonWidth = currentButtonWidth bankButtonWidth = bankButtonWidth > 200 ? 200 : bankButtonWidth currentButtonWidth = currentButtonWidth > 100 ? 100 : currentButtonWidth stashButtonWidth = stashButtonWidth > 100 ? 100 : stashButtonWidth // Calculate current piece home position self.currentPieceHome = CGPoint(x: 80, y: self.frame.height - 70) // Add current piece label self.currentPieceLabel = self.createUILabel("Current") self.currentPieceLabel!.position = CGPoint(x: 20, y: self.frame.height - 40) self.currentPieceLabel!.horizontalAlignmentMode = .center self.guiLayer.addChild(self.currentPieceLabel!) // Add current button self.currentButton = SNZButtonWidget() self.currentButton!.size = CGSize(width: currentButtonWidth, height: 72) self.currentButton!.position = CGPoint(x: SNZSpriteKitUITheme.instance.uiOuterMargins.left, y: self.frame.height - 90) self.currentButton!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25) self.currentButton!.focusBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.15) self.currentButton!.caption = "" self.currentButton!.bind("tap",{ if (GameStateMachine.instance!.currentState is GameScenePlayingState) { self.swapStash() } }) self.addWidget(self.currentButton!) // Calculate stash piece home position self.stashPieceHome = CGPoint(x: 180, y: self.frame.height - 70) // Add stash button self.stashButton = SNZButtonWidget() self.stashButton!.size = CGSize(width: stashButtonWidth, height: 72) self.stashButton!.position = CGPoint(x: currentButton!.position.x + (SNZSpriteKitUITheme.instance.uiInnerMargins.left) + currentButtonWidth, y: self.frame.height - 90) self.stashButton!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25) self.stashButton!.focusBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.15) self.stashButton!.caption = "" self.stashButton!.bind("tap",{ if (GameStateMachine.instance!.currentState is GameScenePlayingState) { self.swapStash() } }) self.addWidget(self.stashButton!) // Add stash piece label self.stashPieceLabel = self.createUILabel("Stash") self.stashPieceLabel!.position = CGPoint(x: 150, y: self.frame.height - 40) self.stashPieceLabel!.horizontalAlignmentMode = .center self.guiLayer.addChild(self.stashPieceLabel!) // Add stash piece sprite, if any self.updateStashPieceSprite() // Add bank label self.bankPointsLabel = self.createUILabel("Bank Points") self.bankPointsLabel!.position = CGPoint(x: self.frame.width - 100, y: self.frame.height - 120) self.bankPointsLabel!.ignoreTouches = true self.guiLayer.addChild(self.bankPointsLabel!) // Add bank display self.bankPointsDisplay = self.createUILabel(HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: self.bankPoints))!) self.bankPointsDisplay!.position = CGPoint(x: self.frame.width - 100, y: self.frame.height - 144) self.bankPointsDisplay!.fontSize = 18 * self.uiTextScale self.guiLayer.addChild(self.bankPointsDisplay!) // Add bank button self.bankButton = BankButtonWidget() self.bankButton!.size = CGSize(width: bankButtonWidth, height: 72) self.bankButton!.position = CGPoint(x: self.frame.width - 100, y: self.frame.height-90) self.bankButton!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25) self.bankButton!.focusBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.15) self.bankButton!.caption = "" self.bankButton!.bind("tap",{ if (GameStateMachine.instance!.currentState is GameScenePlayingState) { self.scene!.view?.presentScene(SceneHelper.instance.bankScene, transition: SKTransition.push(with: SKTransitionDirection.down, duration: 0.4)) } }) self.addWidget(self.bankButton!) // Add menu button self.menuButton = MergelTextureButtonWidget(parentNode: guiLayer) self.menuButton!.texture = SKTexture(imageNamed: "menu51") self.menuButton!.anchorPoint = CGPoint(x: 0,y: 0) self.menuButton!.textureScale = 0.8 self.menuButton!.bind("tap",{ self.scene!.view?.presentScene(SceneHelper.instance.levelScene, transition: SKTransition.push(with: SKTransitionDirection.up, duration: 0.4)) }) self.addWidget(self.menuButton!) // Add undo button self.undoButton = MergelTextureButtonWidget(parentNode: guiLayer) self.undoButton!.texture = SKTexture(imageNamed: "curve4") self.undoButton!.anchorPoint = CGPoint(x: 1,y: 0) self.undoButton!.bind("tap",{ self.undoLastMove() }) self.addWidget(self.undoButton!) // Add score label self.scoreLabel = self.createUILabel("Score") self.scoreLabel!.position = CGPoint(x: 20, y: self.frame.height - 120) self.guiLayer.addChild(self.scoreLabel!) // Add score display self.scoreDisplay = self.createUILabel(HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: self.score))!) self.scoreDisplay!.position = CGPoint(x: 20, y: self.frame.height - 144) self.scoreDisplay!.fontSize = 24 * self.uiTextScale self.guiLayer.addChild(self.scoreDisplay!) // Add stats button self.statsButton = SNZButtonWidget() self.statsButton!.size = CGSize(width: (self.stashButton!.position.x + self.stashButton!.size.width) - self.currentButton!.position.x, height: 62) self.statsButton!.position = CGPoint(x: 20, y: self.currentButton!.position.y - (self.currentButton!.size.height / 2) - 4 - (self.statsButton!.size.height / 2)) self.statsButton!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25) self.statsButton!.focusBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.15) self.statsButton!.caption = "" self.statsButton!.bind("tap",{ self.scene!.view?.presentScene(SceneHelper.instance.statsScene, transition: SKTransition.push(with: SKTransitionDirection.right, duration: 0.4)) }) self.addWidget(self.statsButton!) self.highScoreButton = SNZButtonWidget() self.highScoreButton!.size = CGSize(width: bankButtonWidth, height: 62) self.highScoreButton!.position = CGPoint(x: self.bankButton!.position.x, y: self.statsButton!.position.y) self.highScoreButton!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25) self.highScoreButton!.focusBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.15) self.highScoreButton!.caption = "" self.highScoreButton!.bind("tap",{ NotificationCenter.default.post(name: Notification.Name(rawValue: ShowGKGameCenterViewController), object: nil) //self.scene!.view?.presentScene(SceneHelper.instance.statsScene, transition: SKTransition.pushWithDirection(SKTransitionDirection.Right, duration: 0.4)) }) self.addWidget(self.highScoreButton!) // Add high score label self.highScoreLabel = self.createUILabel("High Score") self.highScoreLabel!.position = CGPoint(x: 20, y: self.frame.height - 170) self.highScoreLabel!.horizontalAlignmentMode = .right self.guiLayer.addChild(self.highScoreLabel!) // Add high score display self.highScoreDisplay = self.createUILabel(HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: GameState.instance!.highScore))!) self.highScoreDisplay!.position = CGPoint(x: 20, y: self.frame.height - 204) self.highScoreDisplay!.fontSize = 18 * self.uiTextScale self.highScoreDisplay!.horizontalAlignmentMode = .right self.guiLayer.addChild(self.highScoreDisplay!) // Add goal score display self.goalScoreDisplay = self.createUILabel("Goal " + HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: GameState.instance!.goalScore))!) self.goalScoreDisplay!.position = CGPoint(x: 20, y: self.frame.height - 204) self.goalScoreDisplay!.fontSize = 12 * self.uiTextScale self.goalScoreDisplay!.horizontalAlignmentMode = .right self.goalScoreDisplay!.fontColor = UIColor(red: 0xf7/255, green: 0xef/255, blue: 0xed/255, alpha: 0.8) self.guiLayer.addChild(self.goalScoreDisplay!) // Current piece caption self.buildCurrentPieceCaption() // Set initial positions self.updateGuiPositions() // Set initial visibility of undo button self.undoButton!.hidden = (GameState.instance!.lastPlacedPiece == nil); // Render the widgets self.renderWidgets() } func buildProgression() { // Progression self.currentPieceSpriteProgressionLeft = SKSpriteNode(texture: SKTexture(imageNamed: "HexCellVoid")) self.currentPieceSpriteProgressionLeft!.setScale(0.5) self.guiLayer.addChild(self.currentPieceSpriteProgressionLeft!) self.currentPieceSpriteProgressionArrow = SKSpriteNode(texture: SKTexture(imageNamed: "play-arrow")) self.currentPieceSpriteProgressionArrow!.setScale(0.15) self.guiLayer.addChild(self.currentPieceSpriteProgressionArrow!) self.currentPieceSpriteProgressionRight = SKSpriteNode(texture: SKTexture(imageNamed: "HexCellVoid")) self.currentPieceSpriteProgressionRight!.setScale(0.5) self.guiLayer.addChild(self.currentPieceSpriteProgressionRight!) } func buildCurrentPieceCaption() { var isHidden = true if (self.currentPieceCaption != nil) { isHidden = self.currentPieceCaption!.isHidden self.currentPieceCaption!.removeFromParent() } if (self.frame.width > self.frame.height) { self.currentPieceCaption = SKShapeNode(rect: CGRect(x: 0, y: 0, width: self.statsButton!.size.width, height: self.statsButton!.size.width), cornerRadius: 4) } else { self.currentPieceCaption = SKShapeNode(rect: CGRect(x: 0, y: 0, width: self.size.width - 40, height: self.statsButton!.size.height), cornerRadius: 4) } self.currentPieceCaption!.fillColor = UIColor(red: 54/255, green: 93/255, blue: 126/255, alpha: 1.0) self.currentPieceCaption!.lineWidth = 0 self.currentPieceCaption!.zPosition = 999 self.guiLayer.addChild(self.currentPieceCaption!) self.updateCurrentPieceCaption(self.currentPieceCaptionText) self.currentPieceCaption!.isHidden = isHidden } /** Updates the position of GUI elements. This gets called whem rotation changes. */ func updateGuiPositions() { if (self.currentPieceLabel != nil) { // Calculate size of upper UI let upperUsableArea = (self.frame.height < self.frame.width ? self.frame.height : self.frame.width) - SNZSpriteKitUITheme.instance.uiOuterMargins.horizontal // Calculate upper button widths var bankButtonWidth = (upperUsableArea / 2) - (SNZSpriteKitUITheme.instance.uiInnerMargins.horizontal / 3) var currentButtonWidth = (upperUsableArea / 4) - (SNZSpriteKitUITheme.instance.uiInnerMargins.horizontal / 3) var stashButtonWidth = currentButtonWidth bankButtonWidth = bankButtonWidth > 200 ? 200 : bankButtonWidth currentButtonWidth = currentButtonWidth > 100 ? 100 : currentButtonWidth stashButtonWidth = stashButtonWidth > 100 ? 100 : stashButtonWidth // Current Piece self.currentButton!.position = CGPoint(x: SNZSpriteKitUITheme.instance.uiOuterMargins.left, y: self.frame.height - 90) self.currentButton!.size = CGSize(width: currentButtonWidth, height: 72) self.currentPieceLabel!.position = CGPoint(x: self.currentButton!.position.x + (currentButtonWidth / 2), y: self.frame.height - 40) self.currentPieceHome = CGPoint(x: self.currentButton!.position.x + (currentButtonWidth / 2), y: self.frame.height - 70) if (GameState.instance!.currentPiece != nil && GameState.instance!.currentPiece!.sprite != nil) { GameState.instance!.currentPiece!.sprite!.position = self.currentPieceHome } // Current Piece Caption self.buildCurrentPieceCaption() if (self.frame.width > self.frame.height) { self.currentPieceCaption!.position = CGPoint(x: 20, y: (self.frame.height - 165) - (self.currentPieceCaption!.frame.height / 2)) } else { self.currentPieceCaption!.position = CGPoint(x: 20, y: (self.frame.height - 130) - (self.currentPieceCaption!.frame.height / 2)) } // Stash Piece self.stashButton!.position = CGPoint(x: currentButton!.position.x + (SNZSpriteKitUITheme.instance.uiInnerMargins.left) + currentButtonWidth, y: self.frame.height - 90) self.stashButton!.size = CGSize(width: stashButtonWidth, height: 72) self.stashPieceLabel!.position = CGPoint(x: self.stashButton!.position.x + (stashButtonWidth/2), y: self.frame.height - 40) self.stashPieceHome = CGPoint(x: self.stashButton!.position.x + (stashButtonWidth/2), y: self.frame.height - 70) if (GameState.instance!.stashPiece != nil && GameState.instance!.stashPiece!.sprite != nil) { GameState.instance!.stashPiece!.sprite!.position = self.stashPieceHome } // Bank Button self.bankButton!.position = CGPoint(x: self.frame.width - bankButtonWidth - SNZSpriteKitUITheme.instance.uiOuterMargins.right, y: self.frame.height-90) self.bankButton!.size = CGSize(width: bankButtonWidth, height: 72) // bank points self.bankPointsLabel!.position = CGPoint(x: self.bankButton!.position.x + SNZSpriteKitUITheme.instance.uiInnerMargins.left, y: self.frame.height - 40) self.bankPointsDisplay!.position = CGPoint(x: self.bankButton!.position.x + SNZSpriteKitUITheme.instance.uiInnerMargins.left, y: self.frame.height - 64) // Score self.scoreLabel!.position = CGPoint(x: 30, y: self.frame.height - 120) self.scoreDisplay!.position = CGPoint(x: 30, y: self.frame.height - 145) self.highScoreLabel!.position = CGPoint(x: self.frame.width - 30, y: self.frame.height - 120) self.highScoreDisplay!.position = CGPoint(x: self.frame.width - 30, y: self.frame.height - 138) self.goalScoreDisplay!.position = CGPoint(x: self.frame.width - 30, y: self.frame.height - 150) // Stats button self.statsButton!.position = CGPoint(x: 20, y: self.currentButton!.position.y - (self.currentButton!.size.height / 2) - 4 - (self.statsButton!.size.height / 2)) // High Score button self.highScoreButton!.position = CGPoint(x: self.bankButton!.position.x, y: self.statsButton!.position.y) // Gameboard self.updateGameboardLayerPosition() // Widgets self.updateWidgets() // Progression self.currentPieceSpriteProgressionLeft!.position = CGPoint(x: 38, y: self.frame.height - 180) self.currentPieceSpriteProgressionArrow!.position = CGPoint(x: 58, y: self.frame.height - 177) self.currentPieceSpriteProgressionRight!.position = CGPoint(x: 78, y: self.frame.height - 180) } } /** Scales and positions the gameboard to fit the current screen size and orientation. */ func updateGameboardLayerPosition() { if (HexMapHelper.instance.hexMap != nil) { var scale: CGFloat = 1.0 var shiftY: CGFloat = 0 let marginPortrait: CGFloat = 30 let marginLandscape: CGFloat = 60 let gameboardWidth = HexMapHelper.instance.getRenderedWidth() let gameboardHeight = HexMapHelper.instance.getRenderedHeight() // Calculate scaling factor to make gameboard fit screen if (self.frame.width > self.frame.height) { // landscape scale = self.frame.height / (gameboardHeight + marginLandscape) } else { // portrait scale = self.frame.width / (gameboardWidth + marginPortrait) shiftY = 50 // shift down a little bit if we are in portrait, so that we don't overlap UI elements. } // Scale gameboard layer self.gameboardLayer.setScale(scale) // Reposition gameboard layer to center in view self.gameboardLayer.position = CGPoint(x: ((self.frame.width) - (gameboardWidth * scale))/2, y: (((self.frame.height) - (gameboardHeight * scale))/2) - shiftY) } } /** Helper function to create an instance of SKLabelNode with typical defaults for our GUI and a specified caption. - Parameters: - caption: The caption for the label node - Returns: An instance of SKLabelNode, initialized with caption and gui defaults. */ func createUILabel(_ caption: String, baseFontSize: CGFloat = 18) -> SKLabelNode { let label = SKLabelNode(text: caption) label.fontColor = UIColor(red: 0xf7/255, green: 0xef/255, blue: 0xed/255, alpha: 1.0) label.fontSize = baseFontSize * self.uiTextScale label.zPosition = 20 label.fontName = "Avenir-Black" label.ignoreTouches = true label.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left return label } /** Remove sprites which are not a static part of the gui - the current piece and the stash piece. */ func removeTransientGuiSprites() { if (GameState.instance!.stashPiece != nil) { if (GameState.instance!.stashPiece!.sprite != nil) { GameState.instance!.stashPiece!.sprite!.removeFromParent() } } if (GameState.instance!.currentPiece != nil) { if (GameState.instance!.currentPiece!.sprite != nil) { GameState.instance!.currentPiece!.sprite!.removeFromParent() } } } /** Helper method to call all of the various gui update methods. */ func updateGuiLayer() { self.updateStashPieceSprite() self.updateScore() self.updateHighScore() self.updateCurrentPieceSprite() self.updateGuiPositions() } /** Refresh the current stash piece sprite. We call createSprite method of the stash piece to get the new sprite, so that we also get any associated animations, etc. */ func updateStashPieceSprite() { if (GameState.instance!.stashPiece != nil) { if (GameState.instance!.stashPiece!.sprite == nil) { GameState.instance!.stashPiece!.sprite = GameState.instance!.stashPiece!.createSprite() GameState.instance!.stashPiece!.sprite!.position = self.stashPieceHome self.guiLayer.addChild(GameState.instance!.stashPiece!.sprite!) } else { GameState.instance!.stashPiece!.sprite!.removeFromParent() GameState.instance!.stashPiece!.sprite = GameState.instance!.stashPiece!.createSprite() GameState.instance!.stashPiece!.sprite!.position = self.stashPieceHome self.guiLayer.addChild(GameState.instance!.stashPiece!.sprite!) } } } /** Refreshes the text of the score display with a formatted copy of the current self.score value */ func updateScore() { if (self.scoreDisplay != nil) { self.scoreDisplay!.text = HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: self.score)) } } /** Refreshes the bank point display with a formatted copy of the current self.bankPoints value. */ func updateBankPoints() { if (self.bankPointsDisplay != nil) { self.bankPointsDisplay!.text = HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: self.bankPoints)) } } /** Refreshes the text of the high score display with a formatted copy of the current high score value */ func updateHighScore() { if (self.highScoreDisplay != nil) { self.highScoreDisplay!.text = HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: GameState.instance!.highScore)) } } /** Scrolls a number upward with a fade-out animation, starting from a given point. */ func scrollPoints(_ points: Int, position: CGPoint) { if (points > 0) { let scrollUp = SKAction.moveBy(x: 0, y: 100, duration: 1.5) let fadeOut = SKAction.fadeAlpha(to: 0, duration: 1.5) let remove = SKAction.removeFromParent() let scrollFade = SKAction.sequence([SKAction.group([scrollUp, fadeOut]),remove]) let pointString:String = HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: points))! let label = SKLabelNode(text: pointString) switch (self.mergesCurrentTurn) { case 0...1: label.fontColor = UIColor.white break; case 2: label.fontColor = UIColor.yellow case 3: label.fontColor = UIColor.green case 4...99: label.fontColor = UIColor.cyan default: label.fontColor = UIColor.white break; } label.fontSize = CGFloat(20 + pointString.characters.count) * self.uiTextScale + (CGFloat(self.mergesCurrentTurn - 1) * 2) label.zPosition = 30 label.position = position label.fontName = "Avenir-Black" self.gameboardLayer.addChild(label) label.run(scrollFade) } } /** Calculates and applies a multiplier to the fontSize of an SKLabelNode to make it fit in a given rectangle. */ func scaleToFitRect(_ node:SKLabelNode, rect:CGRect) { node.fontSize *= min(rect.width / node.frame.width, rect.height / node.frame.height) } /** Displays a message with a scale up, pause, and fade out effect, centered on the screen. - Parameters: - message: The message to be displayed. Newline (\n) characters in the message will be used as delimiters for the creation of separate SKLabelNodes, effectively allowing for the display of multi-line messages. - action: If provided, an SKAction which should be called once the fade-out animation completes. */ func burstMessage(_ message: String, action: SKAction? = nil) { let tokens = message.components(separatedBy: "\n").reversed() var totalHeight:CGFloat = 0 let padding:CGFloat = 20 var labels: [SKLabelNode] = Array() for token in tokens { let label = ShadowLabelNode(text: token) label.fontColor = UIColor.white label.zPosition = 1000 label.fontName = "Avenir-Black" label.fontSize = 20 self.scaleToFitRect(label, rect: self.frame.insetBy(dx: 30, dy: 30)) totalHeight += label.frame.height + padding label.position = CGPoint(x: self.frame.width / 2, y: (self.frame.height / 2)) label.updateShadow() labels.append(label) } // Create the burst animation sequence var burstSequence: [SKAction] = [ SKAction.scale(to: 1.2, duration: 0.4), SKAction.scale(to: 0.8, duration: 0.2), SKAction.scale(to: 1.0, duration: 0.2), SKAction.wait(forDuration: 2.0), SKAction.group([ SKAction.scale(to: 5.0, duration: 1.0), SKAction.fadeOut(withDuration: 1.0) ]) ] // Append the action parameter, if provided if (action != nil) { burstSequence.append(action!) } let burstAnimation = SKAction.sequence(burstSequence) var verticalOffset:CGFloat = 0 for label in labels { label.position.y = (self.frame.height / 2) - (totalHeight / 2) + (label.frame.height / 2) + verticalOffset verticalOffset += padding + label.frame.height label.setScale(0) SceneHelper.instance.gameScene.addChild(label) label.run(burstAnimation) } } func initGameOver() { let label = ShadowLabelNode(text: "GAME OVER") label.fontColor = UIColor.white label.fontSize = 64 * self.uiTextScale label.zPosition = 1000 label.fontName = "Avenir-Black" self.scaleToFitRect(label, rect: self.frame.insetBy(dx: 30, dy: 30)) label.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2) label.updateShadow() self.gameOverLabel = label; } func showGameOver() { // Play game over sound self.run(SoundHelper.instance.gameover) // Disable Undo self.undoButton!.hidden = true self.undoState = nil // Create game over label self.initGameOver() // Show game over message and display Game Over label afterward self.burstMessage("NO MOVES REMAINING", action: SKAction.run({ SceneHelper.instance.gameScene.addChild(self.gameOverLabel!) })) // Send score to game center GameStats.instance!.updateGameCenter() } func hideGameOver() { if (self.gameOverLabel != nil && self.gameOverLabel!.parent != nil) { self.gameOverLabel!.removeFromParent() } } /** Generates a point value and applies it to self.score, based on the piece specified. - Parameters: - hexPiece: The piece for which points are being awarded. */ func awardPointsForPiece(_ hexPiece: HexPiece) { var modifier = self.mergingPieces.count-1 if (modifier < 1) { modifier = 1 } self.awardPoints(hexPiece.getPointValue() * modifier * (self.mergesCurrentTurn > 0 ? self.mergesCurrentTurn : 1)) } func awardPoints(_ points: Int) { self.lastPointsAwarded = points self.score += lastPointsAwarded // Bank 1% self.bankPoints += Int(Double(points) * 0.01) self.checkForUnlocks() } func checkForUnlocks() { // Debug Level /*if (!GameState.instance!.unlockedLevels.contains(.Debug)) { GameState.instance!.unlockedLevels.append(.Debug) }*/ if ((LevelHelper.instance.mode == .hexagon || LevelHelper.instance.mode == .welcome) && !GameState.instance!.unlockedLevels.contains(.pit) && self.score >= 500000) { GameState.instance!.unlockedLevels.append(.pit) self.burstMessage("New Map Unlocked\nTHE PIT") } if (LevelHelper.instance.mode == .pit && !GameState.instance!.unlockedLevels.contains(.moat) && self.score >= 1000000) { GameState.instance!.unlockedLevels.append(.moat) self.burstMessage("New Map Unlocked\nTHE MOAT") } // Check for goal reached if (self.score >= GameState.instance!.goalScore) { let bankPoints = Int(Double(GameState.instance!.goalScore) * 0.05) self.burstMessage("GOAL REACHED\nEarned "+HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: bankPoints))!+" Bank Points") self.bankPoints += bankPoints self.updateBankPoints() GameState.instance!.goalScore *= 2; self.goalScoreDisplay!.text = "Goal " + HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: GameState.instance!.goalScore))!; } } /** Gets the next piece from the level helper and assigns it to GameState.instance!.currentPiece. This is the piece which will be placed if the player touches a valid cell on the gameboard. */ func generateCurrentPiece() { GameState.instance!.currentPiece = LevelHelper.instance.popPiece() } func setCurrentPiece(_ hexPiece: HexPiece) { if (GameState.instance!.currentPiece!.sprite != nil) { GameState.instance!.currentPiece!.sprite!.removeFromParent() } GameState.instance!.currentPiece = hexPiece self.updateCurrentPieceSprite() } func spendBankPoints(_ points: Int) { self.bankPoints -= points } func updateCurrentPieceSprite(_ relocate: Bool = true) { var position: CGPoint? if (GameState.instance!.currentPiece != nil) { if (!relocate) { position = self.currentPieceSprite!.position } // Sprite to go in the GUI if (GameState.instance!.currentPiece!.sprite != nil && GameState.instance!.currentPiece!.sprite!.parent != nil) { GameState.instance!.currentPiece!.sprite!.removeFromParent() } // Generate sprite GameState.instance!.currentPiece!.sprite = GameState.instance!.currentPiece!.createSprite() // Ignore touches GameState.instance!.currentPiece!.sprite!.ignoreTouches = true GameState.instance!.currentPiece!.sprite!.position = self.currentPieceHome GameState.instance!.currentPiece!.sprite!.zPosition = 10 guiLayer.addChild(GameState.instance!.currentPiece!.sprite!) // Sprite to go on the game board if (self.currentPieceSprite != nil) { self.currentPieceSprite!.removeFromParent() } // Create sprite self.currentPieceSprite = GameState.instance!.currentPiece!.createSprite() // Ignore touches self.currentPieceSprite!.ignoreTouches = true // fix z position self.currentPieceSprite!.zPosition = 999 // Pulsate self.currentPieceSprite!.run(SKAction.repeatForever(SKAction.sequence([ SKAction.scale(to: 1.4, duration: 0.4), SKAction.scale(to: 0.8, duration: 0.4) ]))) if (relocate || position == nil) { var targetCell: HexCell? // Either use last placed piece, or center of game board, for target position if (GameState.instance!.lastPlacedPiece != nil && GameState.instance!.lastPlacedPiece!.hexCell != nil) { targetCell = GameState.instance!.lastPlacedPiece!.hexCell! } else { targetCell = HexMapHelper.instance.hexMap!.cell(Int(HexMapHelper.instance.hexMap!.width/2), Int(HexMapHelper.instance.hexMap!.height/2))! } // Get a random open cell near the target position let boardCell = HexMapHelper.instance.hexMap!.getRandomCellNear(targetCell!) // Get cell position if (boardCell != nil) { position = HexMapHelper.instance.hexMapToScreen(boardCell!.position) } } // Position sprite if (position != nil) { // position will be nil if board is full self.currentPieceSprite!.position = position! self.gameboardLayer.addChild(self.currentPieceSprite!) } // Update caption, if any if (self.currentPieceCaption != nil) { if (GameState.instance!.currentPiece!.caption != "") { self.currentPieceCaption!.isHidden = false self.updateCurrentPieceCaption(GameState.instance!.currentPiece!.caption) } else { self.currentPieceCaption!.isHidden = true self.currentPieceCaptionText = "" } } self.updateProgression() } } func updateProgression() { // Update progression sprites if (self.currentPieceSpriteProgressionLeft != nil) { let progressionRight = GameState.instance!.currentPiece!.createMergedSprite() if (progressionRight == nil) { self.currentPieceSpriteProgressionLeft!.isHidden = true self.currentPieceSpriteProgressionArrow!.isHidden = true self.currentPieceSpriteProgressionRight!.isHidden = true } else { if (GameState.instance!.currentPiece!.sprite != nil) { self.currentPieceSpriteProgressionLeft!.texture = GameState.instance!.currentPiece!.sprite!.texture self.currentPieceSpriteProgressionLeft!.isHidden = false self.currentPieceSpriteProgressionArrow!.isHidden = false self.currentPieceSpriteProgressionRight!.texture = progressionRight!.texture self.currentPieceSpriteProgressionRight!.isHidden = false } } } } func updateCurrentPieceCaption(_ caption: String) { self.currentPieceCaptionText = caption self.currentPieceCaption!.removeAllChildren() let tokens = caption.components(separatedBy: " ") var idx = 0 var token = "" var label = self.createUILabel("", baseFontSize: 14) var priorText = "" var verticalOffset:CGFloat = self.currentPieceCaption!.frame.height / 2 let horizontalOffset:CGFloat = self.currentPieceCaption!.frame.width / 2 var lineHeight:CGFloat = 0 var totalHeight:CGFloat = 0 while (idx < tokens.count) { token = tokens[idx] priorText = label.text! label.text = label.text!+" "+token if (label.frame.width > (self.currentPieceCaption!.frame.width) - 20) { label.text = priorText label.horizontalAlignmentMode = .center label.position = CGPoint(x: horizontalOffset,y: verticalOffset) self.currentPieceCaption!.addChild(label) verticalOffset -= 20 totalHeight += label.frame.height label = self.createUILabel("", baseFontSize: 14) } else { idx += 1 } if (lineHeight == 0) { lineHeight = label.frame.height } } if (label.text != "") { label.horizontalAlignmentMode = .center label.position = CGPoint(x: horizontalOffset,y: verticalOffset) self.currentPieceCaption!.addChild(label) totalHeight += label.frame.height } // Vertically center the entire block for label in self.currentPieceCaption!.children { label.position.y += (totalHeight / 2) - (lineHeight / 2) } } /** Swaps GameState.instance!.currentPiece with the piece currently in the stash, if any. If no piece is in the stash, a new currentPiece is geneated and the old currentPiece is placed in the stash. */ func swapStash() { // Clear any caption when piece is going to be swapped in to stash GameState.instance!.currentPiece!.caption = "" // Handle the swap if (GameState.instance!.stashPiece != nil) { let tempPiece = GameState.instance!.currentPiece! GameState.instance!.currentPiece = GameState.instance!.stashPiece GameState.instance!.stashPiece = tempPiece GameState.instance!.currentPiece!.sprite!.run(SKAction.move(to: self.currentPieceHome, duration: 0.1)) GameState.instance!.stashPiece!.sprite!.run(SKAction.sequence([SKAction.move(to: self.stashPieceHome, duration: 0.1),SKAction.run({ self.updateCurrentPieceSprite(false) })])) } else { GameState.instance!.stashPiece = GameState.instance!.currentPiece GameState.instance!.stashPiece!.sprite!.run(SKAction.sequence([SKAction.move(to: self.stashPieceHome, duration: 0.1),SKAction.run({ self.generateCurrentPiece() self.updateCurrentPieceSprite(false) })])) self.generateCurrentPiece() } } }
2b465b6e52663c33f4b836c27edf669a
39.707541
252
0.590924
false
false
false
false
s-aska/Justaway-for-iOS
refs/heads/master
Justaway/MentionsTableViewController.swift
mit
1
// // MentionsTableViewController.swift // Justaway // // Created by Shinichiro Aska on 5/22/16. // Copyright © 2016 Shinichiro Aska. All rights reserved. // import Foundation import KeyClip import Async class MentionsTableViewController: StatusTableViewController { override func saveCache() { if self.adapter.rows.count > 0 { guard let account = AccountSettingsStore.get()?.account() else { return } let key = "mentions:\(account.userID)" let statuses = self.adapter.statuses let dictionary = ["statuses": ( statuses.count > 100 ? Array(statuses[0 ..< 100]) : statuses ).map({ $0.dictionaryValue })] KeyClip.save(key, dictionary: dictionary as NSDictionary) NSLog("notifications saveCache.") } } override func loadCache(_ success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) { adapter.activityMode = true Async.background { guard let account = AccountSettingsStore.get()?.account() else { return } let key = "mentions:\(account.userID)" if let cache = KeyClip.load(key) as NSDictionary? { if let statuses = cache["statuses"] as? [[String: AnyObject]] { success(statuses.map({ TwitterStatus($0) })) return } } success([TwitterStatus]()) Async.background(after: 0.4, { () -> Void in self.refresh() }) } } override func loadData(_ maxID: String?, success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) { Twitter.getMentionTimeline(maxID: maxID, success: success, failure: failure) } override func loadData(sinceID: String?, maxID: String?, success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) { Twitter.getMentionTimeline(maxID: maxID, sinceID: sinceID, success: success, failure: failure) } override func accept(_ status: TwitterStatus) -> Bool { if let accountSettings = AccountSettingsStore.get() { for mention in status.mentions { if accountSettings.isMe(mention.userID) { return true } } } return false } }
dac6631444de76b6c9b359d2b0c62bdb
36.089552
171
0.577465
false
false
false
false
alblue/swift
refs/heads/master
validation-test/Sema/type_checker_perf/fast/rdar22770433.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 -swift-version 5 -solver-disable-shrink -disable-constraint-solver-performance-hacks -solver-enable-operator-designated-types // REQUIRES: tools-release,no_asserts func test(n: Int) -> Int { return n == 0 ? 0 : (0..<n).reduce(0) { ($0 > 0 && $1 % 2 == 0) ? ((($0 + $1) - ($0 + $1)) / ($1 - $0)) + (($0 + $1) / ($1 - $0)) : $0 } }
708b87f17b93b533b11c0dc0e8c34285
50.75
200
0.586957
false
true
false
false
Asky314159/jrayfm-controlboard
refs/heads/main
ios/JRay FM/SecondViewController.swift
mit
1
// // SecondViewController.swift // JRay FM // // Created by Jonathan Ray on 4/10/16. // Copyright © 2016 Jonathan Ray. All rights reserved. // import MediaPlayer import UIKit class SecondViewController: UITableViewController, MPMediaPickerControllerDelegate { @IBOutlet var editButton: UIBarButtonItem! @IBOutlet var doneButton: UIBarButtonItem! private var engine: JRayFMEngine! private var defaultEntryImage: UIImage! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let appDelegate = UIApplication.shared.delegate as! AppDelegate self.engine = appDelegate.engine self.defaultEntryImage = UIImage(systemName: "tv.music.note.fill") self.editButtonVisible(animate: false); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func addLibraryItem(_ sender: AnyObject) { let mediaPicker = MPMediaPickerController(mediaTypes: MPMediaType.music) mediaPicker.allowsPickingMultipleItems = true mediaPicker.showsCloudItems = true mediaPicker.delegate = self mediaPicker.prompt = "Add songs to library" self.present(mediaPicker, animated: true, completion: nil) } func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) { self.dismiss(animated: true, completion: nil) engine.addItemsToLibrary(items: mediaItemCollection.items) tableView.reloadData() } func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) { self.dismiss(animated: true, completion: nil) } override func numberOfSections(in tableView: UITableView) -> Int { return engine.getSectionCount() } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return engine.getSectionTitle(section: section) } override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return engine.getSectionTitles() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return engine.getItemCount(section: section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let entry = engine.getItemAtIndex(section: indexPath.section, index: indexPath.item) cell.textLabel?.text = entry.name cell.detailTextLabel?.text = entry.artist if entry.image != nil { cell.imageView?.image = entry.image } else { cell.imageView?.image = self.defaultEntryImage cell.imageView?.tintColor = UIColor.label } return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCell.EditingStyle.delete { engine.removeItemAtIndex(section: indexPath.section, index: indexPath.item) tableView.reloadData() } } @IBAction func editButtonPressed(_ sender: Any) { self.doneButtonVisible(animate: true) tableView.setEditing(true, animated: true) } @IBAction func doneButtonPressed(_ sender: Any) { self.editButtonVisible(animate: true) tableView.setEditing(false, animated: true) } func editButtonVisible(animate: Bool) { self.navigationItem.setLeftBarButtonItems([editButton], animated: animate) } func doneButtonVisible(animate:Bool) { self.navigationItem.setLeftBarButtonItems([doneButton], animated: animate) } }
c794f2d73e9291eeca5d3d4cfdbc5608
34.438596
137
0.679208
false
false
false
false
gowansg/firefox-ios
refs/heads/master
Providers/ProfilePrefs.swift
mpl-2.0
3
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared public class NSUserDefaultsProfilePrefs: Prefs { private let profile: Profile private let prefix: String private let userDefaults: NSUserDefaults init(profile: Profile, prefix: String, userDefaults: NSUserDefaults) { self.profile = profile self.prefix = prefix self.userDefaults = userDefaults } init(profile: Profile) { self.profile = profile self.prefix = profile.localName() + "." self.userDefaults = NSUserDefaults(suiteName: ExtensionUtils.sharedContainerIdentifier())! } public func branch(branch: String) -> Prefs { let prefix = self.prefix + branch + "." return NSUserDefaultsProfilePrefs(profile: self.profile, prefix: prefix, userDefaults: self.userDefaults) } // Preferences are qualified by the profile's local name. // Connecting a profile to a Firefox Account, or changing to another, won't alter this. private func qualifyKey(key: String) -> String { return self.prefix + key } public func setInt(value: Int32, forKey defaultName: String) { // Why aren't you using userDefaults.setInteger? // Because userDefaults.getInteger returns a non-optional; it's impossible // to tell whether there's a value set, and you thus can't distinguish // between "not present" and zero. // Yeah, NSUserDefaults is meant to be used for storing "defaults", not data. setObject(NSNumber(int: value), forKey: defaultName) } public func setLong(value: UInt64, forKey defaultName: String) { setObject(NSNumber(unsignedLongLong: value), forKey: defaultName) } public func setLong(value: Int64, forKey defaultName: String) { setObject(NSNumber(longLong: value), forKey: defaultName) } public func setString(value: String, forKey defaultName: String) { setObject(value, forKey: defaultName) } public func setObject(value: AnyObject?, forKey defaultName: String) { userDefaults.setObject(value, forKey: qualifyKey(defaultName)) } public func stringForKey(defaultName: String) -> String? { // stringForKey converts numbers to strings, which is almost always a bug. return userDefaults.objectForKey(qualifyKey(defaultName)) as? String } public func boolForKey(defaultName: String) -> Bool? { // boolForKey just returns false if the key doesn't exist. We need to // distinguish between false and non-existent keys, so use objectForKey // and cast the result instead. return userDefaults.objectForKey(qualifyKey(defaultName)) as? Bool } private func nsNumberForKey(defaultName: String) -> NSNumber? { return userDefaults.objectForKey(qualifyKey(defaultName)) as? NSNumber } public func unsignedLongForKey(defaultName: String) -> UInt64? { return nsNumberForKey(defaultName)?.unsignedLongLongValue } public func longForKey(defaultName: String) -> Int64? { return nsNumberForKey(defaultName)?.longLongValue } public func intForKey(defaultName: String) -> Int32? { return nsNumberForKey(defaultName)?.intValue } public func stringArrayForKey(defaultName: String) -> [String]? { let objects = userDefaults.stringArrayForKey(qualifyKey(defaultName)) if let strings = objects as? [String] { return strings } return nil } public func arrayForKey(defaultName: String) -> [AnyObject]? { return userDefaults.arrayForKey(qualifyKey(defaultName)) } public func dictionaryForKey(defaultName: String) -> [String : AnyObject]? { return userDefaults.dictionaryForKey(qualifyKey(defaultName)) as? [String:AnyObject] } public func removeObjectForKey(defaultName: String) { userDefaults.removeObjectForKey(qualifyKey(defaultName)) } public func clearAll() { // TODO: userDefaults.removePersistentDomainForName() has no effect for app group suites. // iOS Bug? Iterate and remove each manually for now. for key in userDefaults.dictionaryRepresentation().keys { userDefaults.removeObjectForKey(key as! String) } } }
bf7d60fc75bc0f132eeaa1044772c492
37.474138
113
0.68743
false
false
false
false
PrinceChen/DouYu
refs/heads/master
DouYu/DouYu/Classes/Main/ViewModel/BaseViewModel.swift
mit
1
// // BaseViewModel.swift // DouYu // // Created by prince.chen on 2017/3/3. // Copyright © 2017年 prince.chen. All rights reserved. // import UIKit class BaseViewModel { lazy var anchorGroups:[AnchorGroup] = [AnchorGroup]() } extension BaseViewModel { func loadAnchorData(isGroupData: Bool, URLString: String, parameters: [String: Any]? = nil, finishedCallback: @escaping () -> ()) { NetworkTools.requestData(type: .get, URLString: URLString) { (result) in guard let resultDict = result as? [String : Any] else { return } guard let dataArray = resultDict["data"] as? [[String : Any]] else {return} if isGroupData { for dict in dataArray { self.anchorGroups.append(AnchorGroup(dict: dict)) } } else { let group = AnchorGroup() for dict in dataArray { group.anchors.append(AnchorModel(dict: dict)) } self.anchorGroups.append(group) } finishedCallback() } } }
fce476203e9ed9504f033611804f131b
26.5
135
0.514876
false
false
false
false
crazymaik/AssertFlow
refs/heads/master
Sources/Matcher/CollectionTypeMatcher.swift
mit
1
import Foundation public extension MatcherType where Element: Collection, Element.Iterator.Element: Equatable { typealias Item = Element.Iterator.Element @discardableResult public func contains(_ expected: Item) -> Self { if unpack() { for e in actual { if expected == e { return self } } fail("Expected \(Element.self) to contain:", expected: expected, actualMsg: "But was: ", actual: actual) } return self } @discardableResult public func containsInOrder(_ expected: Item...) -> Self { if unpack() { var g = expected.makeIterator() var next = g.next() for e in actual { if next == e { next = g.next() if next == nil { return self } } } fail("Expected sequence to contain in order \(expected)") } return self } @discardableResult public func containsOneOf(_ expected: Item...) -> Self { if unpack() { for e in expected { for a in actual { if (a == e) { return self } } } fail("Expected sequence to contain one of \(expected)") } return self } @discardableResult public func isEmpty() -> Self { if unpack() { if !actual.isEmpty { fail("Expected collection to be empty") } } return self } @discardableResult public func hasCount(_ expected: Element.IndexDistance) -> Self { if unpack() { let count = actual.count if count != expected { fail("Expected collection count to be \(expected), but was \(count)") } } return self } }
1852c35733735947700228952dc3c3c8
26.851351
116
0.454634
false
false
false
false
Clean-Swift/CleanStore
refs/heads/master
CleanStore/Scenes/CreateOrder/CreateOrderRouter.swift
mit
1
// // CreateOrderRouter.swift // CleanStore // // Created by Raymond Law on 2/12/19. // Copyright (c) 2019 Clean Swift LLC. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit @objc protocol CreateOrderRoutingLogic { func routeToListOrders(segue: UIStoryboardSegue?) func routeToShowOrder(segue: UIStoryboardSegue?) } protocol CreateOrderDataPassing { var dataStore: CreateOrderDataStore? { get } } class CreateOrderRouter: NSObject, CreateOrderRoutingLogic, CreateOrderDataPassing { weak var viewController: CreateOrderViewController? var dataStore: CreateOrderDataStore? // MARK: Routing func routeToListOrders(segue: UIStoryboardSegue?) { if let segue = segue { let destinationVC = segue.destination as! ListOrdersViewController var destinationDS = destinationVC.router!.dataStore! passDataToListOrders(source: dataStore!, destination: &destinationDS) } else { let index = viewController!.navigationController!.viewControllers.count - 2 let destinationVC = viewController?.navigationController?.viewControllers[index] as! ListOrdersViewController var destinationDS = destinationVC.router!.dataStore! passDataToListOrders(source: dataStore!, destination: &destinationDS) navigateToListOrders(source: viewController!, destination: destinationVC) } } func routeToShowOrder(segue: UIStoryboardSegue?) { if let segue = segue { let destinationVC = segue.destination as! ShowOrderViewController var destinationDS = destinationVC.router!.dataStore! passDataToShowOrder(source: dataStore!, destination: &destinationDS) } else { let index = viewController!.navigationController!.viewControllers.count - 2 let destinationVC = viewController?.navigationController?.viewControllers[index] as! ShowOrderViewController var destinationDS = destinationVC.router!.dataStore! passDataToShowOrder(source: dataStore!, destination: &destinationDS) navigateToShowOrder(source: viewController!, destination: destinationVC) } } // MARK: Navigation func navigateToListOrders(source: CreateOrderViewController, destination: ListOrdersViewController) { source.navigationController?.popViewController(animated: true) } func navigateToShowOrder(source: CreateOrderViewController, destination: ShowOrderViewController) { source.navigationController?.popViewController(animated: true) } // MARK: Passing data func passDataToListOrders(source: CreateOrderDataStore, destination: inout ListOrdersDataStore) { } func passDataToShowOrder(source: CreateOrderDataStore, destination: inout ShowOrderDataStore) { destination.order = source.orderToEdit } }
1f3eda9b99f8141bccb430d9ed399e1f
33
115
0.75917
false
false
false
false
hongyuanjiang/Tipping-O
refs/heads/master
Calculator/ViewController.swift
apache-2.0
1
// // ViewController.swift // Calculator // // Created by Hongyuan Jiang on 2/4/17. // Copyright © 2017 Hongyuan Jiang. All rights reserved. // import UIKit class ViewController: UIViewController, AKPickerViewDataSource, AKPickerViewDelegate { @IBOutlet var pickerView: AKPickerView! let tiptitles = ["10%", "15%", "18%", "20%", "30%"] let tippercents = [0.1, 0.15, 0.18, 0.2, 0.3] @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var billField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.pickerView.delegate = self self.pickerView.dataSource = self self.pickerView.font = UIFont(name: "HelveticaNeue-Light", size: 20)! self.pickerView.highlightedFont = UIFont(name: "HelveticaNeue-Light", size: 20)! self.pickerView.pickerViewStyle = .flat self.pickerView.maskDisabled = false self.pickerView.reloadData() self.view.layer.insertSublayer(CAGradientLayer(), at:0) self.pickerView.selectItem(1) self.billField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func calculateTip(_ sender: Any) { let bill = Double(billField.text!) ?? 0 let tip = bill * tippercents[self.pickerView.selectedItem] let total = bill + tip totalLabel.text = String(format: "$%.2f", total) tipLabel.text = String(format: "$%.2f + $%.2f", bill, tip) } func numberOfItemsInPickerView(_ pickerView: AKPickerView) -> Int { return self.tiptitles.count } func pickerView(_ pickerView: AKPickerView, titleForItem item: Int) -> String { return self.tiptitles[item] } func pickerView(_ pickerView: AKPickerView, didSelectItem item: Int) { self.calculateTip(pickerView) var background = CAGradientLayer() if item == 0 { background = CAGradientLayer().blueColor() } else if item == 1 { background = CAGradientLayer().turquoiseColor() } else if item == 2 { background = CAGradientLayer().purpleColor() } else if item == 3 { background = CAGradientLayer().pinkColor() } else if item == 4 { background = CAGradientLayer().orangeColor() } background.frame = self.view.bounds self.view.layer.replaceSublayer((self.view.layer.sublayers?[0])!, with: background) } func pickerView(_ pickerView: AKPickerView, configureLabel label: UILabel, forItem item: Int) { label.textColor = UIColor(red:(255/255.0),green:(255/255.0), blue: (255/255.0), alpha:0.5) label.highlightedTextColor = UIColor(red:(255/255.0),green:(255/255.0), blue: (255/255.0), alpha:1) } func pickerView(_ pickerView: AKPickerView, marginForItem item: Int) -> CGSize { return CGSize(width: 40, height: 20) } func scrollViewDidScroll(_ scrollView: UIScrollView) { // println("\(scrollView.contentOffset.x)") } }
f0e720f5d2fcbd7dc9a478f14524aac7
28.818966
104
0.601908
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/Components/WebView/Router/WebViewRouter.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import RxCocoa import RxRelay import RxSwift import UIComponentsKit public final class WebViewRouter: WebViewRouterAPI { // MARK: - Exposed public let launchRelay = PublishRelay<TitledLink>() // MARK: - Private private var launch: Signal<TitledLink> { launchRelay.asSignal() } private let disposeBag = DisposeBag() // MARK: - Injected private let topMostViewControllerProvider: TopMostViewControllerProviding private let webViewServiceAPI: WebViewServiceAPI // MARK: - Setup public init( topMostViewControllerProvider: TopMostViewControllerProviding = resolve(), webViewServiceAPI: WebViewServiceAPI = resolve() ) { self.topMostViewControllerProvider = topMostViewControllerProvider self.webViewServiceAPI = webViewServiceAPI launch .map(\.url) .emit(onNext: { [weak self] url in guard let self = self else { return } guard let topViewController = self.topMostViewControllerProvider.topMostViewController else { return } self.webViewServiceAPI.openSafari(url: url, from: topViewController) }) .disposed(by: disposeBag) } }
3fadc9de6d42719ea955eb1c8f690b2a
26.979167
109
0.661206
false
false
false
false
KyoheiG3/PagingView
refs/heads/master
PagingViewExample/PagingViewExample/DemoViewController.swift
mit
1
// // DemoViewController.swift // PagingViewExample // // Created by Kyohei Ito on 2015/09/03. // Copyright © 2015年 kyohei_ito. All rights reserved. // import UIKit import PagingView class DemoViewController: UIViewController { @IBOutlet weak var pagingView: PagingView! let imageNames: [String] = ["1", "2", "3", "4", "5"] override func viewDidLoad() { super.viewDidLoad() pagingView.dataSource = self pagingView.delegate = self pagingView.pagingMargin = 10 pagingView.pagingInset = 30 let nib = UINib(nibName: "DemoViewCell", bundle: nil) pagingView.registerNib(nib, forCellWithReuseIdentifier: "DemoViewCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension DemoViewController: PagingViewDataSource, PagingViewDelegate, UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { if let centerCell = pagingView.visibleCenterCell() { let imageName = imageNames[centerCell.indexPath.item] title = imageName } } func pagingView(_ pagingView: PagingView, numberOfItemsInSection section: Int) -> Int { return imageNames.count } func pagingView(_ pagingView: PagingView, cellForItemAtIndexPath indexPath: IndexPath) -> PagingViewCell { let cell = pagingView.dequeueReusableCellWithReuseIdentifier("DemoViewCell") if let cell = cell as? DemoViewCell { let imageName = imageNames[indexPath.item] cell.imageView.image = UIImage(named: imageName) } return cell } }
6a920294469387886eea51a106ac7823
30.071429
110
0.663793
false
false
false
false
DanielAsher/Side-Menu.iOS
refs/heads/master
BBSwiftFramework/Class/Extern/3rdParty/SideMenu/MenuItemsAnimator.swift
mit
2
// // Copyright © 2014 Yalantis // Licensed under the MIT license: http://opensource.org/licenses/MIT // Latest version can be found at http://github.com/yalantis/Side-Menu.iOS // import UIKit private func TransformForRotatingLayer(layer: CALayer, angle: CGFloat) -> CATransform3D { let offset = layer.bounds.width / 2 var transform = CATransform3DIdentity transform.m34 = -0.002 transform = CATransform3DTranslate(transform, -offset, 0, 0) transform = CATransform3DRotate(transform, angle, 0, 1, 0) transform = CATransform3DTranslate(transform, offset, 0, 0) return transform } class MenuItemsAnimator { var completion: () -> Void = {} var duration: CFTimeInterval = 0 private let layers: [CALayer] private let startAngle: CGFloat private let endAngle: CGFloat init(views: [UIView], startAngle: CGFloat, endAngle: CGFloat) { self.layers = views.map { $0.layer } self.startAngle = startAngle self.endAngle = endAngle } func start() { let count = Double(layers.count) let duration = self.duration * count / (4 * count - 3) for (index, layer) in layers.enumerate() { layer.transform = TransformForRotatingLayer(layer, angle: startAngle) let delay = 3 * duration * Double(index) / count UIView.animateWithDuration(duration, delay: delay, options: .CurveEaseIn, animations: { layer.transform = TransformForRotatingLayer(layer, angle: self.endAngle) }, completion: nil) } let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(self.duration * Double(NSEC_PER_SEC))) dispatch_after(delay, dispatch_get_main_queue()) { self.completion() } } }
a7baaca5bebb7ac327fddba8d4ab8c16
33.588235
99
0.656463
false
false
false
false
ben-ng/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01185-swift-parser-parsetypeidentifier.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 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 // RUN: not %target-swift-frontend %s -typecheck func b<c { enum b { func b var _ = b func k<q { enum k { } } class x { } struct j<u> : r { func j(j: j.n) { } } enum q<v> { let k: v } protocol y { } struct D : y { func y<v k r { } class y<D> { } } func l<c>(m: (l, c) -> c) -> (l, c) -> c { f { i }, k) class l { class func m { b let k: String = { }() struct q<q : n, p: n where p.q == q.q> { } o q: n = { m, i j l { k m p<i) { } } } }lass func c() } s} class a<f : b, : b where f.d == g> { } struct j<l : o> { } func a<l>() -> [j<l>] { } func f<l>() -> (l, l -> l) -> l { l j l.n = { } { l) { n } } protocol f { } class l: f{ class func n {} func a<i>() { b b { } } class a<f : b, l : b m f.l == l> { } protocol b { } struct j<n : b> : b { } enum e<b> : d { func c<b>() -> b { } } protocol d { } enum A : String { } if c == .b { } struct c<f : h> { var b: [c<f>] { g []e f() { } } protocol c : b { func b class j { func y((Any, j))(v: (Any, AnyObject)) { }
c5656fe63a2502a38145e4753fdcbf97
12.842105
79
0.530798
false
false
false
false
PJayRushton/stats
refs/heads/master
Stats/HomeViewController.swift
mit
1
// // HomeViewController.swift // St@s // // Created by Parker Rushton on 1/26/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import UIKit import IGListKit import Kingfisher import Presentr class HomeViewController: Component, AutoStoryboardInitializable { // MARK: - IBOutlets @IBOutlet weak var collectionView: UICollectionView! @IBOutlet var emptyStateView: UIView! @IBOutlet weak var newGameButton: UIButton! // MARK: - Properties fileprivate let gridLayout = ListCollectionViewLayout(stickyHeaders: false, topContentInset: 0, stretchToEdge: false) fileprivate let feedbackGenerator = UISelectionFeedbackGenerator() fileprivate var isPresentingOnboarding = false fileprivate var hasSeenNotificationPrompt = false var currentTeam: Team? { return core.state.teamState.currentTeam } fileprivate lazy var adapter: ListAdapter = { return ListAdapter(updater: ListAdapterUpdater(), viewController: self, workingRangeSize: 0) }() let presenter: Presentr = { let presenter = Presentr(presentationType: .alert) presenter.transitionType = TransitionType.coverHorizontalFromRight return presenter }() // MARK: - ViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() collectionView.collectionViewLayout = gridLayout adapter.collectionView = collectionView adapter.dataSource = self feedbackGenerator.prepare() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) adapter.performUpdates(animated: true) core.fire(event: Updated<StatsViewType>(.trophies)) core.fire(command: UpdateBadgeCount()) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) collectionView.collectionViewLayout.invalidateLayout() } // MARK: - IBActions @IBAction func createTeamButtonPressed(_ sender: UIButton) { feedbackGenerator.selectionChanged() let teamCreationVC = TeamCreationViewController.initializeFromStoryboard().embededInNavigationController teamCreationVC.modalPresentationStyle = .overFullScreen present(teamCreationVC, animated: true, completion: nil) } @IBAction func addTeamButtonPressed(_ sender: UIButton) { feedbackGenerator.selectionChanged() let addTeamVC = AddTeamViewController.initializeFromStoryboard().embededInNavigationController addTeamVC.modalPresentationStyle = .overFullScreen present(addTeamVC, animated: true, completion: nil) } @IBAction func newTeamButtonPressed(_ sender: UIButton) { pushGames(new: true) } // MARK: - Subscriber override func update(with state: AppState) { if state.userState.currentUser == nil, state.userState.isLoaded, !isPresentingOnboarding { isPresentingOnboarding = true let newUserVC = NewUserViewController.initializeFromStoryboard().embededInNavigationController newUserVC.modalPresentationStyle = .overFullScreen present(newUserVC, animated: true) } if let user = state.userState.currentUser { let currentTeam = state.teamState.currentTeam newGameButton.isHidden = currentTeam == nil || !user.isOwnerOrManager(of: currentTeam!) } if let _ = state.teamState.currentTeam, !hasSeenNotificationPrompt { hasSeenNotificationPrompt = true NotificationController.shared.requestAccessIfNeeded(from: self) } adapter.performUpdates(animated: true) } } extension HomeViewController { func presentSettings() { feedbackGenerator.selectionChanged() let settingsVC = SettingsViewController.initializeFromStoryboard().embededInNavigationController settingsVC.modalPresentationStyle = .overFullScreen present(settingsVC, animated: true, completion: nil) } func presentTeamSwitcher() { feedbackGenerator.selectionChanged() let teamListVC = TeamListViewController.initializeFromStoryboard() teamListVC.isSwitcher = true let teamListInNav = teamListVC.embededInNavigationController teamListInNav.modalTransitionStyle = .flipHorizontal teamListInNav.modalPresentationStyle = .fullScreen present(teamListInNav, animated: true) } func presentTeamEdit() { feedbackGenerator.selectionChanged() let creationVC = TeamCreationViewController.initializeFromStoryboard() creationVC.editingTeam = currentTeam let creationVCWithNav = creationVC.embededInNavigationController creationVCWithNav.modalPresentationStyle = .overFullScreen present(creationVCWithNav, animated: true, completion: nil) } func presentSeasonManager() { feedbackGenerator.selectionChanged() let seasonsVC = SeasonsViewController.initializeFromStoryboard() seasonsVC.isModal = true let seasonsNav = seasonsVC.embededInNavigationController seasonsNav.modalPresentationStyle = .overFullScreen present(seasonsNav, animated: true, completion: nil) } fileprivate func pushGames(new: Bool = false) { let gamesVC = GamesViewController.initializeFromStoryboard() gamesVC.new = new navigationController?.pushViewController(gamesVC, animated: true) } fileprivate func pushStats() { let statsVC = StatsViewController.initializeFromStoryboard() navigationController?.pushViewController(statsVC, animated: true) if core.state.statState.currentTrophies.isEmpty { core.fire(command: UpdateTrophies()) } } func pushRoster() { let rosterVC = RosterViewController.initializeFromStoryboard() navigationController?.pushViewController(rosterVC, animated: true) } func pushShareTeamRoles() { if let user = core.state.userState.currentUser, let team = core.state.teamState.currentTeam, user.isOwnerOrManager(of: team) { presentShareRoles() let shareTeamRolesVC = ShareTeamRolesViewController.initializeFromStoryboard() navigationController?.pushViewController(shareTeamRolesVC, animated: true) } else { presentTeamShare(withType: .fan) } } fileprivate func presentShareRoles() { let alert = Presentr.alertViewController(title: "Share Team", body: "Which would you like to add?") alert.addAction(AlertAction(title: "St@ Keeper", style: .default) { _ in self.dismiss(animated: true, completion: { self.presentTeamShare(withType: .managed) }) }) alert.addAction(AlertAction(title: "Player/Fan", style: .default) { _ in self.dismiss(animated: true, completion: { self.presentTeamShare(withType: .fan) }) }) customPresentViewController(alertPresenter, viewController: alert, animated: true, completion: nil) } fileprivate func presentTeamShare(withType type: TeamOwnershipType) { let shareTeamVC = ShareTeamViewController.initializeFromStoryboard() shareTeamVC.modalPresentationStyle = .overFullScreen shareTeamVC.ownershipType = type present(shareTeamVC, animated: false, completion: nil) } func didSelectItem(_ item: HomeMenuItem) { feedbackGenerator.selectionChanged() core.fire(event: Selected<HomeMenuItem>(item)) switch item { case .newGame: pushGames(new: true) case .stats: pushStats() case .games: pushGames() case .roster: pushRoster() case .share: pushShareTeamRoles() } } } // MARK: - IGListKitDataSource extension HomeViewController: ListAdapterDataSource { func objects(for listAdapter: ListAdapter) -> [ListDiffable] { guard let currentTeam = currentTeam else { return [] } var objects: [ListDiffable] = [TeamHeaderSection(team: currentTeam, season: core.state.seasonState.currentSeason)] let items = HomeMenuItem.allValues items.forEach { item in let section = TeamActionSection(team: currentTeam, menuItem: item) switch item { case .stats: section.badgeCount = core.state.hasSeenLatestStats ? nil : 0 case .games: let count = core.state.gameState.currentOngoingGames.count section.badgeCount = count == 0 ? nil : count default: break } objects.append(section) } return objects } func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController { switch object { case _ as TeamHeaderSection: let headerController = TeamHeaderSectionController() headerController.settingsPressed = presentSettings headerController.switchTeamPressed = presentTeamSwitcher headerController.seasonPressed = presentSeasonManager return headerController case _ as TeamActionSection: let actionController = TeamActionSectionController() actionController.didSelectItem = didSelectItem return actionController default: fatalError() } } func emptyView(for listAdapter: ListAdapter) -> UIView? { return emptyStateView } }
d9b20d88152a6acb7ee1eadc07d749d3
35.39781
134
0.669107
false
false
false
false
davecom/SwiftGraph
refs/heads/master
Examples/SwiftGraph-master/Sources/SwiftGraph/Queue.swift
apache-2.0
2
// // Queue.swift // SwiftGraph // // Copyright (c) 2014-2019 David Kopec // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Implements a queue - helper class that uses an array internally. public class Queue<T> { private var container = [T]() private var head = 0 public init() {} public var isEmpty: Bool { return count == 0 } public func push(_ element: T) { container.append(element) } public func pop() -> T { let element = container[head] head += 1 // If queue has more than 50 elements and more than 50% of allocated elements are popped. // Don't calculate the percentage with floating point, it decreases the performance considerably. if container.count > 50 && head * 2 > container.count { container.removeFirst(head) head = 0 } return element } public var front: T { return container[head] } public var count: Int { return container.count - head } } extension Queue where T: Equatable { public func contains(_ thing: T) -> Bool { let content = container.dropFirst(head) if content.firstIndex(of: thing) != nil { return true } return false } }
3a6b05eb53a05223549752170dc596bf
26.257576
105
0.632574
false
false
false
false
dduan/swift
refs/heads/master
test/SILOptimizer/definite_init_failable_initializers.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-sil -disable-objc-attr-requires-foundation-module %s | FileCheck %s // High-level tests that DI handles early returns from failable and throwing // initializers properly. The main complication is conditional release of self // and stored properties. // FIXME: not all of the test cases have CHECKs. Hopefully the interesting cases // are fully covered, though. //// // Structs with failable initializers //// protocol Pachyderm { init() } class Canary : Pachyderm { required init() {} } // <rdar://problem/20941576> SILGen crash: Failable struct init cannot delegate to another failable initializer struct TrivialFailableStruct { init?(blah: ()) { } init?(wibble: ()) { self.init(blah: wibble) } } struct FailableStruct { let x, y: Canary init(noFail: ()) { x = Canary() y = Canary() } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT24failBeforeInitializationT__GSqS0__ // CHECK: bb0(%0 : $@thin FailableStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: br bb1 // CHECK: bb1: // CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[SELF]] init?(failBeforeInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT30failAfterPartialInitializationT__GSqS0__ // CHECK: bb0(%0 : $@thin FailableStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY:%.*]] = apply // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: store [[CANARY]] to [[X_ADDR]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: strong_release [[CANARY]] // CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[SELF]] init?(failAfterPartialInitialization: ()) { x = Canary() return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT27failAfterFullInitializationT__GSqS0__ // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY1:%.*]] = apply // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: store [[CANARY1]] to [[X_ADDR]] // CHECK: [[CANARY2:%.*]] = apply // CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: store [[CANARY2]] to [[Y_ADDR]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: [[SELF:%.*]] = struct $FailableStruct ([[CANARY1]] : $Canary, [[CANARY2]] : $Canary) // CHECK-NEXT: release_value [[SELF]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterFullInitialization: ()) { x = Canary() y = Canary() return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT46failAfterWholeObjectInitializationByAssignmentT__GSqS0__ // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY]] = apply // CHECK-NEXT: store [[CANARY]] to [[SELF_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: release_value [[CANARY]] // CHECK-NEXT: [[SELF_VALUE:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[SELF_VALUE]] init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableStruct(noFail: ()) return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT46failAfterWholeObjectInitializationByDelegationT__GSqS0__ // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers14FailableStructCfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: release_value [[NEW_SELF]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers14FailableStructCfT20failDuringDelegationT__GSqS0__ // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers14FailableStructCfT24failBeforeInitializationT__GSqS0__ // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], bb1, bb2 // CHECK: bb1: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableStruct>) // CHECK: bb2: // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableStruct>) // CHECK: bb3([[NEW_SELF:%.*]] : $Optional<FailableStruct>) // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO init!(failDuringDelegation3: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation4: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation5: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableStruct { init?(failInExtension: ()) { self.init(failInExtension: failInExtension) } init?(assignInExtension: ()) { self = FailableStruct(noFail: ()) } } struct FailableAddrOnlyStruct<T : Pachyderm> { var x, y: T init(noFail: ()) { x = T() y = T() } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers22FailableAddrOnlyStructC{{.*}}24failBeforeInitialization // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: br bb1 // CHECK: bb1: // CHECK-NEXT: inject_enum_addr %0 // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return init?(failBeforeInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers22FailableAddrOnlyStructC{{.*}}failAfterPartialInitialization // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK-NEXT: [[X_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]] // CHECK-NEXT: dealloc_stack [[X_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[X_ADDR]] // CHECK-NEXT: inject_enum_addr %0 // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return init?(failAfterPartialInitialization: ()) { x = T() return nil } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers22FailableAddrOnlyStructC{{.*}}failAfterFullInitialization // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK-NEXT: [[X_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]] // CHECK-NEXT: dealloc_stack [[X_BOX]] // CHECK-NEXT: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK-NEXT: [[Y_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[Y_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: copy_addr [take] [[Y_BOX]] to [initialization] [[Y_ADDR]] // CHECK-NEXT: dealloc_stack [[Y_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: inject_enum_addr %0 // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return init?(failAfterFullInitialization: ()) { x = T() y = T() return nil } init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableAddrOnlyStruct(noFail: ()) return nil } init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation3: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation4: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableAddrOnlyStruct { init?(failInExtension: ()) { self.init(failBeforeInitialization: failInExtension) } init?(assignInExtension: ()) { self = FailableAddrOnlyStruct(noFail: ()) } } //// // Structs with throwing initializers //// func unwrap(x: Int) throws -> Int { return x } struct ThrowStruct { var x: Canary init(fail: ()) throws { x = Canary() } init(noFail: ()) { x = Canary() } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT20failBeforeDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT28failBeforeOrDuringDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT4failT__S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT29failBeforeOrDuringDelegation2Si_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT20failBeforeDelegationSi_S0_ // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: try_apply [[INIT_FN]]([[RESULT]], %1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT20failDuringDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT4failT__S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringDelegation: Int) throws { try self.init(fail: ()) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT19failAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK: release_value [[NEW_SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT27failDuringOrAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT4failT__S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:.*]] : $ThrowStruct): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT27failBeforeOrAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfT16throwsToOptionalSi_GSqS0__ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT20failDuringDelegationSi_S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%0, %1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[NEW_SELF]] // CHECK-NEXT: br bb2([[SELF_OPTIONAL]] : $Optional<ThrowStruct>) // CHECK: bb2([[SELF_OPTIONAL:%.*]] : $Optional<ThrowStruct>): // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], bb3, bb4 // CHECK: bb3: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: br bb5([[NEW_SELF]] : $Optional<ThrowStruct>) // CHECK: bb4: // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb5([[NEW_SELF]] : $Optional<ThrowStruct>) // CHECK: bb5([[NEW_SELF:%.*]] : $Optional<ThrowStruct>): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] : $Optional<ThrowStruct> // CHECK: bb6: // CHECK-NEXT: strong_release [[ERROR:%.*]] : $ErrorProtocol // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2([[NEW_SELF]] : $Optional<ThrowStruct>) // CHECK: bb7([[ERROR]] : $ErrorProtocol): // CHECK-NEXT: br bb6 init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsToOptionalThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowStruct(noFail: ()) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT25failDuringSelfReplacementSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfzT4failT__S0_ // CHECK-NEXT: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type // CHECK-NEXT: try_apply [[INIT_FN]]([[SELF_TYPE]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringSelfReplacement: Int) throws { try self = ThrowStruct(fail: ()) } // CHECK-LABEL: sil hidden @_TFV35definite_init_failable_initializers11ThrowStructCfzT24failAfterSelfReplacementSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @_TFV35definite_init_failable_initializers11ThrowStructCfT6noFailT__S0_ // CHECK-NEXT: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[SELF_TYPE]]) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: release_value [[NEW_SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterSelfReplacement: Int) throws { self = ThrowStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { try self = ThrowStruct(fail: ()) } } struct ThrowAddrOnlyStruct<T : Pachyderm> { var x : T init(fail: ()) throws { x = T() } init(noFail: ()) { x = T() } init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } init(failDuringDelegation: Int) throws { try self.init(fail: ()) } init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsOptionalToThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowAddrOnlyStruct(noFail: ()) } init(failAfterSelfReplacement: Int) throws { self = ThrowAddrOnlyStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowAddrOnlyStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { self = ThrowAddrOnlyStruct(noFail: ()) } } //// // Classes with failable initializers //// class FailableBaseClass { var member: Canary init(noFail: ()) { member = Canary() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17FailableBaseClasscfT28failBeforeFullInitializationT__GSqS0__ // CHECK: bb0(%0 : $FailableBaseClass): // CHECK: [[METATYPE:%.*]] = metatype $@thick FailableBaseClass.Type // CHECK: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]] // CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: return [[RESULT]] init?(failBeforeFullInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17FailableBaseClasscfT27failAfterFullInitializationT__GSqS0__ // CHECK: bb0(%0 : $FailableBaseClass): // CHECK: [[CANARY:%.*]] = apply // CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0 // CHECK-NEXT: store [[CANARY]] to [[MEMBER_ADDR]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: strong_release %0 // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterFullInitialization: ()) { member = Canary() return nil } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17FailableBaseClasscfT20failBeforeDelegationT__GSqS0__ // CHECK: bb0(%0 : $FailableBaseClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: store %0 to [[SELF_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick FailableBaseClass.Type, %0 : $FailableBaseClass // CHECK-NEXT: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]] : $@thick FailableBaseClass.Type // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[RESULT]] convenience init?(failBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17FailableBaseClasscfT19failAfterDelegationT__GSqS0__ // CHECK: bb0(%0 : $FailableBaseClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: store %0 to [[SELF_BOX]] // CHECK: [[INIT_FN:%.*]] = class_method %0 // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: strong_release [[NEW_SELF]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[RESULT]] convenience init?(failAfterDelegation: ()) { self.init(noFail: ()) return nil } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17FailableBaseClasscfT20failDuringDelegationT__GSqS0__ // CHECK: bb0(%0 : $FailableBaseClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: store %0 to [[SELF_BOX]] // CHECK: [[INIT_FN:%.*]] = class_method %0 // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], bb1, bb2 // CHECK: bb1: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableBaseClass>) // CHECK: bb2: // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableBaseClass>) // CHECK: bb3([[NEW_SELF:%.*]] : $Optional<FailableBaseClass>): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // Optional to optional convenience init?(failDuringDelegation: ()) { self.init(failBeforeFullInitialization: ()) } // IUO to optional convenience init!(failDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO convenience init!(noFailDuringDelegation: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional convenience init(noFailDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // necessary '!' } } extension FailableBaseClass { convenience init?(failInExtension: ()) throws { self.init(failBeforeFullInitialization: failInExtension) } } // Chaining to failable initializers in a superclass class FailableDerivedClass : FailableBaseClass { var otherMember: Canary // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers20FailableDerivedClasscfT27derivedFailBeforeDelegationT__GSqS0__ // CHECK: bb0(%0 : $FailableDerivedClass): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass // CHECK: store %0 to [[SELF_BOX]] // CHECK-NEXT: br bb1 // CHECK: bb1: // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick FailableDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref %0 : $FailableDerivedClass, [[METATYPE]] : $@thick FailableDerivedClass.Type // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[RESULT]] init?(derivedFailBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers20FailableDerivedClasscfT27derivedFailDuringDelegationT__GSqS0__ // CHECK: bb0(%0 : $FailableDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass // CHECK: store %0 to [[SELF_BOX]] // CHECK: [[CANARY:%.*]] = apply // CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0 // CHECK-NEXT: store [[CANARY]] to [[MEMBER_ADDR]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17FailableBaseClasscfT28failBeforeFullInitializationT__GSqS0__ // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], bb1, bb2 // CHECK: bb1: // CHECK-NEXT: [[BASE_SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_ref_cast [[BASE_SELF_VALUE]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableDerivedClass>) // CHECK: bb2: // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableDerivedClass>) // CHECK: bb3([[NEW_SELF:%.*]] : $Optional<FailableDerivedClass>): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] : $Optional<FailableDerivedClass> init?(derivedFailDuringDelegation: ()) { self.otherMember = Canary() super.init(failBeforeFullInitialization: ()) } init?(derivedFailAfterDelegation: ()) { self.otherMember = Canary() super.init(noFail: ()) return nil } // non-optional to IUO init(derivedNoFailDuringDelegation: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // necessary '!' } // IUO to IUO init!(derivedFailDuringDelegation2: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // unnecessary-but-correct '!' } } extension FailableDerivedClass { convenience init?(derivedFailInExtension: ()) throws { self.init(derivedFailDuringDelegation: derivedFailInExtension) } } //// // Classes with throwing initializers //// class ThrowBaseClass { required init() throws {} init(noFail: ()) {} } class ThrowDerivedClass : ThrowBaseClass { // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT_S0_ // CHECK: bb0(%0 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %0 to [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfzT_S0_ // CHECK-NEXT: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] required init() throws { try super.init() } override init(noFail: ()) { try! super.init() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT28failBeforeFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] : $ThrowDerivedClass // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) super.init(noFail: ()) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT28failBeforeFullInitializationSi28failDuringFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] : $*ThrowDerivedClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int) // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfzT_S0_ // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref %2 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) try super.init() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT27failAfterFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: strong_release [[DERIVED_SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterFullInitialization: Int) throws { super.init(noFail: ()) try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT27failAfterFullInitializationSi28failDuringFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] // CHECK-NEXT: [[DERIVED_SELF:%.*]] = upcast %2 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfzT_S0_ // CHECK: try_apply [[INIT_FN]]([[DERIVED_SELF]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterFullInitialization: Int, failDuringFullInitialization: Int) throws { try super.init() try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT28failBeforeFullInitializationSi27failAfterFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfT6noFailT__S0_ // CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%1) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND:%.*]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[BITMAP:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref [[BITMAP]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] : $ErrorProtocol init(failBeforeFullInitialization: Int, failAfterFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) super.init(noFail: ()) try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT28failBeforeFullInitializationSi28failDuringFullInitializationSi27failAfterFullInitializationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $Int, %3 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %3 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %3 // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers14ThrowBaseClasscfzT_S0_ // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%2) // CHECK: bb3([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb7([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb7([[ERROR]] : $ErrorProtocol) // CHECK: bb6([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb7([[ERROR]] : $ErrorProtocol) // CHECK: bb7([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb8, bb9 // CHECK: bb8: // CHECK-NEXT: br bb13 // CHECK: bb9: // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb10, bb11 // CHECK: bb10: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb12 // CHECK: bb11: // CHECK-NEXT: [[SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref [[SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb12 // CHECK: bb12: // CHECK-NEXT: br bb13 // CHECK: bb13: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int, failAfterFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) try super.init() try unwrap(failAfterFullInitialization) } convenience init(noFail2: ()) { try! self.init() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT20failBeforeDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass // CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT20failDuringDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT_S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] : $ErrorProtocol convenience init(failDuringDelegation: Int) throws { try self.init() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT28failBeforeOrDuringDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int2 // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT_S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR1:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR1]] : $ErrorProtocol) // CHECK: bb4([[ERROR2:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb5([[ERROR2]] : $ErrorProtocol) // CHECK: bb5([[ERROR3:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP_VALUE:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[BIT_NUM:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP_VALUE]] : $Builtin.Int2, [[BIT_NUM]] : $Builtin.Int2) // CHECK-NEXT: [[CONDITION:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[CONDITION]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass // CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR3]] convenience init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init() } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT29failBeforeOrDuringDelegation2Si_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int2 // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT20failBeforeDelegationSi_S0_ // CHECK-NEXT: try_apply [[INIT_FN]]([[ARG]], %1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR1:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb5([[ERROR1]] : $ErrorProtocol) // CHECK: bb5([[ERROR2:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP_VALUE:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[BIT_NUM:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP_VALUE]] : $Builtin.Int2, [[BIT_NUM]] : $Builtin.Int2) // CHECK-NEXT: [[CONDITION:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[CONDITION]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass // CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR2]] convenience init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT19failAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: strong_release [[NEW_SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT27failDuringOrAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %1 to [[SELF_BOX]] // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT_S0_ // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR1:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: br bb5([[ERROR1]] : $ErrorProtocol) // CHECK: bb4([[ERROR2:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR2]] : $ErrorProtocol) // CHECK: bb5([[ERROR3:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR3]] convenience init(failDuringOrAfterDelegation: Int) throws { try self.init() try unwrap(failDuringOrAfterDelegation) } // CHECK-LABEL: sil hidden @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfzT27failBeforeOrAfterDelegationSi_S0_ // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @_TFC35definite_init_failable_initializers17ThrowDerivedClasscfT6noFailT__S0_ // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @_TF35definite_init_failable_initializers6unwrapFzSiSi // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb4([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: br bb5([[ERROR]] : $ErrorProtocol) // CHECK: bb5([[ERROR:%.*]] : $ErrorProtocol): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[OLD_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, [[OLD_SELF]] : $ThrowDerivedClass // CHECK-NEXT: dealloc_partial_ref [[OLD_SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } } //// // Enums with failable initializers //// enum FailableEnum { case A init?(a: Int64) { self = .A } init!(b: Int64) { self.init(a: b)! // unnecessary-but-correct '!' } init(c: Int64) { self.init(a: c)! // necessary '!' } init(d: Int64) { self.init(b: d)! // unnecessary-but-correct '!' } } //// // Protocols and protocol extensions //// // Delegating to failable initializers from a protocol extension to a // protocol. protocol P1 { init?(p1: Int64) } extension P1 { init!(p1a: Int64) { self.init(p1: p1a)! // unnecessary-but-correct '!' } init(p1b: Int64) { self.init(p1: p1b)! // necessary '!' } } protocol P2 : class { init?(p2: Int64) } extension P2 { init!(p2a: Int64) { self.init(p2: p2a)! // unnecessary-but-correct '!' } init(p2b: Int64) { self.init(p2: p2b)! // necessary '!' } } @objc protocol P3 { init?(p3: Int64) } extension P3 { init!(p3a: Int64) { self.init(p3: p3a)! // unnecessary-but-correct '!' } init(p3b: Int64) { self.init(p3: p3b)! // necessary '!' } } // Delegating to failable initializers from a protocol extension to a // protocol extension. extension P1 { init?(p1c: Int64) { self.init(p1: p1c) } init!(p1d: Int64) { self.init(p1c: p1d)! // unnecessary-but-correct '!' } init(p1e: Int64) { self.init(p1c: p1e)! // necessary '!' } } extension P2 { init?(p2c: Int64) { self.init(p2: p2c) } init!(p2d: Int64) { self.init(p2c: p2d)! // unnecessary-but-correct '!' } init(p2e: Int64) { self.init(p2c: p2e)! // necessary '!' } } //// // self.dynamicType with uninitialized self //// func use(a : Any) {} class DynamicTypeBase { var x: Int init() { use(self.dynamicType) x = 0 } convenience init(a : Int) { use(self.dynamicType) self.init() } } class DynamicTypeDerived : DynamicTypeBase { override init() { use(self.dynamicType) super.init() } convenience init(a : Int) { use(self.dynamicType) self.init() } } struct DynamicTypeStruct { var x: Int init() { use(self.dynamicType) x = 0 } init(a : Int) { use(self.dynamicType) self.init() } }
1bf1f2a39bc4a6d2a6c53d6fe73a775c
41.745806
191
0.624849
false
false
false
false
zj-insist/QSImageBucket
refs/heads/master
QSIMageBucket/DragDestinationView.swift
mit
1
// // DragDestinationView.swift // UPImage // // Created by Pro.chen on 16/7/9. // Copyright © 2016年 chenxt. All rights reserved. // import Cocoa class DragDestinationView: NSView { override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. } override init(frame frameRect: NSRect) { super.init(frame: frameRect) // 注册接受文件拖入的类型 register(forDraggedTypes: [NSFilenamesPboardType]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { let pboard = sender.draggingPasteboard() if checkImageFile(pboard) { statusItem.button?.image = NSImage(named: "upload") return NSDragOperation.copy } else { return NSDragOperation() } } override func draggingExited(_ sender: NSDraggingInfo?) { statusItem.button?.image = NSImage(named: "StatusIcon") } override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool { let pboard = sender.draggingPasteboard() return checkImageFile(pboard) } override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { let pboard = sender.draggingPasteboard() ImageService.shared.uploadImg(pboard) statusItem.button?.image = NSImage(named: "StatusIcon") return true } }
2d648d88f2f4cdb817f027a97cf972da
22.508772
77
0.714179
false
false
false
false
nmdias/DefaultsKit
refs/heads/master
Tests/DefaultsKey + keys.swift
mit
1
// // DefaultsKey + keys.swift // // Copyright (c) 2017 - 2018 Nuno Manuel Dias // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation @testable import DefaultsKit extension DefaultsKey { static let integerKey = Key<Int>("integerKey") static let floatKey = Key<Float>("floatKey") static let doubleKey = Key<Double>("doubleKey") static let stringKey = Key<String>("stringKey") static let boolKey = Key<Bool>("boolKey") static let dateKey = Key<Date>("dateKey") static let enumKey = Key<EnumMock>("enumKey") static let optionSetKey = Key<OptionSetMock>("optionSetKey") static let arrayOfIntegersKey = Key<[Int]>("arrayOfIntegersKey") static let personMockKey = Key<PersonMock>("personMockKey") }
105378ceaa8a37c1b55f3cf6691e5659
45
82
0.736343
false
false
false
false
aapierce0/MatrixClient
refs/heads/master
MatrixClient/ImageProvider.swift
apache-2.0
1
/* Copyright 2017 Avery Pierce Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import SwiftMatrixSDK struct UnknownError : Error { var localizedDescription: String { return "error object was unexpectedly nil" } } /// Downloads images and provides them. class ImageProvider { var semaphores: [URL: DispatchSemaphore] = [:] var cache: [URL: NSImage] = [:] func semaphore(for url: URL) -> DispatchSemaphore { if let semaphore = self.semaphores[url] { return semaphore } let newSemaphore = DispatchSemaphore(value: 1) self.semaphores[url] = newSemaphore return newSemaphore } func cachedImage(for url: URL) -> NSImage? { return cache[url] } func image(for url: URL, completion: @escaping (_ response: MXResponse<NSImage>) -> Void) { // Get the semaphore for this url let semaphore = self.semaphore(for: url) // This operation needs to be performed on a background thread let queue = DispatchQueue(label: "Image Provider") queue.async { // Wait until any downloads are complete semaphore.wait() // If the image already exists in the cache, return it. if let image = self.cache[url] { completion(.success(image)) semaphore.signal() return } URLSession.shared.dataTask(with: url) { (data, response, error) in // The request is complete, so make sure to signal defer { semaphore.signal() } // Create a result object from the URLSession response let result: MXResponse<NSImage> if let data = data, let image = NSImage(data: data) { self.cache[url] = image result = .success(image) } else if let error = error { result = .failure(error) } else { result = .failure(UnknownError()) } // Perform the completion block on the main thread. DispatchQueue.main.async { completion(result) } }.resume() } } }
1b5e85fbdb987e172293851f81d1050d
32.337209
95
0.574468
false
false
false
false
chrisjmendez/swift-exercises
refs/heads/master
Animation/Flicker/Carthage/Checkouts/SYBlinkAnimationKit/Example/SYBlinkAnimationKit/CollectionViewController.swift
mit
2
// // CollectionViewController.swift // SYBlinkAnimationKit // // Created by Shohei Yokoyama on 2016/07/31. // Copyright © 2016年 CocoaPods. All rights reserved. // import UIKit import SYBlinkAnimationKit class CollectionViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! let cellIdentifier = "CollectionViewCell" override func viewDidLoad() { super.viewDidLoad() configure() registerNib() } } // MARK: - Fileprivate Methods - fileprivate extension CollectionViewController { func configure() { collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = UIColor(red: 236/255, green: 236/255, blue: 236/255, alpha: 1) let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.minimumLineSpacing = 5 layout.minimumInteritemSpacing = 5 collectionView.collectionViewLayout = layout } func registerNib() { let nib = UINib(nibName: cellIdentifier, bundle: nil) collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier) } func configure(cell: CollectionViewCell, at indexPath: IndexPath) { switch (indexPath as NSIndexPath).row { case 0: cell.titileLabel.text = "Border Animation" cell.animationType = .border case 1: cell.titileLabel.text = "BorderWithShadow\nAnimation" cell.animationType = .borderWithShadow cell.titileLabel.textAlignmentMode = .center case 2: cell.titileLabel.text = "Background Animation" cell.animationType = .background case 3: cell.titileLabel.text = "ripple Animation" cell.animationType = .ripple default: cell.titileLabel.text = "SYCollectionViewCell" cell.titileLabel.animationType = .text cell.titileLabel.startAnimating() } cell.startAnimating() } } // MARK: - UICollectionViewDataSource extension CollectionViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CollectionViewCell configure(cell: cell, at: indexPath) return cell } } // MARK: - UICollectionViewDelegateFlowLayout extension CollectionViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let margin: CGFloat = 5 let height: CGFloat = 150 let rowCount: CGFloat = 2 return CGSize(width: view.frame.width / rowCount - (margin * (rowCount - 1) / rowCount), height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 5, right: 0) } }
3e0ee794e1c925985f44fe688e6f93a4
33.485437
162
0.669482
false
false
false
false
AaronMT/firefox-ios
refs/heads/main
Client/Frontend/Widgets/PhotonActionSheet/PhotonActionSheetCell.swift
mpl-2.0
5
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Storage import SnapKit import Shared // This file is the cells used for the PhotonActionSheet table view. private struct PhotonActionSheetCellUX { static let LabelColor = UIConstants.SystemBlueColor static let BorderWidth = CGFloat(0.5) static let CellSideOffset = 20 static let TitleLabelOffset = 10 static let CellTopBottomOffset = 12 static let StatusIconSize = 24 static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25) static let CornerRadius: CGFloat = 3 } class PhotonActionSheetCell: UITableViewCell { static let Padding: CGFloat = 16 static let HorizontalPadding: CGFloat = 1 static let VerticalPadding: CGFloat = 2 static let IconSize = 16 var syncButton: SyncMenuButton? var badgeOverlay: BadgeWithBackdrop? private func createLabel() -> UILabel { let label = UILabel() label.minimumScaleFactor = 0.75 // Scale the font if we run out of space label.setContentHuggingPriority(.defaultHigh, for: .vertical) label.adjustsFontSizeToFitWidth = true return label } private func createIconImageView() -> UIImageView { let icon = UIImageView() icon.contentMode = .scaleAspectFit icon.clipsToBounds = true icon.layer.cornerRadius = PhotonActionSheetCellUX.CornerRadius icon.setContentHuggingPriority(.required, for: .horizontal) icon.setContentCompressionResistancePriority(.required, for: .horizontal) return icon } lazy var titleLabel: UILabel = { let label = createLabel() label.numberOfLines = 4 label.font = DynamicFontHelper.defaultHelper.LargeSizeRegularWeightAS return label }() lazy var subtitleLabel: UILabel = { let label = createLabel() label.numberOfLines = 0 label.font = DynamicFontHelper.defaultHelper.SmallSizeRegularWeightAS return label }() lazy var statusIcon: UIImageView = { return createIconImageView() }() lazy var disclosureLabel: UILabel = { let label = UILabel() return label }() struct ToggleSwitch { let mainView: UIImageView = { let background = UIImageView(image: UIImage.templateImageNamed("menu-customswitch-background")) background.contentMode = .scaleAspectFit return background }() private let foreground = UIImageView() init() { foreground.autoresizingMask = [.flexibleWidth, .flexibleHeight] foreground.contentMode = .scaleAspectFit foreground.frame = mainView.frame mainView.isAccessibilityElement = true mainView.addSubview(foreground) setOn(false) } func setOn(_ on: Bool) { foreground.image = on ? UIImage(named: "menu-customswitch-on") : UIImage(named: "menu-customswitch-off") mainView.accessibilityIdentifier = on ? "enabled" : "disabled" mainView.tintColor = on ? UIColor.theme.general.controlTint : UIColor.theme.general.switchToggle } } let toggleSwitch = ToggleSwitch() lazy var selectedOverlay: UIView = { let selectedOverlay = UIView() selectedOverlay.backgroundColor = PhotonActionSheetCellUX.SelectedOverlayColor selectedOverlay.isHidden = true return selectedOverlay }() lazy var disclosureIndicator: UIImageView = { let disclosureIndicator = createIconImageView() disclosureIndicator.image = UIImage(named: "menu-Disclosure")?.withRenderingMode(.alwaysTemplate) disclosureIndicator.tintColor = UIColor.theme.tableView.accessoryViewTint return disclosureIndicator }() lazy var stackView: UIStackView = { let stackView = UIStackView() stackView.spacing = PhotonActionSheetCell.Padding stackView.alignment = .center stackView.axis = .horizontal return stackView }() override var isSelected: Bool { didSet { self.selectedOverlay.isHidden = !isSelected } } override func prepareForReuse() { super.prepareForReuse() self.statusIcon.image = nil disclosureIndicator.removeFromSuperview() disclosureLabel.removeFromSuperview() toggleSwitch.mainView.removeFromSuperview() statusIcon.layer.cornerRadius = PhotonActionSheetCellUX.CornerRadius badgeOverlay?.backdrop.removeFromSuperview() badgeOverlay?.badge.removeFromSuperview() } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) isAccessibilityElement = true contentView.addSubview(selectedOverlay) backgroundColor = .clear selectedOverlay.snp.makeConstraints { make in make.edges.equalTo(contentView) } // Setup our StackViews let textStackView = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel]) textStackView.spacing = PhotonActionSheetCell.VerticalPadding textStackView.setContentHuggingPriority(.defaultLow, for: .horizontal) textStackView.alignment = .leading textStackView.axis = .vertical stackView.addArrangedSubview(statusIcon) stackView.addArrangedSubview(textStackView) contentView.addSubview(stackView) statusIcon.snp.makeConstraints { make in make.size.equalTo(PhotonActionSheetCellUX.StatusIconSize) } let padding = PhotonActionSheetCell.Padding let topPadding = PhotonActionSheetCell.HorizontalPadding stackView.snp.makeConstraints { make in make.edges.equalTo(contentView).inset(UIEdgeInsets(top: topPadding, left: padding, bottom: topPadding, right: padding)) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(with action: PhotonActionSheetItem, syncManager: SyncManager? = nil) { titleLabel.text = action.title titleLabel.textColor = UIColor.theme.tableView.rowText titleLabel.textColor = action.accessory == .Text ? titleLabel.textColor.withAlphaComponent(0.6) : titleLabel.textColor titleLabel.adjustsFontSizeToFitWidth = false titleLabel.numberOfLines = 2 titleLabel.lineBreakMode = .byTruncatingTail titleLabel.minimumScaleFactor = 0.5 subtitleLabel.text = action.text subtitleLabel.textColor = UIColor.theme.tableView.rowText subtitleLabel.isHidden = action.text == nil subtitleLabel.numberOfLines = 0 titleLabel.font = action.bold ? DynamicFontHelper.defaultHelper.DeviceFontLargeBold : DynamicFontHelper.defaultHelper.LargeSizeRegularWeightAS accessibilityIdentifier = action.iconString ?? action.accessibilityId accessibilityLabel = action.title selectionStyle = action.tapHandler != nil ? .default : .none if let iconName = action.iconString { switch action.iconType { case .Image: let image = UIImage(named: iconName)?.withRenderingMode(.alwaysTemplate) statusIcon.image = image statusIcon.tintColor = action.iconTint ?? self.tintColor case .URL: let image = UIImage(named: iconName)?.createScaled(PhotonActionSheetUX.IconSize) statusIcon.layer.cornerRadius = PhotonActionSheetUX.IconSize.width / 2 statusIcon.sd_setImage(with: action.iconURL, placeholderImage: image, options: []) { (img, err, _, _) in if let img = img { self.statusIcon.image = img.createScaled(PhotonActionSheetUX.IconSize) self.statusIcon.layer.cornerRadius = PhotonActionSheetUX.IconSize.width / 2 } } case .TabsButton: let label = UILabel(frame: CGRect()) label.text = action.tabCount label.font = UIFont.boldSystemFont(ofSize: UIConstants.DefaultChromeSmallSize) label.textColor = UIColor.theme.textField.textAndTint let image = UIImage(named: iconName)?.withRenderingMode(.alwaysTemplate) statusIcon.image = image statusIcon.addSubview(label) label.snp.makeConstraints { (make) in make.centerX.equalTo(statusIcon) make.centerY.equalTo(statusIcon) } default: break } if statusIcon.superview == nil { if action.iconAlignment == .right { stackView.addArrangedSubview(statusIcon) } else { stackView.insertArrangedSubview(statusIcon, at: 0) } } else { if action.iconAlignment == .right { statusIcon.removeFromSuperview() stackView.addArrangedSubview(statusIcon) } } } else { statusIcon.removeFromSuperview() } if action.accessory != .Sync { syncButton?.removeFromSuperview() } if let name = action.badgeIconName, action.isEnabled, let parent = statusIcon.superview { badgeOverlay = BadgeWithBackdrop(imageName: name) badgeOverlay?.add(toParent: parent) badgeOverlay?.layout(onButton: statusIcon) badgeOverlay?.show(true) // Custom dark theme tint needed here, it is overkill to create a '.theme' color just for this. let color = ThemeManager.instance.currentName == .dark ? UIColor(white: 0.3, alpha: 1): UIColor.theme.actionMenu.closeButtonBackground badgeOverlay?.badge.tintBackground(color: color) } switch action.accessory { case .Text: disclosureLabel.font = action.bold ? DynamicFontHelper.defaultHelper.DeviceFontLargeBold : DynamicFontHelper.defaultHelper.LargeSizeRegularWeightAS disclosureLabel.text = action.accessoryText disclosureLabel.textColor = titleLabel.textColor stackView.addArrangedSubview(disclosureLabel) case .Disclosure: stackView.addArrangedSubview(disclosureIndicator) case .Switch: toggleSwitch.setOn(action.isEnabled) stackView.addArrangedSubview(toggleSwitch.mainView) case .Sync: if let manager = syncManager { let padding = PhotonActionSheetCell.Padding if syncButton == nil { syncButton = SyncMenuButton(with: manager) syncButton?.contentHorizontalAlignment = .center syncButton?.snp.makeConstraints { make in make.width.equalTo(40 + padding) make.height.equalTo(40) } } stackView.addArrangedSubview(syncButton ?? SyncMenuButton(with: manager)) syncButton?.updateAnimations() stackView.snp.remakeConstraints { make in make.edges.equalTo(contentView).inset(UIEdgeInsets(top: 0, left: padding, bottom: 0, right: 0)) } } default: break // Do nothing. The rest are not supported yet. } action.customRender?(titleLabel, contentView) } }
9d869399151270e6494c1bd2dbc4fc18
40.108392
159
0.645063
false
false
false
false
a2/ParksAndRecreation
refs/heads/master
Localize.playground/Sources/Localize.swift
mit
1
import Foundation private typealias LocalizationSegment = (String, [NSString]) private func +(lhs: LocalizationSegment, rhs: LocalizationSegment) -> LocalizationSegment { return (lhs.0 + rhs.0, lhs.1 + rhs.1) } private func +(lhs: LocalizationSegment, rhs: LocalizableText) -> LocalizationSegment { return lhs + rhs.localizationSegments } private extension LocalizableText { private var localizationSegments: LocalizationSegment { switch self { case .Tree(let segments): return segments.reduce(("", []), combine: +) case .Segment(let element): return (element, []) case .Expression(let value): return ("%@", [ value ]) } } } public func localize(text: LocalizableText, tableName: String? = nil, bundle: NSBundle = NSBundle.mainBundle(), value: String = "", comment: String) -> String { let (key, strings) = text.localizationSegments let format = bundle.localizedStringForKey(key, value: value, table: tableName) guard !strings.isEmpty else { return format } let args = strings.map { Unmanaged.passRetained($0).toOpaque() } as [CVarArgType] let formatted = String(format: format, arguments: args) for ptr in args { Unmanaged<NSString>.fromOpaque(ptr as! COpaquePointer).release() } return formatted }
0627340f58837fbd6d552f7767ccc67a
32.365854
160
0.658626
false
false
false
false
wangweicheng7/ClouldFisher
refs/heads/master
CloudFisher/Class/Square/View/PWSquareTableViewCell.swift
mit
1
// // PWSquareTableViewCell.swift // firimer // // Created by 王炜程 on 2016/11/29. // Copyright © 2016年 wangweicheng. All rights reserved. // import UIKit import Kingfisher class PWSquareTableViewCell: UITableViewCell { class func IdeSquareTableViewCell() -> String { return "PWSquareTableViewCellIdentify" } fileprivate var _model: PWAppInfoModel? var model: PWAppInfoModel? { get { return _model } set (m) { _model = m if let build = _model?.build { buildLabel.text = "\(build)" } if let version = _model?.version { versionLabel.text = "\(version)" } if let type = _model?.type { typeLabel.text = (type == 1) ? " 测试版 " : " 线上版 " // 边距用空格占位 } if let time = _model?.create_time { let date = Date(timeIntervalSince1970: time) let formatter = DateFormatter() formatter.dateFormat = "HH:mm MM.dd" timeLabel.text = formatter.string(from: date) } noteLabel.text = _model?.note if let icon = _model?.appid { let url = URL(string: Api.baseUrl + Api.image + "\(icon).png") iconImageView.kf.setImage(with: url, placeholder: UIImage(named: "icon")) } } } @IBOutlet weak var infoView: UIView! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var versionLabel: UILabel! @IBOutlet weak var buildLabel: UILabel! @IBOutlet weak var platformLabel: UILabel! @IBOutlet weak var noteLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code infoView.layer.cornerRadius = 3 infoView.layer.masksToBounds = true } @IBAction func installAction(_ sender: Any) { } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func downloadAction(_ sender: UIButton) { guard let name = model?.name else { print("文件名为空") return } let urlString = "itms-services://?action=download-manifest&url=" + Api.baseUrl + Api.file + (model?.name)! + ".plist" if let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) }else{ print("下载失败") } } }
bfd717b3a2778032529b522714d1cd73
28.776596
125
0.547338
false
false
false
false
muukii/PhotosPicker
refs/heads/master
PhotosPicker/Sources/PhotosPickerCollectionsItem.swift
mit
2
// PhotosPickerCollection.swift // // Copyright (c) 2015 muukii // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Photos public class PhotosPickerCollectionsItem { public private(set) var title: String public private(set) var numberOfAssets: Int public var assets: PhotosPickerAssets { didSet { self.cachedDividedAssets = nil self.cachedTopImage = nil } } public typealias SelectionHandler = ((collectionsController: PhotosPickerCollectionsController, item: PhotosPickerCollectionsItem) -> Void) public var selectionHandler: SelectionHandler? public func requestDividedAssets(result: ((dividedAssets: DividedDayPhotosPickerAssets) -> Void)?) { if let dividedAssets = self.cachedDividedAssets { result?(dividedAssets: dividedAssets) return } self.assets.requestDividedAssets { (dividedAssets) -> Void in self.cachedDividedAssets = dividedAssets result?(dividedAssets: dividedAssets) } } public func requestTopImage(result: ((image: UIImage?) -> Void)?) { if let image = self.cachedTopImage { result?(image: image) return } self.requestDividedAssets { (dividedAssets) -> Void in if let topAsset: PhotosPickerAsset = dividedAssets.first?.assets.first { topAsset.requestImage(CGSize(width: 100, height: 100), result: { (image) -> Void in self.cachedTopImage = image result?(image: image) return }) } } } public init(title: String, numberOfAssets: Int, assets: PhotosPickerAssets) { self.title = title self.numberOfAssets = numberOfAssets self.assets = assets } // TODO: Cache private var cachedTopImage: UIImage? private var cachedDividedAssets: DividedDayPhotosPickerAssets? }
6b6c7c4f49a1b38e8df2d86e758fe8a0
34.32967
143
0.639079
false
false
false
false
crescentflare/AppConfigSwift
refs/heads/master
AppConfigSwift/Classes/Model/AppConfigModelMapper.swift
mit
1
// // AppConfigModelMapper.swift // AppConfigSwift Pod // // Library model: mapping between dictionary and model // Used to map values dynamically between the custom model and internally stored dictionaries (for overriding settings) // Also provides optional categorization // // Enum for mapping mode public enum AppConfigModelMapperMode { case collectKeys case toDictionary case fromDictionary } // Mapping class public class AppConfigModelMapper { // -- // MARK: Members // -- var categorizedFields: AppConfigOrderedDictionary<String, [String]> = AppConfigOrderedDictionary() var globalCategorizedFields: AppConfigOrderedDictionary<String, [String]> = AppConfigOrderedDictionary() var rawRepresentableFields: [String] = [] var rawRepresentableFieldValues: [String: [String]] = [:] var dictionary: [String: Any] = [:] var globalDictionary: [String: Any] = [:] var mode: AppConfigModelMapperMode // -- // MARK: Initialization // -- // Initialization (for everything except FromDictionary mode) public init(mode: AppConfigModelMapperMode) { self.mode = mode } // Initialization (to be used with FromDictionary mode) public init(dictionary: [String: Any], globalDictionary: [String: Any], mode: AppConfigModelMapperMode) { self.dictionary = dictionary self.globalDictionary = globalDictionary self.mode = mode } // -- // MARK: Mapping // -- // Map between key and value: boolean public func map(key: String, value: inout Bool, category: String = "", global: Bool = false) { if mode == .toDictionary { if global { globalDictionary[key] = value } else { dictionary[key] = value } } else if mode == .fromDictionary && global && globalDictionary[key] != nil { value = globalDictionary[key] as! Bool } else if mode == .fromDictionary && !global && dictionary[key] != nil { value = dictionary[key] as! Bool } else if mode == .collectKeys { add(key: key, category: category, global: global) } } // Map between key and value: int public func map(key: String, value: inout Int, category: String = "", global: Bool = false) { if mode == .toDictionary { if global { globalDictionary[key] = value } else { dictionary[key] = value } } else if mode == .fromDictionary && global && globalDictionary[key] != nil { value = globalDictionary[key] as! Int } else if mode == .fromDictionary && !global && dictionary[key] != nil { value = dictionary[key] as! Int } else if mode == .collectKeys { add(key: key, category: category, global: global) } } // Map between key and value: string public func map(key: String, value: inout String, category: String = "", global: Bool = false) { if mode == .toDictionary { if global { globalDictionary[key] = value } else { dictionary[key] = value } } else if mode == .fromDictionary && global && globalDictionary[key] != nil { value = globalDictionary[key] as! String } else if mode == .fromDictionary && !global && dictionary[key] != nil { value = dictionary[key] as! String } else if mode == .collectKeys { add(key: key, category: category, global: global) } } // Map between key and value: an enum containing a raw value (preferably string) public func map<T: RawRepresentable>(key: String, value: inout T, fallback: T, allValues: [T], category: String = "", global: Bool = false) { if mode == .toDictionary { if global { globalDictionary[key] = value.rawValue } else { dictionary[key] = value.rawValue } } else if mode == .fromDictionary && global && globalDictionary[key] != nil { if let raw = globalDictionary[key] as? T.RawValue { value = T(rawValue: raw)! } else { value = fallback } } else if mode == .fromDictionary && !global && dictionary[key] != nil { if let raw = dictionary[key] as? T.RawValue { value = T(rawValue: raw)! } else { value = fallback } } else if mode == .collectKeys { var stringValues: [String] = [] for value in allValues { if value.rawValue is String { stringValues.append(value.rawValue as! String) } } if stringValues.count > 0 { rawRepresentableFieldValues[key] = stringValues } add(key: key, category: category, global: global, isRawRepresentable: true) } } // After calling mapping on the model with to dictionary mode, retrieve the result using this function, for configuration settings public func getDictionaryValues() -> [String: Any] { return dictionary } // After calling mapping on the model with to dictionary mode, retrieve the result using this function, for global settings public func getGlobalDictionaryValues() -> [String: Any] { return globalDictionary } // -- // MARK: Field grouping // -- // After calling mapping on the model with this object, retrieve the grouped/categorized fields, for configuration settings public func getCategorizedFields() -> AppConfigOrderedDictionary<String, [String]> { return categorizedFields } // After calling mapping on the model with this object, retrieve the grouped/categorized fields, for global settings public func getGlobalCategorizedFields() -> AppConfigOrderedDictionary<String, [String]> { return globalCategorizedFields } // After calling mapping on the model with this object, check if a given field is a raw representable class public func isRawRepresentable(field: String) -> Bool { return rawRepresentableFields.contains(field) } // After calling mapping on the model with this object, return a list of possible values (only for raw representable types) public func getRawRepresentableValues(forField: String) -> [String]? { return rawRepresentableFieldValues[forField] } // Internal method to keep track of keys and categories private func add(key: String, category: String, global: Bool, isRawRepresentable: Bool = false) { if global { if globalCategorizedFields[category] == nil { globalCategorizedFields[category] = [] } globalCategorizedFields[category]!.append(key) } else { if categorizedFields[category] == nil { categorizedFields[category] = [] } categorizedFields[category]!.append(key) } if isRawRepresentable && !rawRepresentableFields.contains(key) { rawRepresentableFields.append(key) } } }
eccb17b23deeb319dd4e73830de67c1d
36.659794
145
0.600739
false
true
false
false
CosmicMind/Motion
refs/heads/develop
Pods/Motion/Sources/Preprocessors/IgnoreSubviewModifiersPreprocessor.swift
gpl-3.0
3
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit class IgnoreSubviewTransitionsPreprocessor: MotionCorePreprocessor { /** Processes the transitionary views. - Parameter fromViews: An Array of UIViews. - Parameter toViews: An Array of UIViews. */ override func process(fromViews: [UIView], toViews: [UIView]) { process(views: fromViews) process(views: toViews) } /** Process an Array of views for the cascade animation. - Parameter views: An Array of UIViews. */ func process(views: [UIView]) { for v in views { guard let recursive = context[v]?.ignoreSubviewTransitions else { continue } var parentView = v if v is UITableView, let wrapperView = v.subviews.get(0) { parentView = wrapperView } guard recursive else { for subview in parentView.subviews { context[subview] = nil } continue } cleanSubviewModifiers(for: parentView) } } } fileprivate extension IgnoreSubviewTransitionsPreprocessor { /** Clears the modifiers for a given view's subviews. - Parameter for view: A UIView. */ func cleanSubviewModifiers(for view: UIView) { for v in view.subviews { context[v] = nil cleanSubviewModifiers(for: v) } } }
a667ba4bd9f92f05e898a3c8c8578d3f
30.607595
80
0.690028
false
false
false
false
AlKhokhlov/SwiftyPageController
refs/heads/master
Example/SwiftyPageController/ViewController.swift
mit
1
// // ViewController.swift // ContainerControllerTest // // Created by Alexander on 8/2/17. // Copyright © 2017 CryptoTicker. All rights reserved. // import UIKit import SwiftyPageController final class ViewController: UIViewController { @IBOutlet weak var segmentControl: UISegmentedControl! var containerController: SwiftyPageController! override func viewDidLoad() { super.viewDidLoad() segmentControl.addTarget(self, action: #selector(segmentControlDidChange(_:)), for: .valueChanged) } @objc func segmentControlDidChange(_ sender: UISegmentedControl) { // select needed controller containerController.selectController(atIndex: sender.selectedSegmentIndex, animated: true) } func setupContainerController(_ controller: SwiftyPageController) { // assign variable containerController = controller // set delegate containerController.delegate = self // set animation type containerController.animator = .parallax // set view controllers let firstController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "\(FirstViewController.self)") let secondController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "\(SecondViewController.self)") let thirdController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "\(ThirdViewController.self)") let tableController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "\(TableViewController.self)") containerController.viewControllers = [firstController, secondController, thirdController, tableController] // select needed controller containerController.selectController(atIndex: 0, animated: false) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let containerController = segue.destination as? SwiftyPageController { setupContainerController(containerController) } } } // MARK: - PagesViewControllerDelegate extension ViewController: SwiftyPageControllerDelegate { func swiftyPageController(_ controller: SwiftyPageController, alongSideTransitionToController toController: UIViewController) { } func swiftyPageController(_ controller: SwiftyPageController, didMoveToController toController: UIViewController) { segmentControl.selectedSegmentIndex = containerController.viewControllers.index(of: toController)! } func swiftyPageController(_ controller: SwiftyPageController, willMoveToController toController: UIViewController) { } }
b7991e2e473ce880d181ab700fda6ab9
36.626667
144
0.718994
false
false
false
false
dreamsxin/swift
refs/heads/master
stdlib/public/core/Existential.swift
apache-2.0
3
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This file contains "existentials" for the protocols defined in // Policy.swift. Similar components should usually be defined next to // their respective protocols. internal struct _CollectionOf< IndexType : Strideable, Element > : Collection { internal init( _startIndex: IndexType, endIndex: IndexType, _ subscriptImpl: (IndexType) -> Element ) { self.startIndex = _startIndex self.endIndex = endIndex self._subscriptImpl = subscriptImpl } /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). func makeIterator() -> AnyIterator<Element> { var index = startIndex return AnyIterator { () -> Element? in if _fastPath(index != self.endIndex) { self.formIndex(after: &index) return self._subscriptImpl(index) } return nil } } internal let startIndex: IndexType internal let endIndex: IndexType internal func index(after i: IndexType) -> IndexType { return i.advanced(by: 1) } internal subscript(i: IndexType) -> Element { return _subscriptImpl(i) } internal let _subscriptImpl: (IndexType) -> Element }
268f869ca65ab7c5dfbd59e32d29d58e
27.896552
80
0.622315
false
false
false
false
mortorqrobotics/morscout-ios
refs/heads/master
MorScout/View Controllers/LoginVC.swift
mit
1
// // LoginVC.swift // MorScout // // Created by Farbod Rafezy on 1/16/16. // Copyright © 2016 MorTorq. All rights reserved. // import Foundation import UIKit import SwiftyJSON class LoginVC: UIViewController { @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() self.setupView() usernameTextField.becomeFirstResponder() } func setupView() { usernameTextField.delegate = self passwordTextField.delegate = self // set paddings for text fields let usernamePaddingView = UIView( frame: CGRect(x: 0, y: 0, width: 8, height: self.usernameTextField.frame.height)) let passwordPaddingView = UIView( frame: CGRect(x: 0, y: 0, width: 8, height: self.passwordTextField.frame.height)) usernameTextField.leftView = usernamePaddingView usernameTextField.leftViewMode = UITextFieldViewMode.always passwordTextField.leftView = passwordPaddingView passwordTextField.leftViewMode = UITextFieldViewMode.always } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func clickLogin(_ sender: UIButton) { showLoading() login() } func login() { httpRequest(morTeamURL + "/login", type: "POST", data: [ "username": usernameTextField.text!, "password": passwordTextField.text!, "rememberMe": "true", ]) { responseText in if responseText == "Invalid login credentials"{ DispatchQueue.main.async(execute: { self.hideLoading() alert(title: "Incorrect Username/Password", message: "This Username/Password combination does not exist.", buttonText: "OK", viewController: self) }) } else { //login successful let user = parseJSON(responseText) let storedUserProperties = [ "username", "firstname", "lastname", "_id", "phone", "email", "profpicpath",] //store user properties in storage for (key, value):(String, JSON) in user { if storedUserProperties.contains(key) { storage.set(String(describing: value), forKey: key) } } if user["team"].exists() { storage.set(false, forKey: "noTeam") storage.set(user["team"]["id"].stringValue, forKey: "team") storage.set(user["position"].stringValue, forKey: "position") self.goTo(viewController: "reveal") } else { storage.set(true, forKey: "noTeam") self.goTo(viewController: "void") // this page gives users the option // to join or create a team. } } } } /** Changes login button appearance to signify that the user is in the process of being logged in */ func showLoading() { loginButton.setTitle("Loading...", for: UIControlState()) loginButton.isEnabled = false } /** Restores login button to original appearance. */ func hideLoading() { self.loginButton.setTitle("Login", for: UIControlState()) self.loginButton.isEnabled = true } } extension LoginVC: UITextFieldDelegate { /* This is called when the return button on the keyboard is pressed. */ func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.placeholder! == "Username/Email" { passwordTextField.becomeFirstResponder() } else if textField.placeholder! == "Password" { showLoading() login() } return true } }
eba441738c3cec649a5a4652bc50bc40
32.064
166
0.565449
false
false
false
false
honghaoz/CrackingTheCodingInterview
refs/heads/master
Swift/LeetCode/记忆题 - 只需要记住最优解/362_Design Hit Counter.swift
mit
1
// 362_Design Hit Counter // https://leetcode.com/problems/design-hit-counter/ // // Created by Honghao Zhang on 10/9/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Design a hit counter which counts the number of hits received in the past 5 minutes. // //Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earliest timestamp starts at 1. // //It is possible that several hits arrive roughly at the same time. // //Example: // //HitCounter counter = new HitCounter(); // //// hit at timestamp 1. //counter.hit(1); // //// hit at timestamp 2. //counter.hit(2); // //// hit at timestamp 3. //counter.hit(3); // //// get hits at timestamp 4, should return 3. //counter.getHits(4); // //// hit at timestamp 300. //counter.hit(300); // //// get hits at timestamp 300, should return 4. //counter.getHits(300); // //// get hits at timestamp 301, should return 3. //counter.getHits(301); //Follow up: //What if the number of hits per second could be very large? Does your design scale? // // 返回过去5分钟内的hits的次数 import Foundation class Num362 { // MARK: - Use bucket // https://leetcode.com/problems/design-hit-counter/discuss/83483/Super-easy-design-O(1)-hit()-O(s)-getHits()-no-fancy-data-structure-is-needed! class HitCounter_Bucket { // hits and timestamps have 300 size, like a circular array // stores the hit count for an index var hits: [Int] // stores the time stamps for an index (index is the timestamp % 300) var timestamps: [Int] /** Initialize your data structure here. */ init() { hits = Array(repeating: 0, count: 300) timestamps = Array(repeating: 0, count: 300) } /** Record a hit. @param timestamp - The current timestamp (in seconds granularity). */ func hit(_ timestamp: Int) { let index = timestamp % 300 if timestamps[index] != timestamp { // if the timestamp at the index is not the same, this means a new cycle // needs to reset the hits count to 1 timestamps[index] = timestamp hits[index] = 1 } else { // if the timestamp is the same, we know this is duplicated hits at the same time hits[index] += 1 } } /** Return the number of hits in the past 5 minutes. @param timestamp - The current timestamp (in seconds granularity). */ func getHits(_ timestamp: Int) -> Int { var count = 0 for i in 0..<300 { // if the interval is within 300 if timestamp - timestamps[i] < 300 { count += hits[i] } } return count } } // MARK: - Naive solution, use an array to store timestamps (use as a queue) class HitCounter { // stores the hit timestamp var hits: [Int] = [] /** Initialize your data structure here. */ init() { } /** Record a hit. @param timestamp - The current timestamp (in seconds granularity). */ func hit(_ timestamp: Int) { hits.append(timestamp) } /** Return the number of hits in the past 5 minutes. @param timestamp - The current timestamp (in seconds granularity). */ func getHits(_ timestamp: Int) -> Int { var count = 0 for h in hits.reversed() { // 300 if h > timestamp - 300 { count += 1 } } return count } } /** * Your HitCounter object will be instantiated and called as such: * let obj = HitCounter() * obj.hit(timestamp) * let ret_2: Int = obj.getHits(timestamp) */ }
2fd18a1c60f9875b1e085d30764835eb
27.076336
257
0.630234
false
false
false
false
moyazi/SwiftDayList
refs/heads/master
SwiftDayList/MainTableViewController.swift
mit
1
// // MainTableViewController.swift // SwiftDayList // // Created by leoo on 2017/5/27. // Copyright © 2017年 Het. All rights reserved. // import UIKit class MainTableViewController: UITableViewController { var dataSource:[String] = ["Day1","Day2","Day3","Day4","Day5","Day6","Day7","Day8"] override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations self.title = "Main Days" self.clearsSelectionOnViewWillAppear = false self.view.backgroundColor = UIColor(colorLiteralRed: 250/255.0, green: 250/255.0, blue: 225/255.0, alpha: 1) self.tableView.tableHeaderView = UIView() self.tableView.tableFooterView = UIView() self.navigationController?.navigationBar.tintColor = UIColor.black self.navigationController?.navigationBar.barTintColor = UIColor(colorLiteralRed: 250/255.0, green: 250/255.0, blue: 225/255.0, alpha: 1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return self.dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCellIndentif", for: indexPath) cell.textLabel?.text = self.dataSource[indexPath.row] cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator cell.detailTextLabel?.textColor = UIColor.red cell.backgroundColor = UIColor(colorLiteralRed: 250/255.0, green: 250/255.0, blue: 240/255.0, alpha: 0.8) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let indef:String = self.dataSource[indexPath.row] if indef == "Day2" { let sb = UIStoryboard(name: "Main", bundle: nil) let vc = sb.instantiateViewController(withIdentifier: "Day2MainViewController") as! Day2MainViewController self.navigationController!.pushViewController(vc, animated: true) return } if indef == "Day7" { let sb = UIStoryboard(name: "Main", bundle: nil) let vc = sb.instantiateViewController(withIdentifier: "Day7MainViewController") as! Day7MainViewController self.navigationController!.pushViewController(vc, animated: true) return } if indef == "Day8" { let sb = UIStoryboard(name: "Main", bundle: nil) let vc = sb.instantiateViewController(withIdentifier: "Day8MainViewController") as! Day8MainViewController self.navigationController!.pushViewController(vc, animated: true) return } if indef == "Day5" { let vc = Day5MainViewController() self.present(vc, animated: true, completion: nil) return } //注意此处动态生成VC时必须要加上项目名 "SwiftDayList." let VCClass = NSClassFromString("SwiftDayList."+indef+"MainViewController") as! UIViewController.Type self.navigationController?.pushViewController(VCClass.init(), animated: 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.destinationViewController. // Pass the selected object to the new view controller. } */ }
13539ce2862ac5395d57fd0fbb9fdf08
39.69
144
0.664045
false
false
false
false
ikuehne/Papaya
refs/heads/master
Sources/Algorithms.swift
mit
1
/** A file for basic graph algorithms, such as BFS, DFS, matchings, etc. */ /** An array extension to pop the last element from an array. */ private extension Array { mutating func pop() -> Element { let element = self[self.count-1] self.removeAtIndex(self.count-1) return element } } /** A basic queue structure used by BFS algorithm. */ private struct Queue<Element> { var items = [Element]() mutating func enqueue(item: Element) { items.insert(item, atIndex: 0) } mutating func dequeue() -> Element { /* let element = items[items.count-1] items.removeAtIndex(items.count-1) return element */ return items.pop() } var isEmpty : Bool { return items.count == 0 } } /** Creates a dictionary of successors in a graph, using the BFS algorithm and starting at a given vertex. - parameter graph: The graph to search in. - parameter start: The vertex from which to begin the BFS. - returns: A dictionary of each vertex's parent, or the vertex visited just before the vertex. */ private func buildBFSParentDict<G: Graph, V: Hashable where V == G.Vertex>( graph: G, start: V) -> [V: V] { var queue = Queue<V>() var visited = Set<V>() var current: V var result = [V: V]() queue.enqueue(start) visited.insert(start) result[start] = start while !queue.isEmpty { current = queue.dequeue() let neighbors = try! graph.neighbors(current) for neighbor in neighbors { if !visited.contains(neighbor) { queue.enqueue(neighbor) result[neighbor] = current visited.insert(neighbor) } } } return result } /** Gives the shortest path from one vertex to another in an unweighted graph. - parameter graph: The graph in which to search. - parameter start: The vertex from which to start the BFS. - parameter end: The destination vertex. - returns: An optional array that gives the shortest path from start to end. returns nil if no such path exists. */ public func breadthFirstPath<G: Graph, V: Hashable where V == G.Vertex>( graph: G, start: V, end: V) -> [V]? { let parentsDictionary = buildBFSParentDict(graph, start: start) var result: [V] = [end] if end == start { return result } if let first = parentsDictionary[end] { var current = first while current != start { result.insert(current, atIndex: 0) current = parentsDictionary[current]! } } else { return nil } result.insert(start, atIndex: 0) return result } // Idea- When lots of shortest paths queries are expected, there should be a // way to store the parentsDictionary so it's only computed once. /** A structure describing a weighted edge. Prim's algorithm priority queue holds these. */ private struct WeightedEdge<Vertex> { let from: Vertex let to: Vertex let weight: Double } /** Runs Prim's algorithm on a weighted undirected graph. - parameter graph: A weighted undirected graph for which to create a minimum spanning tree. - returns: A minimum spanning tree of the input graph. */ public func primsSpanningTree<G: WeightedGraph where G.Vertex: Hashable>( graph: G) -> G { var tree = G() var addedVerts = Set<G.Vertex>() var queue = PriorityHeap<WeightedEdge<G.Vertex>>() { $0.weight < $1.weight } let firstVertex = graph.vertices[0] try! tree.addVertex(firstVertex) addedVerts.insert(firstVertex) for neighbor in try! graph.neighbors(firstVertex) { let weight = try! graph.weight(firstVertex, to: neighbor)! queue.insert(WeightedEdge<G.Vertex>(from: firstVertex, to: neighbor, weight: weight)) } var currentEdge: WeightedEdge<G.Vertex> let target = graph.vertices.count // currently, vertices is computed many times for each graph. // trade some space for time and store sets of vertices? while addedVerts.count < target { repeat { currentEdge = queue.extract()! } while addedVerts.contains(currentEdge.to) // can cause infinite loop? // can cause unwrapping of nil? try! tree.addVertex(currentEdge.to) try! tree.addEdge(currentEdge.from, to: currentEdge.to, weight: currentEdge.weight) addedVerts.insert(currentEdge.to) for neighbor in try! graph.neighbors(currentEdge.to) { let weight = try! graph.weight(currentEdge.to, to: neighbor) queue.insert(WeightedEdge<G.Vertex>(from: currentEdge.to, to: neighbor, weight: weight!)) } } return tree } /* /** A structure used for storing shortest-path estimates for vertices in a graph. */ private struct WeightedVertex<V: Hashable>: Hashable { let vertex: V // The path weight bound and parent may be updated, or 'relaxed' var bound: Double var parent: V? var hashValue : Int { return vertex.hashValue } /*func ==(lhs: Self, rhs: Self) -> Bool { return lhs.vertex == rhs.vertex }*/ } private func ==<V: Hashable>(lhs: WeightedVertex<V>, rhs: WeightedVertex<V>) -> Bool { return lhs.vertex == rhs.vertex } */ /** A class for running Dijkstra's algorithm on weighted graphs. It stores the .d and .pi attributes for the graph's vertices, as described in CLRS, and handles procedures such as initialize single source and relax. Note that Dijkstra assumes a positive-weight graph. */ private class DijkstraController<G: WeightedGraph, V: Hashable where G.Vertex == V> { var distances = [V: Double]() var parents = [V: V]() var graph: G var start: V /** Initialize single source (see CLRS) - gives each vertex a distance estimate of infinity (greater than the total weight of all edges in the graph), and a parent value of nil (not in the dictionary). - parameter g: A weighted graph on which we will be searching for shortest paths. - parameter start: the vertex to start from - this will get a distance estimate of 0. */ init(g: G, s: V) { graph = g start = s let totalweights = g.totalWeight + 1.0 for vertex in g.vertices { distances[vertex] = totalweights } distances[start] = 0 } /** Relaxes the distance estimate of the second given vertex by way of the first given vertex. - parameter from: The vertex from which we relax the distance estimate. - parameter to: the vertex for which we relax the distance estimate. Note, this assumes that the edge and both vertices exist in the graph. */ func relax(from: V, to: V) { let weight = try! graph.weight(from, to: to)! if distances[to]! > distances[from]! + weight { distances[to] = distances[from]! + weight parents[to] = from } } /** Runs dijkstra's algorithm on the graph, as described in CLRS. Just sets up the parent and distance bound dictionaries, does not return any paths - that method is different. */ func dijkstra() { var finished = Set<V>() var queue = PriorityHeap<V>(items: graph.vertices) { self.distances[$0]! <= self.distances[$1]! } while queue.peek() != nil { let vertex = queue.extract()! finished.insert(vertex) for neighbor in try! graph.neighbors(vertex) { relax(vertex, to: neighbor) try! queue.increasePriorityMatching(neighbor, matchingPredicate: { $0 == neighbor }) // this maintains the heap property - we may decrease the key // of the neighbor } } } /** Gives the shortest path to the given vertex. - parameter to: The destination vertex of the path to find. - returns: an array of vertices representing the shortest path, or nil if no path exists in the graph. */ func dijkstraPath(to: V) -> [V]? { if parents[to] == nil { return nil } var result = [V]() var current: V? = to repeat { result.insert(current!, atIndex: 0) current = parents[current!] } while current != nil && current != start result.insert(start, atIndex: 0) return result } } public func dijkstraShortestPath<G: WeightedGraph, V: Hashable where G.Vertex == V>(graph: G, start: V, end: V) -> [V]? { let controller = DijkstraController<G, V>(g: graph, s: start) controller.dijkstra() return controller.dijkstraPath(end) }
eb137c496d988dad73d75344a36d0748
28.174194
79
0.605705
false
false
false
false
googlecodelabs/admob-rewarded-video
refs/heads/master
ios/final/RewardedVideoExample/ViewController.swift
apache-2.0
1
// // Copyright (C) 2017 Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Firebase import UIKit class ViewController: UIViewController, GADRewardBasedVideoAdDelegate { enum GameState: NSInteger { case notStarted case playing case paused case ended } /// Constant for coin rewards. let gameOverReward = 1 /// Starting time for game counter. let gameLength = 10 /// Number of coins the user has earned. var coinCount = 0 /// The reward-based video ad. var rewardBasedVideo: GADRewardBasedVideoAd! /// The countdown timer. var timer: Timer? /// The game counter. var counter = 10 /// The state of the game. var gameState = GameState.notStarted /// The date that the timer was paused. var pauseDate: Date? /// The last fire date before a pause. var previousFireDate: Date? /// In-game text that indicates current counter value or game over state. @IBOutlet weak var gameText: UILabel! /// Button to restart game. @IBOutlet weak var playAgainButton: UIButton! /// Text that indicates current coin count. @IBOutlet weak var coinCountLabel: UILabel! @IBOutlet weak var watchAdButton: UIButton! override func viewDidLoad() { super.viewDidLoad() rewardBasedVideo = GADRewardBasedVideoAd.sharedInstance() rewardBasedVideo.delegate = self coinCountLabel.text = "Coins: \(self.coinCount)" // Pause game when application is backgrounded. NotificationCenter.default.addObserver(self, selector: #selector(ViewController.applicationDidEnterBackground(_:)), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) // Resume game when application is returned to foreground. NotificationCenter.default.addObserver(self, selector: #selector(ViewController.applicationDidBecomeActive(_:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) startNewGame() } // MARK: Game logic fileprivate func startNewGame() { gameState = .playing counter = gameLength playAgainButton.isHidden = true watchAdButton.isHidden = true rewardBasedVideo.load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313") gameText.text = String(counter) timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(ViewController.timerFireMethod(_:)), userInfo: nil, repeats: true) } func applicationDidEnterBackground(_ notification: Notification) { // Pause the game if it is currently playing. if gameState != .playing { return } gameState = .paused // Record the relevant pause times. pauseDate = Date() previousFireDate = timer?.fireDate // Prevent the timer from firing while app is in background. timer?.fireDate = Date.distantFuture } func applicationDidBecomeActive(_ notification: Notification) { // Resume the game if it is currently paused. if gameState != .paused { return } gameState = .playing // Calculate amount of time the app was paused. let pauseTime = (pauseDate?.timeIntervalSinceNow)! * -1 // Set the timer to start firing again. timer?.fireDate = (previousFireDate?.addingTimeInterval(pauseTime))! } func timerFireMethod(_ timer: Timer) { counter -= 1 if counter > 0 { gameText.text = String(counter) } else { endGame() } } fileprivate func earnCoins(_ coins: NSInteger) { coinCount += coins coinCountLabel.text = "Coins: \(self.coinCount)" } fileprivate func endGame() { gameState = .ended gameText.text = "Game over!" playAgainButton.isHidden = false if rewardBasedVideo.isReady == true { watchAdButton.isHidden = false } timer?.invalidate() timer = nil earnCoins(gameOverReward) } // MARK: Button actions @IBAction func playAgain(_ sender: AnyObject) { startNewGame() } @IBAction func watchAd(_ sender: Any) { if rewardBasedVideo.isReady == true { rewardBasedVideo.present(fromRootViewController: self) } } // MARK: GADRewardBasedVideoAdDelegate implementation func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didFailToLoadWithError error: Error) { print("Reward based video ad failed to load: \(error.localizedDescription)") } func rewardBasedVideoAdDidReceive(_ rewardBasedVideoAd: GADRewardBasedVideoAd) { print("Reward based video ad is received.") } func rewardBasedVideoAdDidOpen(_ rewardBasedVideoAd: GADRewardBasedVideoAd) { print("Opened reward based video ad.") } func rewardBasedVideoAdDidStartPlaying(_ rewardBasedVideoAd: GADRewardBasedVideoAd) { print("Reward based video ad started playing.") } func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd) { print("Reward based video ad is closed.") } func rewardBasedVideoAdWillLeaveApplication(_ rewardBasedVideoAd: GADRewardBasedVideoAd) { print("Reward based video ad will leave application.") } func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didRewardUserWith reward: GADAdReward) { print("Reward received with currency: \(reward.type), amount \(reward.amount).") earnCoins(NSInteger(reward.amount)) } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } }
1eee9cbe6f9a6b672f2ec17c28d96a46
28.252381
92
0.709914
false
false
false
false
EstebanVallejo/sdk-ios
refs/heads/master
MercadoPagoSDK/MercadoPagoSDK/Fingerprint.swift
mit
2
// // Fingerprint.swift // MercadoPagoSDK // // Created by Matias Gualino on 28/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation import UIKit public class Fingerprint : NSObject { public var fingerprint : [String : AnyObject]? public override init () { super.init() self.fingerprint = deviceFingerprint() } public func toJSONString() -> String { return JSON(self.fingerprint!).toString() } public func deviceFingerprint() -> [String : AnyObject] { var device : UIDevice = UIDevice.currentDevice() var dictionary : [String : AnyObject] = [String : AnyObject]() dictionary["os"] = "iOS" let devicesId : [AnyObject]? = devicesID() if devicesId != nil { dictionary["vendor_ids"] = devicesId! } if !String.isNullOrEmpty(device.hwmodel) { dictionary["model"] = device.hwmodel } dictionary["os"] = "iOS" if !String.isNullOrEmpty(device.systemVersion) { dictionary["system_version"] = device.systemVersion } let screenSize: CGRect = UIScreen.mainScreen().bounds var width = NSString(format: "%.0f", screenSize.width) var height = NSString(format: "%.0f", screenSize.height) dictionary["resolution"] = "\(width)x\(height)" dictionary["ram"] = device.totalMemory dictionary["disk_space"] = device.totalDiskSpace dictionary["free_disk_space"] = device.freeDiskSpace var moreData = [String : AnyObject]() moreData["feature_camera"] = device.cameraAvailable moreData["feature_flash"] = device.cameraFlashAvailable moreData["feature_front_camera"] = device.frontCameraAvailable moreData["video_camera_available"] = device.videoCameraAvailable moreData["cpu_count"] = device.cpuCount moreData["retina_display_capable"] = device.retinaDisplayCapable if device.userInterfaceIdiom == UIUserInterfaceIdiom.Pad { moreData["device_idiom"] = "Pad" } else { moreData["device_idiom"] = "Phone" } if device.canSendSMS { moreData["can_send_sms"] = 1 } else { moreData["can_send_sms"] = 0 } if device.canMakePhoneCalls { moreData["can_make_phone_calls"] = 1 } else { moreData["can_make_phone_calls"] = 0 } if NSLocale.preferredLanguages().count > 0 { moreData["device_languaje"] = NSLocale.preferredLanguages()[0] } if !String.isNullOrEmpty(device.model) { moreData["device_model"] = device.model } if !String.isNullOrEmpty(device.platform) { moreData["platform"] = device.platform } moreData["device_family"] = device.deviceFamily.rawValue if !String.isNullOrEmpty(device.name) { moreData["device_name"] = device.name } /*var simulator : Bool = false #if TARGET_IPHONE_SIMULATOR simulator = YES #endif if simulator { moreData["simulator"] = 1 } else { moreData["simulator"] = 0 }*/ moreData["simulator"] = 0 dictionary["vendor_specific_attributes"] = moreData return dictionary } public func devicesID() -> [AnyObject]? { let systemVersionString : String = UIDevice.currentDevice().systemVersion let systemVersion : Float = (systemVersionString.componentsSeparatedByString(".")[0] as NSString).floatValue if systemVersion < 6 { let uuid : String = NSUUID().UUIDString if !String.isNullOrEmpty(uuid) { var dic : [String : AnyObject] = ["name" : "uuid"] dic["value"] = uuid return [dic] } } else { let vendorId : String = UIDevice.currentDevice().identifierForVendor.UUIDString let uuid : String = NSUUID().UUIDString var dicVendor : [String : AnyObject] = ["name" : "vendor_id"] dicVendor["value"] = vendorId var dic : [String : AnyObject] = ["name" : "uuid"] dic["value"] = uuid return [dicVendor, dic] } return nil } }
9c1a0da2ee397172c5143c0c1b0c4488
30.678322
116
0.557739
false
false
false
false
brandonlee503/Atmosphere
refs/heads/master
Weather App/Forecast.swift
mit
2
// // Forecast.swift // Weather App // // Created by Brandon Lee on 8/17/15. // Copyright (c) 2015 Brandon Lee. All rights reserved. // import Foundation // Main purpose is to act as a wrapper for both the CurrentWeather and DailyWeather models struct Forecast { var currentWeather: CurrentWeather? var weekly: [DailyWeather] = [] init(weatherDictionary: [String: AnyObject]?) { // Parse the contents of dictionary and create populated instance of current weather // Optional binding to make sure jsonDictionary returns non-nil value, // if so cast it to a dictionary type and assign to variable if let currentWeatherDictionary = weatherDictionary?["currently"] as? [String: AnyObject] { currentWeather = CurrentWeather(weatherDictionary: currentWeatherDictionary) } // Because of the JSON nested dictionary response... And some pro optional chaining if let weeklyWeatherArray = weatherDictionary?["daily"]?["data"] as? [[String: AnyObject]] { // Iterate over weeklyWeatherArray and retrieve each object cast it to the daily local variable for dailyWeather in weeklyWeatherArray { // Create object for each day and append to weekly array let daily = DailyWeather(dailyWeatherDict: dailyWeather) weekly.append(daily) } } } }
5a0f5c64734ab699f5050d37cec42a18
39.277778
107
0.655172
false
false
false
false
jaynakus/Signals
refs/heads/master
SwiftSignalKit/Timer.swift
mit
1
import Foundation public final class Timer { private var timer: DispatchSourceTimer? private var timeout: Double private var `repeat`: Bool private var completion: (Void) -> Void private var queue: Queue public init(timeout: Double, `repeat`: Bool, completion: @escaping(Void) -> Void, queue: Queue) { self.timeout = timeout self.`repeat` = `repeat` self.completion = completion self.queue = queue } deinit { self.invalidate() } public func start() { let timer = DispatchSource.makeTimerSource(queue: self.queue.queue) timer.setEventHandler(handler: { [weak self] in if let strongSelf = self { strongSelf.completion() if !strongSelf.`repeat` { strongSelf.invalidate() } } }) self.timer = timer if self.`repeat` { let time: DispatchTime = DispatchTime.now() + self.timeout timer.scheduleRepeating(deadline: time, interval: self.timeout) } else { let time: DispatchTime = DispatchTime.now() + self.timeout timer.scheduleOneshot(deadline: time) } timer.resume() } public func invalidate() { if let timer = self.timer { timer.cancel() self.timer = nil } } }
19e091d28643d38c273b662e7973a3a6
27.58
101
0.550035
false
false
false
false
lieonCX/TodayHeadline
refs/heads/master
TodayHealine/View/Main/PageTitleView.swift
mit
1
// // PageTitleView.swift // TodayHealine // // Created by lieon on 2017/1/16. // Copyright © 2017年 ChangHongCloudTechService. All rights reserved. // import UIKit private let scrollowLineH: CGFloat = 1.0 private let zoomScale: CGFloat = 1.2 private let labelCountPerPage: Int = 5 class PageTitleView: UIView { var titleTapAction: ((_ index: Int) -> Void)? var normalColor: (CGFloat, CGFloat, CGFloat) = (85, 85, 85) { didSet { for label in titleLabels { label.textColor = UIColor(red: normalColor.0 / 255.0, green: normalColor.1 / 255.0, blue: normalColor.2 / 255.0, alpha: 1) } } } var selectColor: (CGFloat, CGFloat, CGFloat) = (255, 128, 0) { didSet { scrollLine.backgroundColor = UIColor(red: self.selectColor.0 / 255.0, green: self.selectColor.1 / 255.0, blue: self.selectColor.2 / 255.0, alpha: 1) titleLabels[0].textColor = UIColor(red: selectColor.0 / 255.0, green: selectColor.1 / 255.0, blue: selectColor.2 / 255.0, alpha: 1) } } fileprivate var currentIndex: Int = 0 { didSet { var offsetX: CGFloat = 0 if currentIndex > labelCountPerPage/2 { offsetX = CGFloat(currentIndex) * labelWidth - bounds.width * 0.5 + labelWidth * 0.5 } else { offsetX = 0 } scrollView.setContentOffset(CGPoint(x:offsetX, y: 0), animated: true) } } fileprivate var labelWidth: CGFloat = 0.0 fileprivate var titles: [String] fileprivate var titleLabels: [UILabel] = [UILabel]() fileprivate lazy var scrollView: UIScrollView = { let sv = UIScrollView() sv.showsHorizontalScrollIndicator = false sv.showsVerticalScrollIndicator = false sv.scrollsToTop = false sv.bounces = true return sv }() fileprivate lazy var scrollLine: UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor(red: self.selectColor.0 / 255.0, green: self.selectColor.1 / 255.0, blue: self.selectColor.2 / 255.0, alpha: 1) return scrollLine }() init(frame: CGRect, titles: [String]) { self.titles = titles super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView { func setTitle(progress: CGFloat, sourceIndex: Int, targetIndex: Int) { let souceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] let offsetX = targetLabel.frame.origin.x - souceLabel.frame.origin.x let totalX = offsetX * progress scrollLine.frame.origin.x = souceLabel.frame.origin.x + totalX let colorDelta = (selectColor.0 - normalColor.0, selectColor.1 - normalColor.1, selectColor.2 - normalColor.2) souceLabel.textColor = UIColor(red: (selectColor.0 - colorDelta.0 * progress) / 255.0, green: (selectColor.1 - colorDelta.1 * progress) / 255.0, blue: (selectColor.2 - colorDelta.2 * progress) / 255.0, alpha: 1) targetLabel.textColor = UIColor(red: (normalColor.0 + colorDelta.0 * progress) / 255.0, green: (normalColor.1 + colorDelta.1 * progress) / 255.0, blue: (normalColor.2 + colorDelta.2 * progress) / 255.0, alpha: 1) currentIndex = targetIndex } } extension PageTitleView { fileprivate func setupUI() { addSubview(scrollView) scrollView.frame = bounds scrollView.contentSize = CGSize(width: CGFloat(titles.count) * frame.width / CGFloat(labelCountPerPage), height: bounds.height) setupTtitleLabels() setupBottomLineAndScrollLine() } fileprivate func setupTtitleLabels() { let labelW: CGFloat = frame.width / CGFloat(labelCountPerPage) labelWidth = labelW let labelH: CGFloat = frame.height let labelY: CGFloat = 0.0 for (index, title) in titles.enumerated() { let label = UILabel() label.font = UIFont.systemFont(ofSize: 16.0) label.textColor = UIColor(red: normalColor.0 / 255.0, green: normalColor.1 / 255.0, blue: normalColor.2 / 255.0, alpha: 1) label.tag = index label.textAlignment = .center label.text = title let labelX = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) scrollView.addSubview(label) titleLabels.append(label) label.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(titleLabellCilck(tap:))) label.addGestureRecognizer(tap) } } fileprivate func setupBottomLineAndScrollLine() { guard let firtLabel = titleLabels.first else { return } firtLabel.textColor = UIColor(red: selectColor.0 / 255.0, green: selectColor.1 / 255.0, blue: selectColor.2 / 255.0, alpha: 1) scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: 0, y: frame.height - scrollowLineH, width: firtLabel.frame.width, height: scrollowLineH) } @objc private func titleLabellCilck(tap: UITapGestureRecognizer) { guard let selectedLabel = tap.view as? UILabel else { return } let oldLabel = titleLabels[currentIndex] oldLabel.textColor = UIColor(red: normalColor.0 / 255.0, green: normalColor.1 / 255.0, blue: normalColor.2 / 255.0, alpha: 1) selectedLabel.textColor = UIColor(red: selectColor.0 / 255.0, green: selectColor.1 / 255.0, blue: selectColor.2 / 255.0, alpha: 1) currentIndex = selectedLabel.tag let offsetX = CGFloat(currentIndex) * scrollLine.frame.width UIView.animate(withDuration: 0.1) { self.scrollLine.frame.origin.x = offsetX } if let block = titleTapAction { block(selectedLabel.tag) } } }
bcb452a12ecb6311dc98cdf1f79b8cb2
43.147059
220
0.634577
false
false
false
false
Huralnyk/rxswift
refs/heads/master
RxSwiftPlayground/RxSwift.playground/Pages/04. Filter Sequences.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import RxSwift exampleOf(description: "filter") { let disposeBag = DisposeBag() let numbers = Observable.generate(initialState: 1, condition: { $0 < 101 }, iterate: { $0 + 1 }) numbers.filter { number in guard number > 1 else { return false } for i in 2 ..< number { if number % i == 0 { return false } } return true }.toArray() .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } exampleOf(description: "distinctUntilChange") { let disposeBag = DisposeBag() let searchString = Variable("") searchString.asObservable().map { $0.lowercased() }.distinctUntilChanged().subscribe(onNext: { print($0) }).addDisposableTo(disposeBag) searchString.value = "APPLE" searchString.value = "apple" searchString.value = "banana" searchString.value = "apple" } exampleOf(description: "takeWhile") { let disposeBag = DisposeBag() let numbers = Observable.from([1, 2, 3, 4, 3, 2, 1]) numbers.takeWhile { $0 < 4 } .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } //: [Next](@next)
30ba111cf6a47de9787ce54915493707
26.222222
100
0.586939
false
false
false
false
tdquang/CarlWrite
refs/heads/master
CarlWrite/dataFile.swift
mit
1
// // dataFile.swift // This file contains all the information from the writing center that the app uses. // WrittingApp // // Quang Tran & Anmol Raina // Copyright (c) 2015 Quang Tran. All rights reserved. // import UIKit class dataFile { // The code below allows changing this file class var sharedInstance: dataFile { struct Static { static var instance: dataFile? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = dataFile() } return Static.instance! } // Harcoded date. In the future these variables will use the GET command to get data from the Carleton Server var listOfAppointments = [[String]]() var tutorArray = ["Any Tutor", "Anna", "Dave", "Jeff", "Michael", "Sam"] var formFields = ["Date", "Course", "Instructor", "Topic", "Type", "State", "Due Date", "Class year", "Major", "First Visit?", "Copy for Prof?"] var paperLengthArray = ["1-2", "3-5", "6-10","11-20","20+"] var currentStateArray = ["Brainstorming", "First Draft", "Second Draft", "Final Draft"] var paperTypeArray = ["Essay", "Comps", "Resume", "Portfolio", "Application", "Other"] var dueDateArray = ["Today", "Tomorrow", "2 days", "3-5 days", "A week", "1 week+"] var goalsForVisit = ["Clarity", "Thesis/Flow", "Organization", "Citation", "Brainstorming", "Integrating evidence/support", "Learning how to proofread"] var classYearArray = ["2016", "2017", "2018", "2019"] var majorArray = ["English", "History", "Philosophy", "Economics", "Computer Science"] var yesNoArray = ["Yes", "No"] var visitSourceArray = ["Does not apply", "From an instructor", "From orientation", "From an advertisement", "From a student", "Other"] var tutorDays = [[1,2,3,4,5,6], [2,4,5], [1,4,6], [2,3], [1,3,5], [1,2,5,6]] func returnTutorDays(tutorName: String) -> [Int]{ for var index = 0; index < tutorArray.count; ++index{ if tutorArray[index] == tutorName{ return tutorDays[index] } } return [] } func returnAppointmentTimes(_: CVCalendarDayView) -> [String]{ return ["9:00", "9:20", "10:00", "10:20", "11:00", "11:20", "12:00"] } func returnListOfTutors() -> [String]{ return tutorArray } func returnPaperLengths() -> [String]{ return paperLengthArray } func returnListOfStates() -> [String]{ return currentStateArray } func returnPaperType() -> [String]{ return paperTypeArray } func returnDueDate() -> [String]{ return dueDateArray } func returnGoalsForVisit() -> [String]{ return goalsForVisit } func returnClassYear() -> [String]{ return classYearArray } func returnMajor() -> [String]{ return majorArray } func returnYesNo() -> [String]{ return yesNoArray } func returnVisitSource() -> [String]{ return visitSourceArray } func returnFormFields() -> [String]{ return formFields } func addAppointment(appointmentDetails: [String]){ listOfAppointments.append(appointmentDetails) } }
508f8c2ee1287f114166632625b7552e
33.638298
156
0.600123
false
false
false
false
Saturn-Five/ComicZipper
refs/heads/master
ComicZipper/Support/OperationError.swift
mit
2
// // OperationError.swift // ComicZipper // // Created by Ardalan Samimi on 04/01/16. // Copyright © 2016 Ardalan Samimi. All rights reserved. // import Foundation import ZipUtilities public enum OperationError { static func withCode(code: Int) -> String { var error = "Error: " switch (code) { case NOZErrorCode.CompressFailedToOpenNewZipFile.rawValue: error += "Could not create zip file." case NOZErrorCode.CompressNoEntriesToCompress.rawValue: error += "No files to compress." case NOZErrorCode.CompressMissingEntryName.rawValue: error += "Missing name for a file." case NOZErrorCode.CompressEntryCannotBeZipped.rawValue: error += "Failed to compress file(s)." case NOZErrorCode.CompressFailedToAppendEntryToZip.rawValue: error += "Failed to append file to zip." case NOZErrorCode.CompressFailedToFinalizeNewZipFile.rawValue: error += "Could not finalize archive." default: error += "Unknown error with code \(code)" } return error } }
92799dfef480edbce1284ebea0686d0c
28.222222
66
0.697719
false
false
false
false
jatraiz/IBFree
refs/heads/master
IBFree Project/IBFree/XiblessView.swift
mit
1
// // XiblessView.swift // XIBLessExample // // Created by John Stricker on 7/11/16. import Anchorage import UIKit final class XiblessView: UIView { enum ViewStyle { case simpleButton case cornerButtons } fileprivate let cornerButtons: [UIButton]? fileprivate let button: UIButton = UIButton(type: .system) init(style: ViewStyle) { // Create the corner buttons if the style calls for it if style == .cornerButtons { var buttonArray = [UIButton]() for _ in 0..<Constants.numberOfCornerButtons { buttonArray.append(UIButton(type: .system)) } cornerButtons = buttonArray } else { cornerButtons = nil } super.init(frame: CGRect.zero) configureView() } @available(*, unavailable) override init(frame: CGRect) { fatalError("init(frame:) has not been implemented") } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Configure the view private extension XiblessView { struct Constants { static let numberOfCornerButtons = 4 static let cornerButtonSize = CGSize(width: 60, height: 60) static let cornerButtonBackgroundColor = UIColor.lightGray } enum ButtonPositions: Int { case upperLeft = 0 case upperRight = 1 case lowerLeft = 2 case lowerRight = 3 } func configureView() { configureCenterButton() if let buttons = cornerButtons { configureCornerButtons(buttons) } } func configureCenterButton() { // View heirarchy addSubview(button) // Style backgroundColor = UIColor.green button.setTitle("This is a centered button without a XIB", for: UIControlState()) // Layout // The button is centered in the view button.centerXAnchor == centerXAnchor button.centerYAnchor == centerYAnchor } func configureCornerButtons(_ buttons: [UIButton]) { for (index, button) in buttons.enumerated() { // First make sure that the button's index has a position defined for it guard let position = ButtonPositions(rawValue: index) else { debugPrint("Error: \(index) not defined in ButtonPositions") continue } // View heirarchy addSubview(button) // Style & Layout // Button content and style button.setTitle(String(index + 1), for: UIControlState()) button.backgroundColor = Constants.cornerButtonBackgroundColor // Height and width of corner buttons are set by a constant button.heightAnchor == Constants.cornerButtonSize.height button.widthAnchor == Constants.cornerButtonSize.width // Place each button in its appropriate corner switch position { case .upperLeft: button.leftAnchor == leftAnchor button.topAnchor == topAnchor case .upperRight: button.rightAnchor == rightAnchor button.topAnchor == topAnchor case .lowerLeft: button.leftAnchor == leftAnchor button.bottomAnchor == bottomAnchor case .lowerRight: button.rightAnchor == rightAnchor button.bottomAnchor == bottomAnchor } } } }
dfe45302a4b132eef00684222c9f0f63
26.549618
89
0.5913
false
true
false
false
therealbnut/swift
refs/heads/master
stdlib/public/core/Bool.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Bool Datatype and Supporting Operators //===----------------------------------------------------------------------===// /// A value type whose instances are either `true` or `false`. /// /// `Bool` represents Boolean values in Swift. Create instances of `Bool` by /// using one of the Boolean literals `true` or `false`, or by assigning the /// result of a Boolean method or operation to a variable or constant. /// /// var godotHasArrived = false /// /// let numbers = 1...5 /// let containsTen = numbers.contains(10) /// print(containsTen) /// // Prints "false" /// /// let (a, b) = (100, 101) /// let aFirst = a < b /// print(aFirst) /// // Prints "true" /// /// Swift uses only simple Boolean values in conditional contexts to help avoid /// accidental programming errors and to help maintain the clarity of each /// control statement. Unlike in other programming languages, in Swift, integers /// and strings cannot be used where a Boolean value is required. /// /// For example, the following code sample does not compile, because it /// attempts to use the integer `i` in a logical context: /// /// var i = 5 /// while i { /// print(i) /// i -= 1 /// } /// /// The correct approach in Swift is to compare the `i` value with zero in the /// `while` statement. /// /// while i != 0 { /// print(i) /// i -= 1 /// } /// /// Using Imported Boolean values /// ============================= /// /// The C `bool` and `Boolean` types and the Objective-C `BOOL` type are all /// bridged into Swift as `Bool`. The single `Bool` type in Swift guarantees /// that functions, methods, and properties imported from C and Objective-C /// have a consistent type interface. @_fixed_layout public struct Bool { internal var _value: Builtin.Int1 /// Creates an instance initialized to `false`. /// /// Do not call this initializer directly. Instead, use the Boolean literal /// `false` to create a new `Bool` instance. @_transparent public init() { let zero: Int8 = 0 self._value = Builtin.trunc_Int8_Int1(zero._value) } @_versioned @_transparent internal init(_ v: Builtin.Int1) { self._value = v } public init(_ value: Bool) { self = value } } extension Bool : _ExpressibleByBuiltinBooleanLiteral, ExpressibleByBooleanLiteral { @_transparent public init(_builtinBooleanLiteral value: Builtin.Int1) { self._value = value } /// Creates an instance initialized to the specified Boolean literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you use a Boolean literal. Instead, create a new `Bool` instance by /// using one of the Boolean literals `true` or `false`. /// /// var printedMessage = false /// /// if !printedMessage { /// print("You look nice today!") /// printedMessage = true /// } /// // Prints "You look nice today!" /// /// In this example, both assignments to the `printedMessage` variable call /// this Boolean literal initializer behind the scenes. /// /// - Parameter value: The value of the new instance. @_transparent public init(booleanLiteral value: Bool) { self = value } } extension Bool { // This is a magic entry point known to the compiler. @_transparent public // COMPILER_INTRINSIC func _getBuiltinLogicValue() -> Builtin.Int1 { return _value } } extension Bool : CustomStringConvertible { /// A textual representation of the Boolean value. public var description: String { return self ? "true" : "false" } } // This is a magic entry point known to the compiler. @_transparent public // COMPILER_INTRINSIC func _getBool(_ v: Builtin.Int1) -> Bool { return Bool(v) } extension Bool : Equatable, Hashable { /// The hash value for the Boolean value. /// /// Two values that are equal always have equal hash values. /// /// - Note: The hash value is not guaranteed to be stable across different /// invocations of the same program. Do not persist the hash value across /// program runs. /// - SeeAlso: `Hashable` @_transparent public var hashValue: Int { return self ? 1 : 0 } @_transparent public static func == (lhs: Bool, rhs: Bool) -> Bool { return Bool(Builtin.cmp_eq_Int1(lhs._value, rhs._value)) } } extension Bool : LosslessStringConvertible { public init?(_ description: String) { if description == "true" { self = true } else if description == "false" { self = false } else { return nil } } } //===----------------------------------------------------------------------===// // Operators //===----------------------------------------------------------------------===// extension Bool { /// Performs a logical NOT operation on a Boolean value. /// /// The logical NOT operator (`!`) inverts a Boolean value. If the value is /// `true`, the result of the operation is `false`; if the value is `false`, /// the result is `true`. /// /// var printedMessage = false /// /// if !printedMessage { /// print("You look nice today!") /// printedMessage = true /// } /// // Prints "You look nice today!" /// /// - Parameter a: The Boolean value to negate. @_transparent public static prefix func ! (a: Bool) -> Bool { return Bool(Builtin.xor_Int1(a._value, true._value)) } } extension Bool { /// Performs a logical AND operation on two Bool values. /// /// The logical AND operator (`&&`) combines two Bool values and returns /// `true` if both of the values are `true`. If either of the values is /// `false`, the operator returns `false`. /// /// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is /// evaluated first, and the right-hand side (`rhs`) is evaluated only if /// `lhs` evaluates to `true`. For example: /// /// let measurements = [7.44, 6.51, 4.74, 5.88, 6.27, 6.12, 7.76] /// let sum = measurements.reduce(0, combine: +) /// /// if measurements.count > 0 && sum / Double(measurements.count) < 6.5 { /// print("Average measurement is less than 6.5") /// } /// // Prints "Average measurement is less than 6.5" /// /// In this example, `lhs` tests whether `measurements.count` is greater than /// zero. Evaluation of the `&&` operator is one of the following: /// /// - When `measurements.count` is equal to zero, `lhs` evaluates to `false` /// and `rhs` is not evaluated, preventing a divide-by-zero error in the /// expression `sum / Double(measurements.count)`. The result of the /// operation is `false`. /// - When `measurements.count` is greater than zero, `lhs` evaluates to /// `true` and `rhs` is evaluated. The result of evaluating `rhs` is the /// result of the `&&` operation. /// /// - Parameters: /// - lhs: The left-hand side of the operation. /// - rhs: The right-hand side of the operation. @_transparent @inline(__always) public static func && (lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows -> Bool { return lhs ? try rhs() : false } /// Performs a logical OR operation on two Bool values. /// /// The logical OR operator (`||`) combines two Bool values and returns /// `true` if at least one of the values is `true`. If both values are /// `false`, the operator returns `false`. /// /// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is /// evaluated first, and the right-hand side (`rhs`) is evaluated only if /// `lhs` evaluates to `false`. For example: /// /// let majorErrors: Set = ["No first name", "No last name", ...] /// let error = "" /// /// if error.isEmpty || !majorErrors.contains(error) { /// print("No major errors detected") /// } else { /// print("Major error: \(error)") /// } /// // Prints "No major errors detected" /// /// In this example, `lhs` tests whether `error` is an empty string. /// Evaluation of the `||` operator is one of the following: /// /// - When `error` is an empty string, `lhs` evaluates to `true` and `rhs` is /// not evaluated, skipping the call to `majorErrors.contains(_:)`. The /// result of the operation is `true`. /// - When `error` is not an empty string, `lhs` evaluates to `false` and /// `rhs` is evaluated. The result of evaluating `rhs` is the result of the /// `||` operation. /// /// - Parameters: /// - lhs: The left-hand side of the operation. /// - rhs: The right-hand side of the operation. @_transparent @inline(__always) public static func || (lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows -> Bool { return lhs ? true : try rhs() } }
989ee275c422e67cfe596c3b4e5087b2
33.205128
83
0.601199
false
false
false
false
EasySwift/EasySwift
refs/heads/master
Carthage/Checkouts/Bond/Sources/NSObject.swift
apache-2.0
6
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import ReactiveKit public protocol Deallocatable: class { var bnd_deallocated: Signal<Void, NoError> { get } } extension NSObject: Deallocatable { private struct AssociatedKeys { static var DeallocationSignalHelper = "DeallocationSignalHelper" static var DisposeBagKey = "r_DisposeBagKey" } private class BNDDeallocationSignalHelper { let subject = ReplayOneSubject<Void, NoError>() deinit { subject.completed() } } /// A signal that fires completion event when the object is deallocated. public var bnd_deallocated: Signal<Void, NoError> { if let helper = objc_getAssociatedObject(self, &AssociatedKeys.DeallocationSignalHelper) as? BNDDeallocationSignalHelper { return helper.subject.toSignal() } else { let helper = BNDDeallocationSignalHelper() objc_setAssociatedObject(self, &AssociatedKeys.DeallocationSignalHelper, helper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return helper.subject.toSignal() } } /// Use this bag to dispose disposables upon the deallocation of the receiver. public var bnd_bag: DisposeBag { if let disposeBag = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBagKey) { return disposeBag as! DisposeBag } else { let disposeBag = DisposeBag() objc_setAssociatedObject(self, &AssociatedKeys.DisposeBagKey, disposeBag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return disposeBag } } /// Bind `signal` to `bindable` and dispose in `bnd_bag` of receiver. @discardableResult public func bind<O: SignalProtocol, B: BindableProtocol>(_ signal: O, to bindable: B) where O.Element == B.Element, O.Error == NoError { signal.bind(to: bindable).disposeIn(bnd_bag) } /// Bind `signal` to `bindable` and dispose in `bnd_bag` of receiver. @discardableResult public func bind<O: SignalProtocol, B: BindableProtocol>(_ signal: O, to bindable: B) where B.Element: OptionalProtocol, O.Element == B.Element.Wrapped, O.Error == NoError { signal.bind(to: bindable).disposeIn(bnd_bag) } }
8d4fc7378df3ad774fa744e3ab854a0e
40.025
175
0.735222
false
false
false
false
samsao/DataProvider
refs/heads/master
Pod/Classes/Provider/Provider.swift
mit
1
// // Provider.swift // Pods // // Created by Guilherme Silva Lisboa on 2015-12-22. // // public typealias ProviderRemoveItemBlock = ((_ item : ProviderItem) -> Bool) public typealias ProviderRemoveSectionBlock = ((_ section : ProviderSection) -> Bool) public class Provider { // MARK: Properties public private(set) var sections : [ProviderSection] // MARK: Initialization /** Initialize provider with array of elements - parameter sections: sections for the provider. - returns: instance of created provider. */ internal init(withSections sections : [ProviderSection]) { self.sections = sections } // MARK: - Public API // MARK: Data Methods /** Get the provider item at a specific index path - parameter indexPath: index path of the desired item. - returns: item at that index path. */ public func providerItemAtIndexPath(indexPath : IndexPath) -> ProviderItem? { if(indexPath.section < self.sections.count) { let section : ProviderSection = self.sections[indexPath.section] if(indexPath.row < section.items.count) { return section.items[indexPath.row] } } return nil } // MARK: Sections /** Add sections to provider. - parameter sections: sections to be added. - returns: indexset with added sections range. */ internal func addSections(sections : [ProviderSection]) -> IndexSet{ var range : NSRange = NSRange() range.location = self.sections.count range.length = sections.count let indexSet : IndexSet = IndexSet(integersIn: range.toRange() ?? 0..<0) self.sections.append(contentsOf: sections) return indexSet } /** Add section to provider - parameter section: section to be added. - parameter index: index for the section to be added. */ internal func addSection(section : ProviderSection, index : Int) { self.sections.insert(section, at: index) } /** Remove sections with a index set. - parameter indexes: index set with sections indexes to be deleted. */ internal func removeSections(indexes : IndexSet) { self.sections.removeObjectsWith(indexSet: indexes) } /** Remove sections of the provider. - parameter sectionsToRemove: array of sections to remove in the provider. - returns: index set of removed sections. */ internal func removeSections(_ removeBlock : ProviderRemoveSectionBlock) -> IndexSet { var indexSet = IndexSet() for (index, section) in self.sections.enumerated() { if removeBlock(section) { indexSet.insert(index) } } self.sections.removeObjectsWith(indexSet: indexSet) return indexSet } // MARK: Items /** Add Item to provider at a index path - parameter item: item to be added. - parameter indexPath: index path to add this item at. */ internal func addItemToProvider(item : ProviderItem, atIndexPath indexPath : IndexPath) { self.sections[indexPath.section].items.insert(item, at: indexPath.row) } /** Add an array of items in a section of the provider. - parameter items: items to be added. - parameter section: index of the provider section to add the items. */ internal func addItemsToProvider(items : [ProviderItem], inSection sectionIndex : Int) { self.sections[sectionIndex].items.append(contentsOf: items) } /** Remove items from provider - parameter removeBlock: Block to remove the item. - parameter sectionIndex: section index to remove this items from. - returns: indexes of the deleted items in the section. */ internal func removeItems(removeBlock : ProviderRemoveItemBlock, inSection sectionIndex : Int) -> IndexSet{ var indexSet = IndexSet() for (index, item) in self.sections[sectionIndex].items.enumerated() { if removeBlock(item) { indexSet.insert(index) } } self.sections[sectionIndex].items.removeObjectsWith(indexSet: indexSet) return indexSet } /** Remove items at index paths - parameter indexPaths: index paths to be removed. */ internal func removeItems(indexPaths : [IndexPath]) { indexPaths.forEach { (indexPath) in self.sections[indexPath.section].items.remove(at: indexPath.row); } } // MARK: update Data /** Replace provider data with new one. - parameter newSections: new provider data. */ internal func updateProviderData(newSections : [ProviderSection]) { self.sections = newSections } /** Replace the data in a specific section in the provider for the new one. - parameter newItems: new section data. - parameter sectionIndex: index of the section to replace the data. */ internal func updateSectionData(newItems : [ProviderItem], sectionIndexToUpdate sectionIndex : Int) { self.sections[sectionIndex].items = newItems } internal func nullifyDelegates() { return } }
1905cbdb568177aba3fd87f316fb8ff1
27.554974
111
0.620279
false
false
false
false
YMXian/Deliria
refs/heads/master
Deliria/UIKit/UIGeometry/UIOffset+Vector2DConvertible.swift
mit
1
// // UIOffset+Vector2DConvertible.swift // Deliria // // Created by Yanke Guo on 16/2/9. // Copyright © 2016年 JuXian(Beijing) Technology Co., Ltd. All rights reserved. // import UIKit extension UIOffset: Vector2DConvertible, ExpressibleByArrayLiteral { public var x: CGFloat { get { return self.horizontal } set(value) { self.horizontal = value } } public var y: CGFloat { get { return self.vertical } set(value) { self.vertical = value } } public init(x: CGFloat, y: CGFloat) { self.horizontal = x self.vertical = y } public typealias Element = CGFloat public init(arrayLiteral elements: CGPoint.Element...) { self.init(horizontal: elements[0], vertical: elements[1]) } } extension Vector2DConvertible { public var offset: UIOffset { return UIOffset(horizontal: self.x, vertical: self.y) } }
0895cd61ea3d4b2d97545599c5bb82a3
17.1
79
0.648619
false
false
false
false
gssdromen/CedFilterView
refs/heads/master
FilterTest/ESFFilterItemModel.swift
gpl-3.0
1
// // ESFFilterModel.swift // JingJiRen_ESF_iOS // // Created by cedricwu on 12/29/16. // Copyright © 2016 Cedric Wu. All rights reserved. // import ObjectMapper extension ESFFilterItemModel { class func getDepth(model: ESFFilterItemModel) -> Int { var max = 0 guard model.subItems != nil else { return max + 1 } for item in model.subItems! { let height = ESFFilterItemModel.getDepth(model: item) if height > max { max = height } } return max + 1 } } extension ESFFilterItemModel { func getDepth() -> Int { var depth = 0 if subItems == nil { return depth } for item in subItems! { let height = item.getDepth() depth = max(height, depth) } return depth + 1 } } class ESFFilterItemModel: NSObject, Mappable { // var maxDepth = -1 var depth: Int? var maxDepth: Int? var displayText: String? var filterKey: String? var fullFilterKey: String? var id: Int? var multiple: Bool? var selected: Bool? var style: Int? var extInfo: String? var subItems: [ESFFilterItemModel]? required init?(map: Map) { } func mapping(map: Map) { depth <- map["depth"] maxDepth <- map["maxDepth"] displayText <- map["displayText"] filterKey <- map["filterKey"] fullFilterKey <- map["fullFilterKey"] id <- map["id"] multiple <- map["multiple"] selected <- map["selected"] style <- map["style"] extInfo <- map["extInfo"] subItems <- map["subItems"] } }
9ec4cc334dbae6a96d2ee9bc21543cf4
21.368421
65
0.548824
false
false
false
false
butterproject/butter-ios
refs/heads/master
Butter/API/ButterItem.swift
gpl-3.0
1
// // ButterItem.swift // Butter // // Created by DjinnGA on 24/07/2015. // Copyright (c) 2015 Butter Project. All rights reserved. // import Foundation import SwiftyJSON class ButterItem { var id: Int var properties:[String:AnyObject] = [String:AnyObject]() var torrents: [String:ButterTorrent] = [String:ButterTorrent]() func setProperty(name:String, val:AnyObject) { properties[name] = val } func getProperty(name:String) -> AnyObject? { return properties[name] } func hasProperty(name: String) -> Bool { return getProperty(name) != nil } init(id:Int,torrents: JSON) { self.id = id if (torrents != "") { for (_, subJson) in torrents { if let url = subJson["url"].string { let tor = ButterTorrent( url: url, seeds: subJson["seeds"].int!, peers: subJson["peers"].int!, quality: subJson["quality"].string!, size: subJson["size"].string!, hash: subJson["hash"].string!) self.torrents[subJson["quality"].string!] = tor } } } } init(id:Int,torrentURL: String, quality: String, size: String) { self.id = id let tor = ButterTorrent( url: torrentURL, seeds: 0, peers: 0, quality: quality, size: size, hash: "") self.torrents[quality] = tor } init(id:Int,torrents: [ButterTorrent]) { self.id = id for tor in torrents { self.torrents[tor.quality] = tor } } }
3bd5aea3f791825f62319c44e0656dc1
25.820896
68
0.488592
false
false
false
false
xiaoyangrun/DYTV
refs/heads/master
DYTV/DYTV/Classes/Home/Controller/HomeViewController.swift
mit
1
// // HomeViewController.swift // DYTV // // Created by 小羊快跑 on 2017/1/11. // Copyright © 2017年 小羊快跑. All rights reserved. // import UIKit // MARK: - 系统回调函数 class HomeViewController: UIViewController { // MARK: - 懒加载属性 //闭包创建 private lazy var pageTitleView: PageTitleView = { let titleFrame = CGRect.init(x: 0, y: 64, width: UIScreen.main.bounds.size.width, height: 44) let titles = ["推荐", "游戏", "娱乐", "去玩"]; let titleView = PageTitleView.init(frame: titleFrame, titles: titles, isScrollEnable: false) return titleView }() //记得加上 () override func viewDidLoad() { super.viewDidLoad() //记得添加, 不添加就显示不出来 automaticallyAdjustsScrollViewInsets = false //设置导航栏 setupNavigationBar() //添加pageTitleView view.addSubview(pageTitleView) } } // MARK: - 设置导航栏内容 extension HomeViewController{ //设置导航设置导航栏内容 func setupNavigationBar(){ setupLeftNavigationBar() setupRightNavigationBar() } //设置左边 func setupLeftNavigationBar(){ let btn = UIButton() btn.setImage(UIImage(named: "logo"), for: .normal) btn.sizeToFit() btn.addTarget(self, action: #selector(leftItemClick), for: .touchUpInside) navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: btn) } //设置右边 func setupRightNavigationBar(){ //0.确定uibutton的 尺寸 let size = CGSize.init(width: 40, height: 44) //1.创建历史按钮 let historyItem = UIBarButtonItem.init(imageName: "Image_my_history", highImageName: "Image_my_history_click", size: size, target: self, action: #selector(historyItemClick)) //2.创建二维码按钮 let qrCodeItem = UIBarButtonItem.init(imageName: "Image_scan", highImageName: "Image_scan_click", size: size, target: self, action: #selector(qrCodeItemClick)) //3.创建搜索按钮 let searchItem = UIBarButtonItem.init(imageName: "btn_search", highImageName: "btn_search_clicked", size: size, target: self, action: #selector(searchItemClick)) navigationItem.rightBarButtonItems = [historyItem, searchItem, qrCodeItem] } // MARK: 导航栏的事件处理 @objc private func leftItemClick() { print("点击了logo") } @objc private func qrCodeItemClick() { print("点击了二维码") } @objc private func searchItemClick() { print("点击了搜索") } @objc private func historyItemClick() { print("点击了历史") } }
3d7cfeca34fce452d72b45d954cdd816
30.935897
181
0.637094
false
false
false
false
BananosTeam/CreativeLab
refs/heads/master
Carthage/Checkouts/OAuthSwift/Demo/Common/Constants.swift
mit
7
// // Constants.swift // OAuthSwift // // Created by Dongri Jin on 7/17/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation let Twitter = [ "consumerKey": "", "consumerSecret": "" ] let Salesforce = [ "consumerKey": "", "consumerSecret": "" ] let Flickr = [ "consumerKey": "", "consumerSecret": "" ] let Github = [ "consumerKey": "", "consumerSecret": "" ] let Instagram = [ "consumerKey": "", "consumerSecret": "" ] let Foursquare = [ "consumerKey": "", "consumerSecret": "" ] let Fitbit = [ "consumerKey": "", "consumerSecret": "" ] let Withings = [ "consumerKey": "", "consumerSecret": "" ] let Linkedin = [ "consumerKey": "", "consumerSecret": "" ] let Linkedin2 = [ "consumerKey": "", "consumerSecret": "" ] let Dropbox = [ "consumerKey": "", "consumerSecret": "" ] let Dribbble = [ "consumerKey": "", "consumerSecret": "" ] let BitBucket = [ "consumerKey": "", "consumerSecret": "" ] let GoogleDrive = [ "consumerKey": "", "consumerSecret": "" ] let Smugmug = [ "consumerKey": "", "consumerSecret": "" ] let Intuit = [ "consumerKey": "", "consumerSecret": "" ] let Zaim = [ "consumerKey": "", "consumerSecret": "" ] let Tumblr = [ "consumerKey": "", "consumerSecret": "" ] let Slack = [ "consumerKey": "", "consumerSecret": "" ] let Uber = [ "consumerKey": "", "consumerSecret": "" ]
01feab069d37dc1bc0baa1daefa7c889
12.490909
55
0.546496
false
false
false
false
pisrc/RxDobby
refs/heads/master
RxDobbyExample/MenuViewController.swift
mit
1
// // MenuViewController.swift // RxDobby // // Created by ryan on 9/8/16. // Copyright © 2016 kimyoungjin. All rights reserved. // import UIKit class MenuViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.addGestureRecognizer( UIPanGestureRecognizer(target: self, action: #selector(MenuViewController.viewPannedLeft(_:)))) } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ weak var centerViewController: UIViewController? var oldXPostion: CGFloat = 0.0 func viewPannedRight(_ recognizer: UIPanGestureRecognizer) { guard let centerViewController = centerViewController else { return } let leftToRight = (recognizer.velocity(in: view).x > 0) switch recognizer.state { case .began: oldXPostion = view.frame.origin.x case .changed: let deltaX = recognizer.translation(in: view).x recognizer.setTranslation(CGPoint.zero, in: view) if view.frame.origin.x + deltaX > centerViewController.view.frame.width { break } if view.frame.origin.x + view.frame.width + deltaX < centerViewController.view.frame.width { break } view.frame.origin.x = view.frame.origin.x + deltaX case .ended: if leftToRight { dismiss(animated: true, completion: nil) } else { // 처음 위치로 되돌아감 UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: { self.view.frame.origin.x = self.oldXPostion }, completion: nil) } default: break } } func viewPannedLeft(_ recognizer: UIPanGestureRecognizer) { let rightToLeft = (recognizer.velocity(in: view).x < 0) switch recognizer.state { case .began: oldXPostion = view.frame.origin.x case .changed: let deltaX = recognizer.translation(in: view).x recognizer.setTranslation(CGPoint.zero, in: view) if 0 < view.frame.origin.x + deltaX { break } if view.frame.origin.x + view.frame.width + deltaX < 0 { break } view.frame.origin.x = view.frame.origin.x + deltaX case .ended: if rightToLeft { dismiss(animated: true, completion: nil) } else { // 처음 위치로 되돌아감 UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: { self.view.frame.origin.x = self.oldXPostion }, completion: nil) } default: break } } }
2230a598c6c834b833123f2029de9516
31.507937
107
0.493652
false
false
false
false
google/iosched-ios
refs/heads/master
Source/IOsched/Screens/Home/HomeMomentsDataSource.swift
apache-2.0
1
// // Copyright (c) 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation public struct Moment { enum CTA: String { case viewLivestream = "LIVE_STREAM" case viewMap = "MAP_LOCATION" } let attendeeRequired: Bool let cta: CTA? let displayDate: String // Ignored. Using Date formatter instead. let startTime: Date let endTime: Date let featureID: String? let featureName: String? let imageURL: URL let imageURLDarkTheme: URL let streamURL: URL? let textColor: String let timeVisible: Bool let title: String var formattedDateInterval: String { return Moment.dateIntervalFormatter.string(from: startTime, to: endTime) } var accessibilityLabel: String? { switch self { case .keynote: return NSLocalizedString("Watch the Google I/O keynote.", comment: "Accessibility label for keynote moment") case .developerKeynote: return NSLocalizedString("Watch the Google I/O developer keynote.", comment: "Accessibility label for keynote moment") case .lunchDayOne, .lunchDayTwo, .lunchDayThree: return NSLocalizedString("Visit one of the EATS food stands to grab some lunch.", comment: "Accessibility label for lunch moment") case .sessionsDayOne, .sessionsDayTwoMorning, .sessionsDayTwoAfternoon, .sessionsDayThreeMorning, .sessionsDayThreeAfternoon: return NSLocalizedString("Tune in to live sessions on the I/O livestream.", comment: "Accessibility label for sessions moment") case .afterHoursDinner: return NSLocalizedString("Eat dinner after hours at the I/O venue.", comment: "Accessibility label for dinner moment") case .dayOneWrap: return NSLocalizedString("Day one of Google I/O has concluded.", comment: "Accessibility label for end of day 1") case .dayTwoMorning: return NSLocalizedString("Get ready for day two of Google I/O.", comment: "Accessibility label for day 2 morning moment") case .concert: return NSLocalizedString("Join the I/O concert in person or remotely via livestream.", comment: "Accessibility label for concert moment") case .dayTwoWrap: return NSLocalizedString("Day two of Google I/O has concluded.", comment: "Accessibility label for end of day 2") case .dayThreeMorning: return NSLocalizedString("Get ready for day three of Google I/O.", comment: "Accessibility label for day 3 morning moment") case .dayThreeWrap: return NSLocalizedString("This year's Google I/O has concluded. See you next year!", comment: "Accessibility label for end of day 3") case _: break } return nil } var accessibilityHint: String? { if cta == .viewLivestream, self == .keynote || self == .developerKeynote { return NSLocalizedString("Double-tap to open keynote details", comment: "Accessibility hint for activatable cell") } if cta == .viewLivestream { return NSLocalizedString("Double-tap to open livestream link", comment: "Accessibility hint for activatable cell") } if cta == .viewMap { return NSLocalizedString("Double-tap to open in map", comment: "Accessibility hint for activatable cell") } return nil } private static let dateFormatter: DateFormatter = { // Example date: "2019-05-07 11:30:00 -0700" let formatter = TimeZoneAwareDateFormatter() formatter.timeZone = TimeZone.userTimeZone() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z" return formatter }() private static let dateIntervalFormatter: DateIntervalFormatter = { let formatter = DateIntervalFormatter() formatter.timeZone = TimeZone.userTimeZone() formatter.dateStyle = .none formatter.timeStyle = .short registerForTimeZoneUpdates() return formatter }() private static func registerForTimeZoneUpdates() { _ = NotificationCenter.default.addObserver(forName: .timezoneUpdate, object: nil, queue: nil) { _ in dateIntervalFormatter.timeZone = TimeZone.userTimeZone() } } // MARK: - Moment constants static let keynote = Moment( attendeeRequired: false, cta: .viewLivestream, displayDate: "May 7th", startTime: dateFormatter.date(from: "2019-05-07 10:00:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-07 11:30:00 -0700")!, featureID: nil, featureName: "Watch Livestream", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHome-GoogleKeynote%402x.png?alt=media&token=0df80e81-5bea-4171-9016-4f1e3dcfc7f9")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-GoogleKeynote%402x.png?alt=media&token=bfd169ae-f501-4cf8-94be-462682d40fd7")!, streamURL: URL(string: "https://youtu.be/JuMbOCQu-XM"), textColor: "#ffffff", timeVisible: true, title: "Keynote" ) static let lunchDayOne = Moment( attendeeRequired: true, cta: .viewMap, displayDate: "May 7th", startTime: dateFormatter.date(from: "2019-05-07 11:30:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-07 12:45:00 -0700")!, featureID: "eats", featureName: "EATS", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FSchedule-Lunch-1%402X.png?alt=media&token=0bdab2ab-b1ac-4c70-8ffb-4f3f317f5531")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Schedule-Lunch-1%402X.png?alt=media&token=21ab538e-a791-49c5-b3d8-cc0c92b6f460")!, streamURL: nil, textColor: "#ffffff", timeVisible: true, title: "Lunch" ) static let developerKeynote = Moment( attendeeRequired: false, cta: .viewLivestream, displayDate: "May 7th", startTime: dateFormatter.date(from: "2019-05-07 12:45:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-07 14:00:00 -0700")!, featureID: nil, featureName: "Watch Livestream", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHome-DevKeynote%402x.png?alt=media&token=d11ff5ac-0bda-46cb-b730-761494207979")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-DevKeynot%402x.png?alt=media&token=069779b3-ddba-421d-86c0-090f7b3f1692")!, streamURL: URL(string: "https://youtu.be/lyRPyRKHO8M"), textColor: "#ffffff", timeVisible: true, title: "Developer keynote" ) static let sessionsDayOne = Moment( attendeeRequired: false, cta: .viewLivestream, displayDate: "May 7th", startTime: dateFormatter.date(from: "2019-05-07 14:00:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-07 18:30:00 -0700")!, featureID: nil, featureName: "Watch Livestream", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHomeIO%402x.png?alt=media&token=0bea342d-94d4-4d1f-8adf-d61f1a3e2ea3")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-HomeIO%402x.png?alt=media&token=1e98c915-2ad5-40ef-bd90-1c56ee1f390a")!, streamURL: URL(string: "https://youtu.be/e0B28zBn9JE"), textColor: "#ffffff", timeVisible: true, title: "Live show (sessions)" ) static let afterHoursDinner = Moment( attendeeRequired: false, cta: .viewMap, displayDate: "May 7th", startTime: dateFormatter.date(from: "2019-05-07 18:30:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-07 22:00:00 -0700")!, featureID: nil, featureName: "View Map", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-AfterDark-Text%402x.png?alt=media&token=f863a425-cb3b-4430-a8c6-8364d00c8363")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-AfterDark-Text%402x.png?alt=media&token=f863a425-cb3b-4430-a8c6-8364d00c8363")!, streamURL: nil, textColor: "#ffffff", timeVisible: true, title: "Live show (sessions)" ) static let dayOneWrap = Moment( attendeeRequired: false, cta: nil, displayDate: "May 7th", startTime: dateFormatter.date(from: "2019-05-07 22:00:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-08 06:00:00 -0700")!, featureID: nil, featureName: nil, imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day1%402x.png?alt=media&token=173d3868-0c25-4da2-8f25-8d814490559e")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day1-dm%402x.png?alt=media&token=abc8e4cc-463b-4685-8c4b-f1b4664f3134")!, streamURL: nil, textColor: "#ffffff", timeVisible: false, title: "Day 1: wrap" ) static let dayTwoMorning = Moment( attendeeRequired: false, cta: nil, displayDate: "May 8th", startTime: dateFormatter.date(from: "2019-05-08 06:00:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-08 08:30:00 -0700")!, featureID: nil, featureName: nil, imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FAPP-day02%402x.png?alt=media&token=cc5556c0-d125-4619-b3e4-6ca39b5bb09c")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-APP-day02%402x.png?alt=media&token=136d1308-cc70-4bc4-9320-535aa196387e")!, streamURL: nil, textColor: "#ffffff", timeVisible: true, title: "Day 2: morning" ) static let sessionsDayTwoMorning = Moment( attendeeRequired: false, cta: .viewLivestream, displayDate: "May 8th", startTime: dateFormatter.date(from: "2019-05-08 08:30:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-08 11:30:00 -0700")!, featureID: nil, featureName: "Watch Livestream", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHomeIO%402x.png?alt=media&token=0bea342d-94d4-4d1f-8adf-d61f1a3e2ea3")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-HomeIO%402x.png?alt=media&token=1e98c915-2ad5-40ef-bd90-1c56ee1f390a")!, streamURL: URL(string: "https://youtu.be/irpNzosHbPU"), textColor: "#ffffff", timeVisible: true, title: "Live show (sessions)" ) static let lunchDayTwo = Moment( attendeeRequired: true, cta: .viewMap, displayDate: "May 8th", startTime: dateFormatter.date(from: "2019-05-08 11:30:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-08 14:30:00 -0700")!, featureID: "eats", featureName: "EATS", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FSchedule-Lunch-2%402X.png?alt=media&token=8e54b7a8-f72f-4803-8d93-ddb3c78694a7")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Schedule-Lunch-2%402X.png?alt=media&token=dba29718-437f-4d38-ae5f-93fed2f7cab2")!, streamURL: nil, textColor: "#ffffff", timeVisible: true, title: "Lunch" ) static let sessionsDayTwoAfternoon = Moment( attendeeRequired: false, cta: .viewLivestream, displayDate: "May 8th", startTime: dateFormatter.date(from: "2019-05-08 14:30:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-08 19:30:00 -0700")!, featureID: nil, featureName: "Watch Livestream", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHomeIO%402x.png?alt=media&token=0bea342d-94d4-4d1f-8adf-d61f1a3e2ea3")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-HomeIO%402x.png?alt=media&token=1e98c915-2ad5-40ef-bd90-1c56ee1f390a")!, streamURL: URL(string: "https://youtu.be/irpNzosHbPU"), textColor: "#ffffff", timeVisible: true, title: "Live show (sessions)" ) static let concert = Moment( attendeeRequired: false, cta: .viewLivestream, displayDate: "May 8th", startTime: dateFormatter.date(from: "2019-05-08 19:30:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-08 22:00:00 -0700")!, featureID: nil, featureName: "Watch Livestream", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-Concert-Text-v2.png?alt=media&token=cf913585-65b7-4fb7-958c-5e333e6ee85f")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-Concert-Text-v2.png?alt=media&token=cf913585-65b7-4fb7-958c-5e333e6ee85f")!, streamURL: URL(string: "https://youtu.be/Z9WusLkJ01s"), textColor: "#ffffff", timeVisible: true, title: "Concert" ) static let dayTwoWrap = Moment( attendeeRequired: false, cta: nil, displayDate: "May 8th", startTime: dateFormatter.date(from: "2019-05-08 22:00:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-09 06:00:00 -0700")!, featureID: nil, featureName: nil, imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day2%402x.png?alt=media&token=37ac81db-b334-4c05-8448-4b1d139d711b")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day2-dm%402x.png?alt=media&token=0a40d99f-39b1-4936-8967-0319039e05cd")!, streamURL: nil, textColor: "#ffffff", timeVisible: false, title: "Day 2: wrap" ) static let dayThreeMorning = Moment( attendeeRequired: false, cta: nil, displayDate: "May 9th", startTime: dateFormatter.date(from: "2019-05-09 06:00:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-09 08:30:00 -0700")!, featureID: nil, featureName: nil, imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FAPP-day03%402x.png?alt=media&token=2a7e37e3-3138-43a2-acef-ff3ce44664a3")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-APP-day03%402x.png?alt=media&token=5527c547-ac01-40e5-ac12-f99cf5e2e110")!, streamURL: nil, textColor: "#ffffff", timeVisible: true, title: "Day 3: morning" ) static let sessionsDayThreeMorning = Moment( attendeeRequired: false, cta: .viewLivestream, displayDate: "May 9th", startTime: dateFormatter.date(from: "2019-05-09 08:30:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-09 11:30:00 -0700")!, featureID: nil, featureName: "Watch Livestream", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHomeIO%402x.png?alt=media&token=0bea342d-94d4-4d1f-8adf-d61f1a3e2ea3")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-HomeIO%402x.png?alt=media&token=1e98c915-2ad5-40ef-bd90-1c56ee1f390a")!, streamURL: URL(string: "https://youtu.be/WQklcSsYdu4"), textColor: "#ffffff", timeVisible: true, title: "Live show (sessions)" ) static let lunchDayThree = Moment( attendeeRequired: true, cta: .viewMap, displayDate: "May 9th", startTime: dateFormatter.date(from: "2019-05-09 11:30:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-09 14:30:00 -0700")!, featureID: "eats", featureName: "EATS", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FSchedule-Lunch-3%402X.png?alt=media&token=e4079280-f497-460c-bb89-51746c4d9e13")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Schedule-Lunch-3%402X.png?alt=media&token=2ac97cb7-2e4c-41fd-bd37-5594251158cc")!, streamURL: nil, textColor: "#ffffff", timeVisible: true, title: "Lunch" ) static let sessionsDayThreeAfternoon = Moment( attendeeRequired: false, cta: .viewLivestream, displayDate: "May 9th", startTime: dateFormatter.date(from: "2019-05-09 14:30:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-09 17:00:00 -0700")!, featureID: nil, featureName: "Watch Livestream", imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHomeIO%402x.png?alt=media&token=0bea342d-94d4-4d1f-8adf-d61f1a3e2ea3")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-HomeIO%402x.png?alt=media&token=1e98c915-2ad5-40ef-bd90-1c56ee1f390a")!, streamURL: URL(string: "https://youtu.be/WQklcSsYdu4"), textColor: "#ffffff", timeVisible: true, title: "Live show (sessions)" ) static let dayThreeWrap = Moment( attendeeRequired: false, cta: nil, displayDate: "May 9th", startTime: dateFormatter.date(from: "2019-05-09 17:00:00 -0700")!, endTime: dateFormatter.date(from: "2019-05-09 22:00:00 -0700")!, featureID: nil, featureName: nil, imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day3%402x.png?alt=media&token=9f7c2a81-ebe5-473b-ab05-529093a201e4")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FEnd%20of%20day3-dm%402x.png?alt=media&token=f4d4fdb6-9e13-4e96-bb0e-c6b990ceacf8")!, streamURL: nil, textColor: "#ffffff", timeVisible: false, title: "That’s a wrap…thanks!" ) static let evergreenBranding = Moment( attendeeRequired: false, cta: nil, displayDate: "May 10th", startTime: dateFormatter.date(from: "2019-05-09 22:00:00 -0700")!, endTime: dateFormatter.date(from: "2025-01-01 09:00:00 -0800")!, featureID: nil, featureName: nil, imageURL: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FHome-Evergreen2%402x.png?alt=media&token=35c71f46-818c-41c1-b58a-94be038221a2")!, imageURLDarkTheme: URL(string: "https://firebasestorage.googleapis.com/v0/b/io2019-festivus/o/images%2Fhome%2FDM-Home-Evergreen2%402x.png?alt=media&token=95022ef8-0fdb-4fb5-8f4a-0acc6ea59825")!, streamURL: nil, textColor: "#ffffff", timeVisible: false, title: "Evergreen branding" ) static let allMoments: [Moment] = [ .keynote, .lunchDayOne, .developerKeynote, .sessionsDayOne, .afterHoursDinner, .dayOneWrap, .dayTwoMorning, .sessionsDayTwoMorning, .lunchDayTwo, .sessionsDayTwoAfternoon, .concert, .dayTwoWrap, .dayThreeMorning, .sessionsDayThreeMorning, .lunchDayThree, .sessionsDayThreeAfternoon, .dayThreeWrap ] static func currentMoment(for date: Date = Date()) -> Moment? { for moment in allMoments where moment.startTime <= date && moment.endTime > date { return moment } return nil } } extension Moment: Equatable {} public func == (lhs: Moment, rhs: Moment) -> Bool { return lhs.title == rhs.title && lhs.cta == rhs.cta && lhs.startTime == rhs.startTime && lhs.endTime == rhs.endTime && lhs.imageURL == rhs.imageURL && lhs.streamURL == rhs.streamURL }
3d4afdbc4ed5c1d40197b6db76429601
44.416851
202
0.696773
false
false
false
false
naoyashiga/CatsForInstagram
refs/heads/master
Nekobu/FavoriteCollectionViewController+RPZoomTransitionAnimating.swift
mit
1
// // FavoriteCollectionViewController+RPZoomTransitionAnimating.swift // Nekobu // // Created by naoyashiga on 2015/08/23. // Copyright (c) 2015年 naoyashiga. All rights reserved. // import Foundation extension FavoriteCollectionViewController: RPZoomTransitionAnimating { func sourceImageView() -> UIImageView { //使用しない return UIImageView() } func calculatedPositionSourceImageView() -> UIImageView { if let selectedItems = collectionView?.indexPathsForSelectedItems()?.first { self.selectedIndexPath = selectedItems } let cell = collectionView?.cellForItemAtIndexPath(self.selectedIndexPath) as! FavoriteCollectionViewCell let imageView = UIImageView(image: cell.thumbNailImageView.image) imageView.contentMode = cell.thumbNailImageView.contentMode imageView.clipsToBounds = true imageView.userInteractionEnabled = false imageView.frame = cell.thumbNailImageView.convertRect(cell.thumbNailImageView.frame, toView: collectionView?.superview) imageView.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y + PageMenuConstraint.menuHeight, imageView.frame.size.width, imageView.frame.size.height) return imageView } func transitionDestinationImageViewFrame() -> CGRect { let cell = collectionView?.cellForItemAtIndexPath(selectedIndexPath) as! FavoriteCollectionViewCell let cellFrameInSuperview = cell.thumbNailImageView.convertRect(cell.thumbNailImageView.frame, toView: collectionView?.superview) let resizedCellFrameInSuperview = CGRectMake(cellFrameInSuperview.origin.x, cellFrameInSuperview.origin.y + PageMenuConstraint.menuHeight, cellFrameInSuperview.size.width, cellFrameInSuperview.size.height) return resizedCellFrameInSuperview } }
a9ffebfbe75e45c1696b9ef20fc6b560
42.976744
213
0.739683
false
false
false
false
talentsparkio/Pong
refs/heads/master
Pong/ViewController.swift
bsd-3-clause
1
// // ViewController.swift // Pong // // Created by Nick Chen on 8/19/15. // Copyright © 2015 TalentSpark. All rights reserved. // import UIKit class ViewController: UIViewController, UICollisionBehaviorDelegate { let DIAMETER = CGFloat(50.0) let PADDLE_WIDTH = CGFloat(100.0) let PADDLE_HEIGHT = CGFloat(25.0) let NUM_BRICKS = 20 var BRICK_SIZE: CGSize { let size = UIScreen.mainScreen().bounds.size.width / CGFloat(NUM_BRICKS) return CGSize(width: size, height: size) } var orangeBall: UIView! var paddle: UIView! var animator: UIDynamicAnimator! var bricks = [UIView]() override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) orangeBall = UIView(frame: CGRectMake(0.0, 0.0, DIAMETER, DIAMETER)) orangeBall.center = CGPointMake(UIScreen.mainScreen().bounds.size.width / 2, 300) orangeBall.backgroundColor = UIColor.orangeColor() orangeBall.layer.cornerRadius = 25.0; view.addSubview(orangeBall) paddle = UIView(frame:CGRectMake(0.0, 0.0, PADDLE_WIDTH, PADDLE_HEIGHT)) paddle.center = CGPointMake(UIScreen.mainScreen().bounds.size.width / 2, UIScreen.mainScreen().bounds.size.height - PADDLE_HEIGHT / 2) paddle.backgroundColor = UIColor.grayColor() view.addSubview(paddle) for var i = 0; i < NUM_BRICKS; i++ { var frame = CGRect(origin: CGPointZero, size: BRICK_SIZE) frame.origin.y = 200 frame.origin.x = CGFloat(i) * BRICK_SIZE.width let dropView = UIView(frame: frame) dropView.backgroundColor = UIColor.random bricks.append(dropView) view.addSubview(dropView) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.initBehaviors() } @IBAction func movePaddle(sender: UIPanGestureRecognizer) { let translationPoint = sender.locationInView(self.view) paddle.center = CGPointMake(translationPoint.x, paddle.center.y) animator.updateItemUsingCurrentState(paddle) } func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item1: UIDynamicItem, withItem item2: UIDynamicItem, atPoint p: CGPoint) { // Collision between ball and paddle if(item1 === orangeBall && item2 === paddle) { let pushBehavior = UIPushBehavior(items: [orangeBall], mode: .Instantaneous) pushBehavior.pushDirection = CGVectorMake(0.0, -1.0) pushBehavior.magnitude = 0.75 // Need to remove the behavior without causing circular reference pushBehavior.action = { [unowned pushBehavior] in if(!pushBehavior.active) { pushBehavior.dynamicAnimator?.removeBehavior(pushBehavior) } } animator.addBehavior(pushBehavior) } } func initBehaviors() { animator = UIDynamicAnimator(referenceView: self.view) // Add gravity for ball let gravityBehavior = UIGravityBehavior(items: [orangeBall]) animator.addBehavior(gravityBehavior) // Add collision let collisionBoundsBehavior = UICollisionBehavior(items: [orangeBall, paddle]) collisionBoundsBehavior.translatesReferenceBoundsIntoBoundary = true animator.addBehavior(collisionBoundsBehavior) // Add physical properties for ball let elasticityBehavior = UIDynamicItemBehavior(items: [orangeBall]) elasticityBehavior.elasticity = 1.0 animator.addBehavior(elasticityBehavior) // Add physical properties for bricks let brickBehavior = UIDynamicItemBehavior(items: bricks) brickBehavior.allowsRotation = false animator.addBehavior(brickBehavior) // Add physical properties for paddle let paddleBehavior = UIDynamicItemBehavior(items: [paddle]) paddleBehavior.density = 100.0 paddleBehavior.allowsRotation = false animator.addBehavior(paddleBehavior) // Add collision between ball and bricks (individually so there is no avalanche effect) for brick in bricks { let ballAndBrick: [UIDynamicItem] = [brick, orangeBall] let collisionBallAndBricksBehavior = UICollisionBehavior(items: ballAndBrick) animator.addBehavior(collisionBallAndBricksBehavior) } // Add collision between ball and paddle let collisionBallAndPaddleBehavior = UICollisionBehavior(items: [orangeBall, paddle]) collisionBallAndPaddleBehavior.collisionDelegate = self animator.addBehavior(collisionBallAndPaddleBehavior) } } private extension UIColor { class var random: UIColor { switch arc4random() % 5 { case 0: return UIColor.greenColor() case 1: return UIColor.blueColor() case 2: return UIColor.orangeColor() case 3: return UIColor.redColor() case 4: return UIColor.purpleColor() default: return UIColor.blackColor() } } }
6028ce219c99a885bb1c7467322746f1
36.230769
152
0.647446
false
false
false
false
objecthub/swift-lispkit
refs/heads/master
Sources/LispKit/Runtime/Features.swift
apache-2.0
1
// // Feature.swift // LispKit // // Created by Matthias Zenger on 15/10/2017. // Copyright © 2017 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation public enum Feature: String { case lispkit = "lispkit" case r7rs = "r7rs" case ratios = "ratios" case complex = "complex" case syntaxRules = "syntax-rules" case littleEndian = "little-endian" case bigEndian = "big-endian" case dynamicLoading = "dynamic-loading" case modules = "modules" case threads = "threads" case bit32 = "32bit" case bit64 = "64bit" case macos = "macos" case macosx = "macosx" case ios = "ios" case linux = "linux" case i386 = "i386" case x8664 = "x86-64" case arm64 = "arm64" case arm = "arm" public static let supported: Set<String> = { var set = Set<String>() set.insert(Feature.lispkit.rawValue) set.insert(Feature.r7rs.rawValue) set.insert(Feature.ratios.rawValue) set.insert(Feature.complex.rawValue) set.insert(Feature.syntaxRules.rawValue) set.insert(Feature.dynamicLoading.rawValue) set.insert(Feature.modules.rawValue) set.insert(Feature.threads.rawValue) set.insert(CFByteOrderGetCurrent() == 1 ? Feature.littleEndian.rawValue : Feature.bigEndian.rawValue) #if arch(i386) set.insert(Feature.i386.rawValue) set.insert(Feature.bit32.rawValue) #elseif arch(x86_64) set.insert(Feature.x8664.rawValue) set.insert(Feature.bit64.rawValue) #elseif arch(arm) set.insert(Feature.arm.rawValue) set.insert(Feature.bit32.rawValue) #elseif arch(arm64) set.insert(Feature.arm64.rawValue) set.insert(Feature.bit64.rawValue) #endif #if os(macOS) set.insert(Feature.macos.rawValue) set.insert(Feature.macosx.rawValue) #elseif os(iOS) set.insert(Feature.ios.rawValue) #elseif os(Linux) set.insert(Feature.linux.rawValue) #endif return set }() }
35752fb65987e1b04142e02a5d679e22
30.575
76
0.680918
false
false
false
false