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
hachinobu/CleanQiitaClient
refs/heads/master
DomainLayer/Translator/ListItemModelTranslator.swift
mit
1
// // ListItemModelTranslator.swift // CleanQiitaClient // // Created by Takahiro Nishinobu on 2016/09/23. // Copyright © 2016年 hachinobu. All rights reserved. // import Foundation import DataLayer struct ListItemModelsTranslator: Translator { func translate(_ entities: [ItemEntity]) -> [ListItemModel] { return entities.map { ListItemModelTranslator().translate($0) } } } struct ListItemModelTranslator: Translator { func translate(_ entity: ItemEntity) -> ListItemModel { let id = entity.id ?? "" let userName = entity.user?.id ?? "" let title = entity.title ?? "" let tagList = entity.tagList?.flatMap { $0.name } ?? [] let profileImageURL = entity.user?.profileImageUrl ?? "" return ListItemModel(id: id, userName: userName, title: title, tagList: tagList, profileImageURL: profileImageURL) } }
576f61c3be581acc87e01fdb9993f0bb
26.235294
122
0.639309
false
false
false
false
nodes-ios/nstack-translations-generator
refs/heads/master
LocalizationsGenerator/Classes/Parser/Parser.swift
mit
1
// // Parser.swift // nstack-localizations-generator // // Created by Dominik Hádl on 14/02/16. // Copyright © 2016 Nodes. All rights reserved. // import Foundation struct ParserOutput { var JSON: [String: AnyObject] var mainKeys: [String] var language: [String: AnyObject] var isFlat: Bool } struct Parser { static func parseResponseData(_ data: Data) throws -> ParserOutput { let object = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let dictionary = object as? [String: AnyObject] else { throw NSError(domain: Constants.ErrorDomain.tGenerator.rawValue, code: ErrorCode.parserError.rawValue, userInfo: [NSLocalizedDescriptionKey : "The data isn't in the correct format. Localizations JSON file should have a dictionary as its root object."]) } var content: [String: AnyObject]? = dictionary content = content?["data"] as? [String : AnyObject] ?? content if let t = content?["Translation"] as? [String : AnyObject] { content = t } else if let t = content?["translations"] as? [String : AnyObject] { content = t } guard let langsDictionary = content, let first = langsDictionary.first else { throw NSError(domain: Constants.ErrorDomain.tGenerator.rawValue, code: ErrorCode.parserError.rawValue, userInfo: [NSLocalizedDescriptionKey : "Parsed JSON didn't contain localization data."]) } // Check if key is either "en" or "en-UK" let isPossibleLanguageKey = first.key.count == 2 || (first.key.count == 5 && first.key.contains("-")) let testKey = first.key[first.key.startIndex..<first.key.index(first.key.startIndex, offsetBy: 2)] // substring 0..2 let isWrappedInLanguages = isPossibleLanguageKey && Locale.isoLanguageCodes.contains(String(testKey)) var language: [String: AnyObject] if isWrappedInLanguages, let val = first.value as? [String: AnyObject] { // the nested lang is value language = val } else { // the root obj is the translations language = langsDictionary } // Fix for default if let object = language["default"] { language.removeValue(forKey: "default") language["defaultSection"] = object } return ParserOutput(JSON: dictionary, mainKeys: language.map({ return $0.0 }).sorted(by: {$0 < $1}), language: language, isFlat: language is [String: String]) } }
238add0ec82a062dd5ecde860acf83c6
40.5
155
0.610442
false
false
false
false
BennyKJohnson/OpenCloudKit
refs/heads/master
Sources/CKModifyRecordsURLRequest.swift
mit
1
// // CKModifyRecordsURLRequest.swift // OpenCloudKit // // Created by Ben Johnson on 27/07/2016. // // import Foundation class CKModifyRecordsURLRequest: CKURLRequest { var recordsToSave: [CKRecord]? var recordIDsToDelete: [CKRecordID]? var recordsByRecordIDs: [CKRecordID: CKRecord] = [:] var atomic: Bool = true // var sendAllFields: Bool var savePolicy: CKRecordSavePolicy init(recordsToSave: [CKRecord]?, recordIDsToDelete: [CKRecordID]?, isAtomic: Bool, database: CKDatabase, savePolicy: CKRecordSavePolicy, zoneID: CKRecordZoneID?) { self.recordsToSave = recordsToSave self.recordIDsToDelete = recordIDsToDelete self.atomic = isAtomic self.savePolicy = savePolicy super.init() self.databaseScope = database.scope self.path = "modify" self.operationType = CKOperationRequestType.records // Setup Body Properties var parameters: [String: Any] = [:] if database.scope == .public { parameters["atomic"] = NSNumber(value: false) } else { parameters["atomic"] = NSNumber(value: isAtomic) } #if os(Linux) parameters["operations"] = operationsDictionary().bridge() #else parameters["operations"] = operationsDictionary() as NSArray #endif if let zoneID = zoneID { parameters["zoneID"] = zoneID.dictionary.bridge() } requestProperties = parameters } func operationsDictionary() -> [[String: Any]] { var operationsDictionaryArray: [[String: Any]] = [] if let recordIDsToDelete = recordIDsToDelete { let deleteOperations = recordIDsToDelete.map({ (recordID) -> [String: Any] in let operationDictionary: [String: Any] = [ "operationType": "forceDelete".bridge(), "record":(["recordName":recordID.recordName.bridge()] as [String: Any]).bridge() as Any ] return operationDictionary }) operationsDictionaryArray.append(contentsOf: deleteOperations) } if let recordsToSave = recordsToSave { let saveOperations = recordsToSave.map({ (record) -> [String: Any] in let operationType: String let fieldsDictionary: [String: Any] //record.dictionary var recordDictionary: [String: Any] = ["recordType": record.recordType.bridge(), "recordName": record.recordID.recordName.bridge()] if let recordChangeTag = record.recordChangeTag { if savePolicy == .IfServerRecordUnchanged { operationType = "update" } else { operationType = "forceUpdate" } // Set Operation Type to Replace if savePolicy == .AllKeys { fieldsDictionary = record.fieldsDictionary(forKeys: record.allKeys()) } else { fieldsDictionary = record.fieldsDictionary(forKeys: record.changedKeys()) } recordDictionary["recordChangeTag"] = recordChangeTag.bridge() } else { // Create new record fieldsDictionary = record.fieldsDictionary(forKeys: record.allKeys()) operationType = "create" } recordDictionary["fields"] = fieldsDictionary.bridge() as NSDictionary if let parent = record.parent { recordDictionary["createShortGUID"] = NSNumber(value: 1) recordDictionary["parent"] = ["recordName": parent.recordID.recordName.bridge()].bridge() } let operationDictionary: [String: Any] = ["operationType": operationType.bridge(), "record": recordDictionary.bridge() as NSDictionary] return operationDictionary }) operationsDictionaryArray.append(contentsOf: saveOperations) } return operationsDictionaryArray } }
18a73b94023f42bda2ce6b2f6b03575f
32.766423
167
0.525076
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Client/Frontend/Home/TopSites/DataManagement/TopSitesDataAdaptor.swift
mpl-2.0
1
// 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 protocol TopSitesManagerDelegate: AnyObject { func didLoadNewData() } /// Data adaptor to fetch the top sites data asynchronously /// The data gets updated from notifications on specific user actions protocol TopSitesDataAdaptor { /// The preferred number of rows by the user, this can be from 1 to 4 /// Note that this isn't necessarily the number of rows that will appear since empty rows won't show. /// In other words, the number of rows shown depends on the actual data and the user preference. var numberOfRows: Int { get } /// Get top sites data, already calculated and ready to be shown to the user func getTopSitesData() -> [TopSite] /// Calculate top site data /// This calculation is dependent on the number of tiles per row that is shown in the user interface. /// Top sites are composed of pinned sites, history, Contiles and Google top site. /// Google top site is always first, then comes the contiles, pinned sites and history top sites. /// We only add Google top site or Contiles if number of pins doesn't exceeds the available number shown of tiles. /// - Parameter numberOfTilesPerRow: The number of tiles per row shown to the user func recalculateTopSiteData(for numberOfTilesPerRow: Int) /// Get favicon for site func getFaviconImage(forSite site: Site) -> UIImage? } class TopSitesDataAdaptorImplementation: TopSitesDataAdaptor, FeatureFlaggable, HasNimbusSponsoredTiles { private let profile: Profile private var topSites: [TopSite] = [] private let dataQueue = DispatchQueue(label: "com.moz.topSitesManager.queue", qos: .userInteractive) // Raw data to build top sites with private var historySites: [Site] = [] private var contiles: [Contile] = [] var notificationCenter: NotificationProtocol weak var delegate: TopSitesManagerDelegate? private let topSiteHistoryManager: TopSiteHistoryManager private let googleTopSiteManager: GoogleTopSiteManager private let contileProvider: ContileProviderInterface private let dispatchGroup: DispatchGroupInterface private var siteImageHelper: SiteImageHelperProtocol // Pre-loading the data with a default number of tiles so we always show section when needed // If this isn't done, then no data will be found from the view model and section won't show // This gets ajusted once we actually know in which UI we're showing top sites. private static let defaultTopSitesRowCount = 8 private var faviconImages = [String: UIImage]() { didSet { delegate?.didLoadNewData() } } init(profile: Profile, topSiteHistoryManager: TopSiteHistoryManager, googleTopSiteManager: GoogleTopSiteManager, siteImageHelper: SiteImageHelperProtocol, contileProvider: ContileProviderInterface = ContileProvider(), notificationCenter: NotificationProtocol = NotificationCenter.default, dispatchGroup: DispatchGroupInterface = DispatchGroup() ) { self.profile = profile self.topSiteHistoryManager = topSiteHistoryManager self.googleTopSiteManager = googleTopSiteManager self.siteImageHelper = siteImageHelper self.contileProvider = contileProvider self.notificationCenter = notificationCenter self.dispatchGroup = dispatchGroup topSiteHistoryManager.delegate = self setupNotifications(forObserver: self, observing: [.FirefoxAccountChanged, .PrivateDataClearedHistory, .ProfileDidFinishSyncing, .TopSitesUpdated]) loadTopSitesData() } deinit { notificationCenter.removeObserver(self) } func getTopSitesData() -> [TopSite] { return topSites } func recalculateTopSiteData(for numberOfTilesPerRow: Int) { var sites = historySites let availableSpaceCount = getAvailableSpaceCount(numberOfTilesPerRow: numberOfTilesPerRow) let shouldAddGoogle = shouldAddGoogle(availableSpaceCount: availableSpaceCount) // Add Sponsored tile if shouldAddSponsoredTiles { addSponsoredTiles(sites: &sites, shouldAddGoogle: shouldAddGoogle, availableSpaceCount: availableSpaceCount) } // Add Google Tile if shouldAddGoogle { addGoogleTopSite(sites: &sites) } sites.removeDuplicates() topSites = sites.map { TopSite(site: $0) } } // MARK: - Data loading // Loads the data source of top sites. Internal for convenience of testing func loadTopSitesData(dataLoadingCompletion: (() -> Void)? = nil) { loadContiles() loadTopSites() dispatchGroup.notify(queue: dataQueue) { [weak self] in self?.recalculateTopSiteData(for: TopSitesDataAdaptorImplementation.defaultTopSitesRowCount) self?.delegate?.didLoadNewData() dataLoadingCompletion?() } } func getFaviconImage(forSite site: Site) -> UIImage? { if let faviconImage = faviconImages[site.url] { return faviconImage } siteImageHelper.fetchImageFor(site: site, imageType: .favicon, shouldFallback: false) { image in self.faviconImages[site.url] = image } return nil } private func loadContiles() { guard shouldLoadSponsoredTiles else { return } dispatchGroup.enter() contileProvider.fetchContiles { [weak self] result in if case .success(let contiles) = result { self?.contiles = contiles } else { self?.contiles = [] } self?.dispatchGroup.leave() } } private func loadTopSites() { dispatchGroup.enter() topSiteHistoryManager.getTopSites { [weak self] sites in if let sites = sites { self?.historySites = sites } self?.dispatchGroup.leave() } } // MARK: - Tiles placement calculation /// Get available space count for the sponsored tiles and Google tiles /// - Parameter numberOfTilesPerRow: Comes from top sites view model and accounts for different layout (landscape, portrait, iPhone, iPad, etc). /// - Returns: The available space count for the rest of the calculation private func getAvailableSpaceCount(numberOfTilesPerRow: Int) -> Int { let pinnedSiteCount = countPinnedSites(sites: historySites) let totalNumberOfShownTiles = numberOfTilesPerRow * numberOfRows return totalNumberOfShownTiles - pinnedSiteCount } // The number of rows the user wants. // If there is no preference, the default is used. var numberOfRows: Int { let preferredNumberOfRows = profile.prefs.intForKey(PrefsKeys.NumberOfTopSiteRows) let defaultNumberOfRows = TopSitesRowCountSettingsController.defaultNumberOfRows return Int(preferredNumberOfRows ?? defaultNumberOfRows) } func addSponsoredTiles(sites: inout [Site], shouldAddGoogle: Bool, availableSpaceCount: Int) { let sponsoredTileSpaces = getSponsoredNumberTiles(shouldAddGoogle: shouldAddGoogle, availableSpaceCount: availableSpaceCount) if sponsoredTileSpaces > 0 { let maxNumberOfTiles = nimbusSponoredTiles.getMaxNumberOfTiles() sites.addSponsoredTiles(sponsoredTileSpaces: sponsoredTileSpaces, contiles: contiles, maxNumberOfSponsoredTile: maxNumberOfTiles) } } private func countPinnedSites(sites: [Site]) -> Int { var pinnedSites = 0 sites.forEach { if $0 as? PinnedSite != nil { pinnedSites += 1 } } return pinnedSites } // MARK: - Google Tile private func shouldAddGoogle(availableSpaceCount: Int) -> Bool { googleTopSiteManager.shouldAddGoogleTopSite(hasSpace: availableSpaceCount > 0) } private func addGoogleTopSite(sites: inout [Site]) { googleTopSiteManager.addGoogleTopSite(sites: &sites) } // MARK: - Sponsored tiles (Contiles) private var shouldLoadSponsoredTiles: Bool { return featureFlags.isFeatureEnabled(.sponsoredTiles, checking: .buildAndUser) } private var shouldAddSponsoredTiles: Bool { return !contiles.isEmpty && shouldLoadSponsoredTiles } /// Google tile has precedence over Sponsored Tiles, if Google tile is present private func getSponsoredNumberTiles(shouldAddGoogle: Bool, availableSpaceCount: Int) -> Int { let googleAdjustedSpaceCount = availableSpaceCount - GoogleTopSiteManager.Constants.reservedSpaceCount return shouldAddGoogle ? googleAdjustedSpaceCount : availableSpaceCount } } // MARK: Site Array extension private extension Array where Element == Site { /// Add sponsored tiles to the top sites. /// - Parameters: /// - sponsoredTileSpaces: The number of spaces available for sponsored tiles /// - contiles: An array of Contiles a type of tiles belonging in the Shortcuts section on the Firefox home page. /// - maxNumberOfSponsoredTile: maximum number of sponsored tiles /// - sites: The top sites to add the sponsored tile to mutating func addSponsoredTiles(sponsoredTileSpaces: Int, contiles: [Contile], maxNumberOfSponsoredTile: Int) { guard maxNumberOfSponsoredTile > 0 else { return } var siteAddedCount = 0 for (index, _) in contiles.enumerated() { guard siteAddedCount < sponsoredTileSpaces, let contile = contiles[safe: index] else { return } let site = SponsoredTile(contile: contile) // Show the next sponsored site if site is already present in the pinned sites guard !siteIsAlreadyPresent(site: site) else { continue } insert(site, at: siteAddedCount) siteAddedCount += 1 // Do not add more sponsored tile if we reach the maximum guard siteAddedCount < maxNumberOfSponsoredTile else { break } } } // Keeping the order of the sites, we remove duplicate tiles. // Ex: If a sponsored tile is present then it has precedence over the history sites. // Ex: A default site is present but user has recent history site of the same site. That recent history tile won't be added. mutating func removeDuplicates() { var alreadyThere = Set<Site>() let uniqueSites = compactMap { (site) -> Site? in // Do not remove sponsored tiles or pinned tiles duplicates guard (site as? SponsoredTile) == nil && (site as? PinnedSite) == nil else { alreadyThere.insert(site) return site } let siteDomain = site.url.asURL?.shortDomain let shouldAddSite = !alreadyThere.contains(where: { $0.url.asURL?.shortDomain == siteDomain }) // If shouldAddSite or site domain was not found, then insert the site guard shouldAddSite || siteDomain == nil else { return nil } alreadyThere.insert(site) return site } self = uniqueSites } // We don't add a sponsored tile if that domain site is already pinned by the user. private func siteIsAlreadyPresent(site: Site) -> Bool { let siteDomain = site.url.asURL?.shortDomain return !filter { ($0.url.asURL?.shortDomain == siteDomain) && (($0 as? PinnedSite) != nil) }.isEmpty } } // MARK: - DataObserverDelegate extension TopSitesDataAdaptorImplementation: DataObserverDelegate { func didInvalidateDataSource(forceRefresh forced: Bool) { guard forced else { return } loadTopSitesData() } } // MARK: - Notifiable protocol extension TopSitesDataAdaptorImplementation: Notifiable, Loggable { func handleNotifications(_ notification: Notification) { switch notification.name { case .ProfileDidFinishSyncing, .PrivateDataClearedHistory, .FirefoxAccountChanged, .TopSitesUpdated: topSiteHistoryManager.refreshIfNeeded(forceRefresh: true) default: browserLog.warning("Received unexpected notification \(notification.name)") } } }
8709146c48907d72e2950b84ca0fdc6e
38.885093
148
0.664486
false
false
false
false
mpangburn/RayTracer
refs/heads/master
RayTracer/Views/PointTableViewCell.swift
mit
1
// // PointTableViewCell.swift // RayTracer // // Created by Michael Pangburn on 7/8/17. // Copyright © 2017 Michael Pangburn. All rights reserved. // import UIKit protocol PointTableViewCellDelegate: class { func pointTableViewCellPointDidChange(_ cell: PointTableViewCell) } final class PointTableViewCell: ExpandableTableViewCell { weak var delegate: PointTableViewCellDelegate? var point: Point { get { return Point(x: Double(xSlider.value).roundedTo(decimalPlaces: 1), y: Double(ySlider.value).roundedTo(decimalPlaces: 1), z: Double(zSlider.value).roundedTo(decimalPlaces: 1)) } set { xSlider.value = Float(newValue.x) ySlider.value = Float(newValue.y) zSlider.value = Float(newValue.z) updateCoordinatesLabel() } } @IBOutlet weak var titleLabel: UILabel! { didSet { titleLabel.text = NSLocalizedString("Position", comment: "The title text for the position editing cell") } } @IBOutlet weak var coordinatesLabel: UILabel! @IBOutlet weak var xLabel: UILabel! { didSet { xLabel.text = NSLocalizedString("x", comment: "The text for the point's x coordinate slider label") } } @IBOutlet weak var yLabel: UILabel! { didSet { yLabel.text = NSLocalizedString("y", comment: "The text for the point's y coordinate slider label") } } @IBOutlet weak var zLabel: UILabel! { didSet { zLabel.text = NSLocalizedString("z", comment: "The text for the point's z coordinate slider label") } } @IBOutlet weak var xSlider: UISlider! @IBOutlet weak var ySlider: UISlider! @IBOutlet weak var zSlider: UISlider! @IBOutlet weak var slidersWrapperView: UIView! { didSet { expandableView = slidersWrapperView } } @IBOutlet weak var slidersWrapperViewHeightConstraint: NSLayoutConstraint! { didSet { expandableViewHeightConstraint = slidersWrapperViewHeightConstraint } } private func updateCoordinatesLabel() { let point = self.point coordinatesLabel.text = "(\(point.x), \(point.y), \(point.z))" } @IBAction func sliderValueChanged(_ sender: UISlider) { updateCoordinatesLabel() delegate?.pointTableViewCellPointDidChange(self) } }
6bc6024623cde08160120f324ed30208
27.45977
116
0.627625
false
false
false
false
peferron/algo
refs/heads/master
EPI/Graphs/Search a maze/swift/test.swift
mit
1
import Darwin func == (lhs: [Coord], rhs: [Coord]) -> Bool { guard lhs.count == rhs.count else { return false } for (i, array) in lhs.enumerated() { guard array == rhs[i] else { return false } } return true } let tests: [(maze: [[Int]], subTests: [(start: Coord, end: Coord, path: [Coord]?)])] = [ ( maze: [ [0], ], subTests: [ ( start: (0, 0), end: (0, 0), path: [ (0, 0), ] ), ] ), ( maze: [ [0, 1], [0, 0], ], subTests: [ ( start: (0, 0), end: (1, 0), path: [ (0, 0), (1, 0), ] ), ( start: (1, 0), end: (1, 1), path: [ (1, 0), (1, 1), ] ), ( start: (0, 0), end: (1, 1), path: [ (0, 0), (1, 0), (1, 1), ] ), ( start: (0, 0), end: (0, 1), path: nil ), ] ), ( maze: [ [0, 0, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1], ], subTests: [ ( start: (1, 1), end: (2, 0), path: [ (1, 1), (0, 1), (0, 2), (0, 3), (1, 3), (2, 3), (2, 2), (3, 2), (3, 1), (3, 0), (2, 0), ] ), ] ), ] for test in tests { for subTest in test.subTests { var maze: [[Status]] = test.maze.map { row in row.map { status in status == 1 ? .Blocked : .Empty } } let actual = path(from: subTest.start, to: subTest.end, in: &maze) guard actual == nil && subTest.path == nil || actual != nil && subTest.path != nil && actual! == subTest.path! else { print("For maze \(test.maze), " + "expected path from \(subTest.start) to \(subTest.end) to be \(String(describing: subTest.path)), " + "but was \(String(describing: actual))") exit(1) } } }
b90bc11af9b4528e0a6c6b571752f2c2
22.643478
117
0.265539
false
true
false
false
mercadopago/sdk-ios
refs/heads/master
MercadoPagoSDK/MercadoPagoSDK/TransactionDetails.swift
mit
1
// // TransactionDetails.swift // MercadoPagoSDK // // Created by Matias Gualino on 6/3/15. // Copyright (c) 2015 com.mercadopago. All rights reserved. // import Foundation public class TransactionDetails : NSObject { public var couponAmount : Double = 0 public var externalResourceUrl : String! public var financialInstitution : String! public var installmentAmount : Double = 0 public var netReceivedAmount : Double = 0 public var overpaidAmount : Double = 0 public var totalPaidAmount : Double = 0 public class func fromJSON(json : NSDictionary) -> TransactionDetails { let transactionDetails : TransactionDetails = TransactionDetails() if json["coupon_amount"] != nil && !(json["coupon_amount"]! is NSNull) { transactionDetails.couponAmount = JSON(json["coupon_amount"]!).asDouble! } transactionDetails.externalResourceUrl = JSON(json["external_resource_url"]!).asString transactionDetails.financialInstitution = JSON(json["financial_institution"]!).asString if json["installment_amount"] != nil && !(json["installment_amount"]! is NSNull) { transactionDetails.installmentAmount = JSON(json["installment_amount"]!).asDouble! } if json["net_received_amount"] != nil && !(json["net_received_amount"]! is NSNull) { transactionDetails.netReceivedAmount = JSON(json["net_received_amount"]!).asDouble! } if json["overpaid_amount"] != nil && !(json["overpaid_amount"]! is NSNull) { transactionDetails.overpaidAmount = JSON(json["overpaid_amount"]!).asDouble! } if json["total_paid_amount"] != nil && !(json["total_paid_amount"]! is NSNull) { transactionDetails.totalPaidAmount = JSON(json["total_paid_amount"]!).asDouble! } return transactionDetails } }
49479d762e7318a74cda107f34d28e94
42.560976
95
0.698039
false
false
false
false
ferdinandurban/HUDini
refs/heads/master
HUDini/HUDiniWindow.swift
mit
1
// // HUDiniWindow.swift // HUDini // // Created by Ferdinand Urban on 15/10/15. // Copyright © 2015 Ferdinand Urban. All rights reserved. // import UIKit internal class HUDiniWindow: UIWindow { internal let frameView: HUDiniFrameView private var willHide = false private let backgroundView: UIView = { let view = UIView() view.backgroundColor = UIColor(white:0.0, alpha:0.25) view.alpha = 0.0; return view; }() internal init(frameView: HUDiniFrameView = HUDiniFrameView()) { self.frameView = frameView super.init(frame: UIApplication.sharedApplication().delegate!.window!!.bounds) windowInit() } required init?(coder aDecoder: NSCoder) { frameView = HUDiniFrameView() super.init(coder: aDecoder) windowInit() } private func windowInit() { rootViewController = HUDiniWindowRootViewController() windowLevel = UIWindowLevelNormal + 1.0 backgroundColor = UIColor.clearColor() addSubview(backgroundView) addSubview(frameView) } internal override func layoutSubviews() { super.layoutSubviews() frameView.center = center backgroundView.frame = bounds } internal func showFrameView() { layer.removeAllAnimations() makeKeyAndVisible() frameView.center = center frameView.alpha = 1.0 hidden = false } internal func hideFrameView(animated anim: Bool) { let completion: (finished: Bool) -> (Void) = { finished in if finished { self.hidden = true self.resignKeyWindow() } self.willHide = false } if hidden { return } willHide = true if anim { UIView.animateWithDuration(0.8, animations: { self.frameView.alpha = 0.0 }, completion: completion) } else { completion(finished: true) } } // MARK: - Background internal func showBackground(animated anim: Bool) { if anim { UIView.animateWithDuration(0.175) { self.backgroundView.alpha = 1.0 } } else { backgroundView.alpha = 1.0; } } internal func hideBackground(animated anim: Bool) { if anim { UIView.animateWithDuration(0.65) { self.backgroundView.alpha = 0.0 } } else { backgroundView.alpha = 0.0; } } }
ed11b68efd17dc66ddf52d0bc3e5de94
24.941176
111
0.555933
false
false
false
false
CooperCorona/Voronoi
refs/heads/master
Sources/Voronoi/VoronoiEdge.swift
mit
1
// // VoronoiEdge.swift // Voronoi2 // // Created by Cooper Knaak on 5/29/16. // Copyright © 2016 Cooper Knaak. All rights reserved. // import Foundation import CoronaMath /** Represents an edge formed by the intersection of the parabolas. */ internal class VoronoiEdge: CustomStringConvertible { ///The initial point at which the two parabolas intersected. internal let startPoint:Point ///The final point at which the two parabolas intersected (this is either ///set during a CircleEvent or extrapolated to the edge of the VoronoiDiagram ///at the end of the sweep) internal var endPoint:Point = Point.zero { didSet { self.hasSetEnd = true } } ///The focus of the left parabola. internal let left:Point ///The focus of the right parabola. internal let right:Point ///The left parabola that forms this edge via intersection with another parabola. internal weak var leftParabola:VoronoiParabola? = nil { didSet { self.leftParabola?.rightEdge = self } } ///The right parabola that forms this edge via intersection with another parabola. internal weak var rightParabola:VoronoiParabola? = nil { didSet { self.rightParabola?.leftEdge = self } } ///The left parabola's underlying cell. internal unowned let leftCell:VoronoiCell ///The right parabola's underlying cell. internal unowned let rightCell:VoronoiCell ///The slope of the line that this edge lies on. internal var slope:Double { //Negative recipricol to get the actual slope perpendicular to the focii. return (self.right.x - self.left.x) / (self.left.y - self.right.y) } ///The y-intercept of the line that this edge lies on. internal var yIntercept:Double { return self.startPoint.y - self.slope * self.startPoint.x } ///The vector pointing in the direction of the line this edge lies on. internal var directionVector:Point { //Direction is perpendicular to the two focii corresponding to the left/right points. return Point(x: self.right.y - self.left.y, y: self.left.x - self.right.x) } ///When the VoronoiDiagram sets the end point, this is set to true. internal var hasSetEnd = false internal var description: String { if self.hasSetEnd { return "VoronoiEdge(\(self.startPoint) -> \(self.endPoint))" } else { return "VoronoiEdge(\(self.startPoint) Dir(\(self.directionVector)))" } } ///Initializes a VoronoiEdge with a start point and the cells ///(which contain the focii/parabola)on either side. internal init(start:Point, left:VoronoiCell, right:VoronoiCell) { self.startPoint = start self.leftCell = left self.rightCell = right self.left = left.voronoiPoint self.right = right.voronoiPoint left.cellEdges.append(self) right.cellEdges.append(self) } /** Calculates the point at which this edge connects with the bounding rectangle formed by (0, 0, boundaries.width, boundaries.height). Some edges overshoot the boundaries, so this method is used to clamp them to the edge. - parameter boundaries: The size of the VoronoiDiagram. - returns: The point at which this edge intersects with the boundaries, or nil if it does not. */ internal func intersectionWith(_ boundaries:Size) -> [Point] { let startPoint = self.startPoint let endPoint = self.endPoint let vector = (endPoint - startPoint) var intersections:[Point] = [] //Horizontal boundaries if (startPoint.x <= 0.0) == (0.0 <= endPoint.x) { //Edge crosses line x = 0 let t = -startPoint.x / vector.x let y = vector.y * t + startPoint.y if 0.0 <= y && y <= boundaries.height { //Point crosses the edge that actually lies on the boundaries intersections.append(Point(x: 0.0, y: y)) } } if (startPoint.x <= boundaries.width) == (boundaries.width <= endPoint.x) { //Edge crosses line x = boundaries.width let t = (boundaries.width - startPoint.x) / vector.x let y = vector.y * t + startPoint.y if 0.0 <= y && y <= boundaries.height { //Point crosses the edge that actually lies on the boundaries intersections.append(Point(x: boundaries.width, y: y)) } } //Vertical boundaries if (startPoint.y <= 0.0) == (0.0 <= endPoint.y) { //Edge crosses line x = 0 let t = -startPoint.y / vector.y let x = vector.x * t + startPoint.x if 0.0 <= x && x <= boundaries.width { //Point crosses the edge that actually lies on the boundaries intersections.append(Point(x: x, y: 0.0)) } } if (startPoint.y <= boundaries.height) == (boundaries.height <= endPoint.y) { //Edge crosses line y = boundaries.height let t = (boundaries.height - startPoint.y) / vector.y let x = vector.x * t + startPoint.x if 0.0 <= x && x <= boundaries.width { //Point crosses the edge that actually lies on the boundaries intersections.append(Point(x: x, y: boundaries.height)) } } return intersections } }
5a91ab2d7d7b787a939a3c92c2352a47
37.715278
99
0.608969
false
false
false
false
automationWisdri/WISData.JunZheng
refs/heads/master
WISData.JunZheng/Controller/Furnace/FurnaceViewController.swift
mit
1
// // FurnaceViewController.swift // WISData.JunZheng // // Created by Allen on 16/8/24. // Copyright © 2016 Wisdri. All rights reserved. // import UIKit import SwiftyJSON import SVProgressHUD #if !RX_NO_MODULE import RxSwift import RxCocoa #endif //public let DataTableColumnWidth: CGFloat = 70.0 class FurnaceViewController: ViewController { @IBOutlet weak var dataView: UIScrollView! private var firstColumnView: UIView! private var scrollView: UIScrollView! private var firstColumnTableView: DataTableView! private var columnTableView = [DataTableView]() private var noDataView: NoDataView! private var hasRefreshedData = false private var rowCount: Int = 8 private var tableContentJSON: [JSON] = [] private var tableTitleJSON = JSON.null // private static let firstColumnViewWidth: CGFloat = 95 class func instantiateFromStoryboard() -> FurnaceViewController { let storyboard = UIStoryboard(name: "Furnace", bundle: nil) return storyboard.instantiateViewControllerWithIdentifier(String(self)) as! FurnaceViewController } override func viewDidLoad() { super.viewDidLoad() // initialize No data View if self.noDataView == nil { self.noDataView = (NSBundle.mainBundle().loadNibNamed("NoDataView", owner: self, options: nil)!.last as! NoDataView ) } self.hasRefreshedData = false // Observing notifications NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.handleNotification(_:)), name: DataSearchNotification, object: nil) // Get table column title if let path = NSBundle.mainBundle().pathForResource("FurnaceTitle", ofType: "json") { let data = NSData(contentsOfFile: path) tableTitleJSON = JSON(data: data!) } else { tableTitleJSON = JSON.null } // Define the table dimensions // let navigationBarHeight = self.navigationController?.navigationBar.bounds.height ?? NAVIGATION_BAR_HEIGHT let dataViewWidth = CURRENT_SCREEN_WIDTH let dataViewHeight = CURRENT_SCREEN_HEIGHT - navigationBarHeight - STATUS_BAR_HEIGHT - WISCommon.pageMenuHeaderHeight self.dataView.frame = CGRectZero//CGRectMake(0, 0, dataViewWidth, dataViewHeight) // // TBC: how to get row count? // let columnCount = Furnace().propertyNames().count - 1 // Draw view for first column firstColumnView = UIView(frame: CGRectZero/*CGRectMake(0, 0, FurnaceViewController.firstColumnViewWidth, dataViewHeight)*/) firstColumnView.backgroundColor = UIColor.whiteColor() // headerView.userInteractionEnabled = true self.dataView.addSubview(firstColumnView) // Draw first column table firstColumnTableView = DataTableView(frame: firstColumnView.bounds, style: .Plain, rowInfo: nil) firstColumnTableView.dataTableDelegate = self firstColumnView.addSubview(firstColumnTableView) // Draw view for data table scrollView = UIScrollView(frame: CGRectMake (WISCommon.firstColumnViewWidth, 0, dataViewWidth - WISCommon.firstColumnViewWidth, dataViewHeight)) scrollView.contentSize = CGSizeMake(CGFloat(columnCount) * WISCommon.DataTableColumnWidth, CGFloat(rowCount) * DataTableBaseRowHeight) scrollView.showsHorizontalScrollIndicator = true scrollView.showsVerticalScrollIndicator = true scrollView.bounces = true scrollView.delegate = self scrollView.backgroundColor = UIColor.whiteColor() self.dataView.addSubview(scrollView) // Draw data table var tableColumnsCount = 0 for p in Furnace().propertyNames() { if p == "Id" { continue } else { let tempColumnTableView = DataTableView(frame: CGRectMake(CGFloat(tableColumnsCount) * WISCommon.DataTableColumnWidth, 0, WISCommon.DataTableColumnWidth, dataViewHeight), style: .Plain, rowInfo: nil) self.columnTableView.append(tempColumnTableView) self.columnTableView[tableColumnsCount].dataTableDelegate = self self.scrollView.addSubview(self.columnTableView[tableColumnsCount]) tableColumnsCount += 1 } } // To get data row selected and segue to the dataDetailViewController var selectedElement = firstColumnTableView.selectedIndexPath.asObservable() for tableView in columnTableView { selectedElement = Observable.of(selectedElement, tableView.selectedIndexPath).merge() } var dataTitle: String = EMPTY_STRING // title in the center of navigationbar in dataDetailView var dataContents: [String: String] = [:] // data contents in dataDetailView // selectedElement .subscribeNext { [unowned self] rowIndex -> () in // print("tapped row number: \(rowIndex)") // Read title of record self.firstColumnTableView.viewModel.titleArraySubject .asObservable() .subscribeNext { titleArray in guard rowIndex > -1 && rowIndex < titleArray.count else { return } dataTitle = titleArray[rowIndex] ?? "" }.addDisposableTo(self.disposeBag) var columnTitle: String? // Read detail data with title for column in self.columnTableView { column.viewModel.titleArraySubject .asObservable() .subscribeNext { data in guard rowIndex > -1 && rowIndex < data.count else { return } columnTitle = self.tableTitleJSON["title"][column.title].stringValue ?? "" dataContents[columnTitle!] = data[rowIndex] ?? "" }.addDisposableTo(self.disposeBag) } // DataDetailViewController.performPushToDataDetailViewController(self, title: dataTitle, dataContents: dataContents, animated: true) }.addDisposableTo(disposeBag) dataView.mj_header = WISRefreshHeader {[weak self] () -> () in self?.headerRefresh() } // Get data for data table // self.getData() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) arrangeFurnaceView(self).layoutIfNeeded() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Get data for data table if !hasRefreshedData { getData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func headerRefresh() { //if WISDataManager.sharedInstance().networkReachabilityStatus != .NotReachable { // 如果有上拉“加载更多”正在执行,则取消它 if dataView.mj_footer != nil { if dataView.mj_footer.isRefreshing() { dataView.mj_footer.endRefreshing() } } getData() //} else { // SVProgressHUD.setDefaultMaskType(.None) // SVProgressHUD.showErrorWithStatus(NSLocalizedString("Networking Not Reachable")) //} dataView.mj_header.endRefreshing() } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if currentDevice.isPad { return .All } else { return .AllButUpsideDown } } override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation { return .Portrait } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition({ [unowned self] _ in self.arrangeFurnaceView(self) }, completion:nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: DataSearchNotification, object: nil) } private func arrangeFurnaceView(furnaceViewController: FurnaceViewController) -> UIView { if furnaceViewController.view.subviews.contains(furnaceViewController.noDataView) { furnaceViewController.noDataView.frame = furnaceViewController.dataView.frame } else { let navigationBarHeight = self.navigationController?.navigationBar.bounds.height ?? NAVIGATION_BAR_HEIGHT let dataViewWidth = CURRENT_SCREEN_WIDTH let dataTableHeight = CGFloat(rowCount) * DataTableBaseRowHeight + DataTableHeaderRowHeight let blankScreenHeight = CURRENT_SCREEN_HEIGHT - navigationBarHeight - STATUS_BAR_HEIGHT - WISCommon.pageMenuHeaderHeight // let dataViewHeight = dataTableHeight > blankScreenHeight ? dataTableHeight : blankScreenHeight furnaceViewController.dataView.frame = CGRectMake(0, 0, dataViewWidth, blankScreenHeight) furnaceViewController.dataView.contentSize = CGSizeMake(dataViewWidth, dataTableHeight) furnaceViewController.firstColumnView.frame = CGRectMake(0, 0, WISCommon.firstColumnViewWidth, blankScreenHeight) furnaceViewController.firstColumnTableView.frame = firstColumnView.bounds furnaceViewController.scrollView.frame = CGRectMake(WISCommon.firstColumnViewWidth, 0, dataViewWidth - WISCommon.firstColumnViewWidth, blankScreenHeight) // 需要重新指定 DataTableView 的 frame,否则横屏切换为竖屏后,下方显示不全 var tableColumnsCount = 0 for tableView in self.columnTableView { tableView.frame = CGRectMake(CGFloat(tableColumnsCount) * WISCommon.DataTableColumnWidth, 0, WISCommon.DataTableColumnWidth, blankScreenHeight) tableColumnsCount += 1 } } return furnaceViewController.view } func getData() { SVProgressHUD.showWithStatus("数据获取中...") // Put time consuming network request on global queue dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { Furnace.get(date: SearchParameter["date"]!, shiftNo: SearchParameter["shiftNo"]!, lNo: SearchParameter["lNo"]!) { (response: WISValueResponse<[JSON]>) in // To make sure UI refreshing task runs on main queue // dispatch_async(dispatch_get_main_queue()) { if response.success { SVProgressHUD.setDefaultMaskType(.None) SVProgressHUD.showSuccessWithStatus("数据获取成功!") self.noDataView.removeFromSuperview() self.dataView.addSubview(self.firstColumnView) self.firstColumnView.addSubview(self.firstColumnTableView) self.dataView.addSubview(self.scrollView) self.firstColumnTableView.viewModel.headerString = SearchParameter["date"]! + "\n" + getShiftName(SearchParameter["shiftNo"]!)[0] var firstColumnTitleArray: [String] = [] for i in 0 ..< 8 { firstColumnTitleArray.append(getShiftName(SearchParameter["shiftNo"]!)[i + 1]) } self.firstColumnTableView.viewModel.titleArray = firstColumnTitleArray self.firstColumnTableView.viewModel.titleArraySubject .onNext(firstColumnTitleArray) // self.firstColumnTableView.reloadData() self.tableContentJSON = response.value! // self.firstColumnTableView.reloadData() var tableColumnsCount = 0 for p in Furnace().propertyNames() { if p == "Id" { continue } else { // header let columnTitle = self.tableTitleJSON["title"][p].stringValue self.columnTableView[tableColumnsCount].title = p self.columnTableView[tableColumnsCount].viewModel.headerString = columnTitle self.columnTableView[tableColumnsCount].viewModel.headerStringSubject .onNext(columnTitle) // content var contentArray: [String] = [] for j in 0 ..< self.tableContentJSON.count { let content = self.tableContentJSON[j][p].stringValue.trimNumberFromFractionalPart(2) contentArray.append(content) } if self.tableContentJSON.count < self.rowCount { for _ in self.tableContentJSON.count...(self.rowCount - 1) { contentArray.append("") } } self.columnTableView[tableColumnsCount].viewModel.titleArray = contentArray self.columnTableView[tableColumnsCount].viewModel.titleArraySubject .onNext(contentArray) // self.columnTableView[tableColumnsCount].reloadData() tableColumnsCount += 1 } } self.hasRefreshedData = true } else { self.noDataView.frame = self.dataView.frame self.noDataView.hintTextView.text = response.message self.firstColumnView.removeFromSuperview() self.firstColumnTableView.removeFromSuperview() self.scrollView.removeFromSuperview() self.dataView.addSubview(self.noDataView) self.hasRefreshedData = false wisError(response.message) } } // } } } func handleNotification(notification: NSNotification) -> Void { getData() } /* // 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. } */ } extension FurnaceViewController: DataTableViewDelegate { func dataTableViewContentOffSet(contentOffSet: CGPoint) { for subView in scrollView.subviews { if subView.isKindOfClass(DataTableView) { (subView as! DataTableView).setTableViewContentOffSet(contentOffSet) } } for subView in firstColumnView.subviews { (subView as! DataTableView).setTableViewContentOffSet(contentOffSet) } } } extension FurnaceViewController: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { // let p: CGPoint = scrollView.contentOffset // print(NSStringFromCGPoint(p)) } }
bd3e0ea793a982b9f9521a16a308c04d
42.801587
215
0.585674
false
false
false
false
zixun/GodEye
refs/heads/master
GodEye/Classes/Main/ViewModel/ANRRecordViewModel.swift
mit
1
// // ANRRecordViewModel.swift // Pods // // Created by zixun on 16/12/30. // // import Foundation class ANRRecordViewModel: BaseRecordViewModel { private(set) var model:ANRRecordModel! init(_ model:ANRRecordModel) { super.init() self.model = model } func attributeString() -> NSAttributedString { let result = NSMutableAttributedString() result.append(self.headerString()) result.append(self.mainThreadBacktraceString()) if self.model.showAll { result.append(self.allThreadBacktraceString()) }else { result.append(self.contentString(with: "Click cell to show all", content: "...", newline: false, color: UIColor.cyan)) } return result } private func headerString() -> NSAttributedString { let content = "main thread not response with threshold:\(self.model.threshold!)" return self.headerString(with: "ANR", content: content, color: UIColor(hex: 0xFF0000)) } private func mainThreadBacktraceString() -> NSAttributedString { let result = NSMutableAttributedString(attributedString: self.contentString(with: "MainThread Backtrace", content: self.model.mainThreadBacktrace, newline: true)) let range = result.string.NS.range(of: self.model.mainThreadBacktrace!) if range.location != NSNotFound { let att = [NSAttributedString.Key.font:UIFont(name: "Courier", size: 6)!, NSAttributedString.Key.foregroundColor:UIColor.white] as! [NSAttributedString.Key : Any] result.setAttributes(att, range: range) } return result } private func allThreadBacktraceString() -> NSAttributedString { let result = NSMutableAttributedString(attributedString: self.contentString(with: "AllThread Backtrace", content: self.model.allThreadBacktrace, newline: true)) let range = result.string.NS.range(of: self.model.allThreadBacktrace!) if range.location != NSNotFound { let att = [NSAttributedString.Key.font:UIFont(name: "Courier", size: 6)!, NSAttributedString.Key.foregroundColor:UIColor.white] as! [NSAttributedString.Key : Any] result.setAttributes(att, range: range) } return result } }
940bbe4257decffc03c71a1082e00e2d
35.119403
170
0.634711
false
false
false
false
pvzig/SlackKit
refs/heads/main
SKWebAPI/Sources/NetworkInterface.swift
mit
1
// // NetworkInterface.swift // // Copyright © 2017 Peter Zignego. 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. #if os(Linux) import Dispatch #endif #if canImport(FoundationNetworking) import FoundationNetworking #endif import Foundation #if !COCOAPODS import SKCore #endif public struct NetworkInterface { private let apiUrl = "https://slack.com/api/" #if canImport(FoundationNetworking) private let session = FoundationNetworking.URLSession(configuration: .default) #else private let session = URLSession(configuration: .default) #endif internal init() {} internal func request( _ endpoint: Endpoint, accessToken: String, parameters: [String: Any?], successClosure: @escaping ([String: Any]) -> Void, errorClosure: @escaping (SlackError) -> Void ) { guard !accessToken.isEmpty else { errorClosure(.invalidAuth) return } guard let url = requestURL(for: endpoint, parameters: parameters) else { errorClosure(SlackError.clientNetworkError) return } var request = URLRequest(url: url) request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") session.dataTask(with: request) {(data, response, publicError) in do { successClosure(try NetworkInterface.handleResponse(data, response: response, publicError: publicError)) } catch let error { errorClosure(error as? SlackError ?? SlackError.unknownError) } }.resume() } //Adapted from https://gist.github.com/erica/baa8a187a5b4796dab27 internal func synchronusRequest(_ endpoint: Endpoint, parameters: [String: Any?]) -> [String: Any]? { guard let url = requestURL(for: endpoint, parameters: parameters) else { return nil } let request = URLRequest(url: url) var data: Data? = nil var response: URLResponse? = nil var error: Error? = nil let semaphore = DispatchSemaphore(value: 0) session.dataTask(with: request) { (reqData, reqResponse, reqError) in data = reqData response = reqResponse error = reqError if data == nil, let error = error { print(error) } semaphore.signal() }.resume() _ = semaphore.wait(timeout: DispatchTime.distantFuture) return try? NetworkInterface.handleResponse(data, response: response, publicError: error) } internal func customRequest( _ url: String, token: String, data: Data, success: @escaping (Bool) -> Void, errorClosure: @escaping (SlackError) -> Void ) { guard let string = url.removingPercentEncoding, let url = URL(string: string) else { errorClosure(SlackError.clientNetworkError) return } var request = URLRequest(url:url) request.httpMethod = "POST" let contentType = "application/json; charset: utf-8" request.setValue(contentType, forHTTPHeaderField: "Content-Type") request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") request.httpBody = data session.dataTask(with: request) {(data, response, publicError) in if publicError == nil { success(true) } else { errorClosure(SlackError.clientNetworkError) } }.resume() } internal func uploadRequest( data: Data, accessToken: String, parameters: [String: Any?], successClosure: @escaping ([String: Any]) -> Void, errorClosure: @escaping (SlackError) -> Void ) { guard let url = requestURL(for: .filesUpload, parameters: parameters), let filename = parameters["filename"] as? String, let filetype = parameters["filetype"] as? String else { errorClosure(SlackError.clientNetworkError) return } var request = URLRequest(url:url) request.httpMethod = "POST" let boundaryConstant = randomBoundary() let contentType = "multipart/form-data; boundary=" + boundaryConstant request.setValue(contentType, forHTTPHeaderField: "Content-Type") request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") request.httpBody = requestBodyData(data: data, boundaryConstant: boundaryConstant, filename: filename, filetype: filetype) session.dataTask(with: request) {(data, response, publicError) in do { successClosure(try NetworkInterface.handleResponse(data, response: response, publicError: publicError)) } catch let error { errorClosure(error as? SlackError ?? SlackError.unknownError) } }.resume() } internal static func handleResponse(_ data: Data?, response: URLResponse?, publicError: Error?) throws -> [String: Any] { guard let data = data, let response = response as? HTTPURLResponse else { throw SlackError.clientNetworkError } do { guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { throw SlackError.clientJSONError } switch response.statusCode { case 200: if json["ok"] as? Bool == true { return json } else { if let errorString = json["error"] as? String { throw SlackError(rawValue: errorString) ?? .unknownError } else { throw SlackError.unknownError } } case 429: throw SlackError.tooManyRequests default: throw SlackError.clientNetworkError } } catch let error { if let slackError = error as? SlackError { throw slackError } else { throw SlackError.unknownError } } } private func requestURL(for endpoint: Endpoint, parameters: [String: Any?]) -> URL? { var components = URLComponents(string: "\(apiUrl)\(endpoint.rawValue)") if parameters.count > 0 { components?.queryItems = parameters.compactMapValues({$0}).map { URLQueryItem(name: $0.0, value: "\($0.1)") } } // As discussed http://www.openradar.me/24076063 and https://stackoverflow.com/a/37314144/407523, Apple considers // a + and ? as valid characters in a URL query string, but Slack has recently started enforcing that they be // encoded when included in a query string. As a result, we need to manually apply the encoding after Apple's // default encoding is applied. var encodedQuery = components?.percentEncodedQuery encodedQuery = encodedQuery?.replacingOccurrences(of: ">", with: "%3E") encodedQuery = encodedQuery?.replacingOccurrences(of: "<", with: "%3C") encodedQuery = encodedQuery?.replacingOccurrences(of: "@", with: "%40") encodedQuery = encodedQuery?.replacingOccurrences(of: "?", with: "%3F") encodedQuery = encodedQuery?.replacingOccurrences(of: "+", with: "%2B") components?.percentEncodedQuery = encodedQuery return components?.url } private func requestBodyData(data: Data, boundaryConstant: String, filename: String, filetype: String) -> Data? { let boundaryStart = "--\(boundaryConstant)\r\n" let boundaryEnd = "--\(boundaryConstant)--\r\n" let contentDispositionString = "Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n" let contentTypeString = "Content-Type: \(filetype)\r\n\r\n" let dataEnd = "\r\n" guard let boundaryStartData = boundaryStart.data(using: .utf8), let dispositionData = contentDispositionString.data(using: .utf8), let contentTypeData = contentTypeString.data(using: .utf8), let boundaryEndData = boundaryEnd.data(using: .utf8), let dataEndData = dataEnd.data(using: .utf8) else { return nil } var requestBodyData = Data() requestBodyData.append(contentsOf: boundaryStartData) requestBodyData.append(contentsOf: dispositionData) requestBodyData.append(contentsOf: contentTypeData) requestBodyData.append(contentsOf: data) requestBodyData.append(contentsOf: dataEndData) requestBodyData.append(contentsOf: boundaryEndData) return requestBodyData } private func randomBoundary() -> String { #if os(Linux) return "slackkit.boundary.\(Int(random()))\(Int(random()))" #else return "slackkit.boundary.\(arc4random())\(arc4random())" #endif } }
9e1de748802b866823c97d3e92304954
39.833333
130
0.629567
false
false
false
false
AbidHussainCom/HackingWithSwift
refs/heads/master
project4/Project4/ViewController.swift
unlicense
20
// // ViewController.swift // Project4 // // Created by Hudzilla on 19/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // import UIKit import WebKit class ViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView! var progressView: UIProgressView! var websites = ["apple.com", "slashdot.org"] override func loadView() { webView = WKWebView() webView.navigationDelegate = self view = webView } override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string: "http://" + websites[0])! webView.loadRequest(NSURLRequest(URL: url)) webView.allowsBackForwardNavigationGestures = true // add ourselves as observer. NB: if this were a more complicated app // we would need to remove ourselves as an observer as needed webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Open", style: .Plain, target: self, action: "openTapped") progressView = UIProgressView(progressViewStyle: .Default) let progressButton = UIBarButtonItem(customView: progressView) let spacer = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) let refresh = UIBarButtonItem(barButtonSystemItem: .Refresh, target: webView, action: "reload") toolbarItems = [progressButton, spacer, refresh] navigationController?.toolbarHidden = false } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>) { if keyPath == "estimatedProgress" { progressView.progress = Float(webView.estimatedProgress) } } func openTapped() { let ac = UIAlertController(title: "Open page…", message: nil, preferredStyle: .ActionSheet) for website in websites { ac.addAction(UIAlertAction(title: website, style: .Default, handler: openPage)) } ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(ac, animated: true, completion: nil) } func openPage(action: UIAlertAction!) { let url = NSURL(string: "http://" + action.title)! webView.loadRequest(NSURLRequest(URL: url)) } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { title = webView.title } func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { if let url = navigationAction.request.URL { if let host = url.host { for website in websites { if host.rangeOfString(website) != nil { decisionHandler(.Allow) return } } } } decisionHandler(.Cancel) } }
a172c7f39d342f0923c99bed884f6662
29.897727
158
0.737036
false
false
false
false
beckjing/contacts
refs/heads/master
contacts/contacts/Base/Contact/Model/contactModel/JYCContactModel.swift
mit
1
// // JYCContactModel.swift // contacts // // Created by yuecheng on 21/06/2017. // Copyright © 2017 yuecheng. All rights reserved. // import UIKit import AddressBook.ABRecord class JYCContactModel: NSObject { var pinyin:String? var chineseName:String? var record:ABRecord? var showName:String? init(record:ABRecord) { super.init(); self.record = record let lastName:String = ABRecordCopyValue(record, kABPersonLastNameProperty)?.takeRetainedValue() as! String? ?? "" let firstName:String = ABRecordCopyValue(record, kABPersonFirstNameProperty)?.takeRetainedValue() as! String? ?? "" if isIncludeChinese(string:lastName) { self.pinyin = transformToPinYin(string: lastName) self.showName = lastName + firstName } else { self.pinyin = lastName self.showName = firstName + " " + lastName } } func isIncludeChinese(string: String) -> Bool { for (_, value) in string.characters.enumerated() { if ("\u{4E00}" <= value && value <= "\u{9FA5}") { return true } } return false } func transformToPinYin(string:String)->String{ let mutableString = NSMutableString(string:string) CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false) CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false) let loaclString = String(mutableString) return loaclString.replacingOccurrences(of: " ", with: "").uppercased() } }
42b9817561af93b0548953e08cb9cdba
28.491228
123
0.607377
false
false
false
false
SmallElephant/FEAlgorithm-Swift
refs/heads/master
9-Array/9-Array/Joseph.swift
mit
1
// // Joseph.swift // 9-Array // // Created by FlyElephant on 17/1/13. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class Joseph { // 圆圈中最后剩下的数字 //题目:n个数字(0,1,…,n-1)形成一个圆圈,从数字0开始,每次从这个圆圈中删除第m个数字(第一个为当前数字本身,第二个为当前数字的下一个数字)。当一个数字删除后,从被删除数字的下一个继续删除第m个数字.求出在这个圆圈中剩下的最后一个数字. func lastNumber(n:Int,m:Int)->Int { if n < 1 || m < 1 { return -1 } var number:Int = 0 if n >= 2 { for i in 2...n { number = (number + m) % i } } return number } func normalLastNumber(n:Int,m:Int) -> Int { if n < 1 || m < 1 { return -1 } var number:Int = 0 if n >= 2 { var arr:[Int] = [] for i in 0..<n { arr.append(i) } var position:Int = 0 while arr.count > 1 { for j in 0..<m { if j == m - 1 { arr.remove(at: position) position -= 1 } if position == arr.count - 1{ position = 0 } else { position += 1 } } } number = arr[0] } return number } }
ba2ce6a7f748c3d59c4d755bb1ef9b19
20.791045
127
0.368493
false
false
false
false
spark/photon-tinker-ios
refs/heads/master
Photon-Tinker/Mesh/Gen3SetupEncryptionManager.swift
apache-2.0
1
// // Created by Raimundas Sakalauskas on 23/08/2018. // Copyright (c) 2018 Particle. All rights reserved. // import Foundation import mbedTLSWrapper class Gen3SetupEncryptionManager: NSObject { private var cipher:AesCcmWrapper private var key:Data private var reqNonce:Data private var repNonce:Data required init(derivedSecret: Data) { key = derivedSecret.subdata(in: 0..<16) reqNonce = derivedSecret.subdata(in: 16..<24) repNonce = derivedSecret.subdata(in: 24..<32) cipher = AesCcmWrapper(key: key)! super.init() } func getRequestNonce(requestId: UInt32) -> Data { var data = Data() var reqIdLe = requestId.littleEndian data.append(UInt8(reqIdLe & 0xff)) data.append(UInt8((reqIdLe >> 8) & 0xff)) data.append(UInt8((reqIdLe >> 16) & 0xff)) data.append(UInt8((reqIdLe >> 24) & 0xff)) data.append(reqNonce) return data } func getReplyNonce(requestId: UInt32) -> Data { var data = Data() var reqIdLe = requestId.littleEndian data.append(UInt8(reqIdLe & 0xff)) data.append(UInt8((reqIdLe >> 8) & 0xff)) data.append(UInt8((reqIdLe >> 16) & 0xff)) data.append(UInt8(((reqIdLe >> 24) & 0xff) | 0x80)) data.append(repNonce) return data } func encrypt(_ msg: RequestMessage) -> Data { var requestId = UInt32(msg.id) var outputData = Data() var dataToEncrypt = Data() //size - store it in output data to be used as additional data during the encryption process var leValue = UInt16(msg.data.count).littleEndian outputData.append(UnsafeBufferPointer(start: &leValue, count: 1)) //requestId leValue = msg.id.littleEndian dataToEncrypt.append(UnsafeBufferPointer(start: &leValue, count: 1)) //type leValue = msg.type.rawValue.littleEndian dataToEncrypt.append(UnsafeBufferPointer(start: &leValue, count: 1)) //reserved for future use dataToEncrypt.append(Data(repeating: 0, count: 2)) //payload dataToEncrypt.append(msg.data) var tag:NSData? = nil outputData.append(cipher.encryptData(dataToEncrypt, nonce: getRequestNonce(requestId: requestId), add: outputData, tag: &tag, tagSize: 8)!) outputData.append(tag as! Data) return outputData } //decrypt part assumes that it will decrypt //the reply to previously encrypted request func decrypt(_ data: Data, messageId: UInt16) -> ReplyMessage { var data = data //read data var sizeData = data.subdata(in: 0..<2) var size: Int16 = data.withUnsafeBytes { (pointer: UnsafePointer<Int16>) -> Int16 in return Int16(pointer[0]) } var leSize = size.littleEndian data.removeSubrange(0..<2) //read encrypted data var dataToDecrypt = data.subdata(in: 0..<6+Int(size)) data.removeSubrange(0..<6+Int(size)) //remaining part is tag var tag = data //try to decrypt var replNonce = getReplyNonce(requestId: UInt32(messageId)) var decryptedData = cipher.decryptData(dataToDecrypt, nonce: replNonce, add: sizeData, tag: tag)! var rm = ReplyMessage(id: 0, result: .NONE, data: Data()) //get id rm.id = decryptedData.withUnsafeBytes { (pointer: UnsafePointer<UInt16>) -> UInt16 in return UInt16(pointer[0]) } decryptedData.removeSubrange(0..<2) //get type rm.result = ControlReplyErrorType(rawValue: decryptedData.withUnsafeBytes { (pointer: UnsafePointer<Int32>) -> Int32 in return Int32(pointer[0]) }) ?? ControlReplyErrorType.INVALID_UNKNOWN decryptedData.removeSubrange(0..<4) //get data rm.data = decryptedData return rm } }
2ee534586d29cf0e3a39d08dd821abc4
29.671875
147
0.625064
false
false
false
false
alirsamar/BiOS
refs/heads/master
beginning-ios-alien-adventure-alien-adventure-1-init/Alien Adventure/Settings.swift
mit
1
// // Settings.swift // Alien Adventure // // Created by Jarrod Parkes on 9/18/15. // Copyright © 2015 Udacity. All rights reserved. // import UIKit // MARK: - Settings struct Settings { // MARK: Common struct Common { static let GameDataURL = NSBundle.mainBundle().URLForResource("GameData", withExtension: "plist")! static let Font = "Superclarendon-Italic" static let FontColor = UIColor.whiteColor() static var Level = 0 static var ShowBadges = false static let RequestsToSkip = 0 } // MARK: Dialogue (Set by UDDataLoader) struct Dialogue { static var StartingDialogue = "" static var RequestingDialogue = "" static var TransitioningDialogue = "" static var WinningDialogue = "" static var LosingDialogue = "" } // MARK: Names struct Names { static let Hero = "Hero" static let Background = "Background" static let Treasure = "Treasure" } }
3a7370aec464b1d14c9f398be216e77d
23.232558
106
0.597889
false
false
false
false
bingFly/dict2Model
refs/heads/master
字典转模型/SwiftDictModel/SwiftDictModel/Sources/SwiftDictModel.swift
mit
1
// // SwiftDictModel.swift // 字典转模型 // // Created by hanbing on 15/3/3. // Copyright (c) 2015年 fly. All rights reserved. // import Foundation /** * 定义协议 */ @objc public protocol DictModelProtocol{ static func customClassMapping() -> [String: String]? } /** * 字典转模型 */ public class SwiftDictModel: NSObject{ //// 提供全局访问接口 public static let sharedManager = SwiftDictModel() /** 将字典转换成模型对象 :param: dict 数据字典 :param: cls 模型类 :returns: 实例化的类对象 */ public func objectWithDictionary(dict: NSDictionary, cls: AnyClass) -> AnyObject?{ let dictInfo = fullModelInfo(cls) var obj: AnyObject = cls.alloc() /** * 类信息字典 */ for (k, v) in dictInfo { /// 取出数据字典中的内容 if let value: AnyObject? = dict[k] { // 系统自带的类型 if v.isEmpty && !(value === NSNull()) { obj.setValue(value, forKey: k) } else { // 自定义的类型 let type = "\(value!.classForCoder)" println("自定义对象 \(value) \(k) \(v) ------- type: \(type)") if type == "NSDictionary" { /// 递归遍历 if let subObj: AnyObject? = objectWithDictionary(value as! NSDictionary, cls: NSClassFromString(v)) { obj.setValue(subObj, forKey: k) } } else if type == "NSArray" { if let subObj: AnyObject? = objectWithArray(value as! NSArray, cls:NSClassFromString(v)) { obj.setValue(subObj, forKey: k) } } } } } return obj } /** 将数组转化成模型 :param: array 数据数组 :param: cls 模型类 :returns: 返回实例化对象数组 */ func objectWithArray(array: NSArray, cls: AnyClass) -> [AnyObject]? { var result = [AnyObject]() for value in array { let type = "\(value.classForCoder)" if type == "NSDictionary" { //MARK: - 这里可能不是cls,如果换了一种类呢? if let subObj: AnyObject = objectWithDictionary(value as! NSDictionary, cls: cls) { result.append(subObj) } } else if type == "NSArray" { /// 递归调用 if let subObj: AnyObject = objectWithArray(value as! NSArray, cls: cls) { result.append(subObj) } } } return result } /// 缓存字典 格式[类名: 模型字典, 类名2: 模型字典] var modelCache = [String: [String: String]]() /** 获取类的完整信息 eg:[b: , info: 字典转模型Tests.Info, others: 字典转模型Tests.Info, i: , f: , num: , other: 字典转模型Tests.Info, str2: , d: , str1: ] :param: cls 给定类 :returns: 返回所有信息 */ func fullModelInfo(cls: AnyClass) -> [String: String] { if let cache = modelCache["\(cls)"] { println("\(cls)已经被缓存") return cache } var currentCls: AnyClass = cls var dictInfo = [String: String]() while let parent: AnyClass = currentCls.superclass() { dictInfo.merge(modelInfo(currentCls)) currentCls = parent } // 写入缓存 modelCache["\(cls)"] = dictInfo return dictInfo } /** 获取给定类信息 :param: cls 给定类 */ func modelInfo(cls: AnyClass) -> [String: String]{ if let cache = modelCache["\(cls)"] { println("\(cls)已经被缓存") return cache } var mapping: [String: String]? if cls.respondsToSelector("customClassMapping") { println("实现了协议") mapping = cls.customClassMapping() } var count: UInt32 = 0 let ivars = class_copyIvarList(cls, &count) println("属性个数=\(count)") var dictInfo = [String: String]() for i in 0..<count { let v = ivars[Int(i)] let cname = ivar_getName(v) let name = String.fromCString(cname)! var type = mapping?[name] ?? "" // 设置字典 dictInfo[name] = type } free(ivars) modelCache["\(cls)"] = dictInfo return dictInfo } func loadProperty(cls: AnyClass){ var count: UInt32 = 0 let properties = class_copyPropertyList(cls, &count) println("属性个数=\(count)") for i in 0..<count { let property = properties[Int(i)] let cname = property_getName(property) let name = String.fromCString(cname)! let ctype = property_getAttributes(property) let type = String.fromCString(ctype)! println(name+"------"+type) } free(properties) } func loadIvars(cls: AnyClass){ var count: UInt32 = 0 let ivars = class_copyIvarList(cls, &count) println("属性个数=\(count)") for i in 0..<count { // 获取属性名称 let v = ivars[Int(i)] let cname = ivar_getName(v) let name = String.fromCString(cname)! let ctype = ivar_getTypeEncoding(v) let type = String.fromCString(ctype)! println("\(name)------\(type)") } free(ivars) } } extension Dictionary{ /** 合并字典的分类 泛型 :param: dict 要合并的字典 */ mutating func merge<K,V>(dict:[K: V]){ for (k,v) in dict { self.updateValue(v as! Value, forKey: k as! Key) } } // mutating func merge(dict:[String: String]){ // for (k,v) in dict { // self.updateValue(v as! Value, forKey: k as! Key) // } // } }
37e8dfb7b28373c82ec8a2174aa5af2e
24.053846
125
0.434669
false
false
false
false
LTMana/LTPageView
refs/heads/master
LTPageVIew/LTPageVIew/LTPageView/LTContentView.swift
mit
1
// // LTContentView.swift // LTPageVIew // // Created by liubotong on 2017/5/8. // Copyright © 2017年 LTMana. All rights reserved. // import UIKit private let kContentCellID = "content" class LTContentView: UIView { fileprivate var childVcs:[UIViewController] fileprivate var parentVc:UIViewController fileprivate lazy var collectionView : UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = self.bounds.size layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier:kContentCellID) collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.bounces = false collectionView.scrollsToTop = false //点击状态栏页面滚回最顶部 return collectionView }() init(frame: CGRect,childVcs:[UIViewController],parentVc:UIViewController){ self.childVcs = childVcs self.parentVc = parentVc super.init(frame:frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension LTContentView{ fileprivate func setupUI(){ for childVc in childVcs { parentVc.addChildViewController(childVc) } addSubview(collectionView) } } extension LTContentView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kContentCellID, for: indexPath) for subview in cell.contentView.subviews { subview.removeFromSuperview() } let childVc = childVcs[indexPath.item] cell.contentView.addSubview(childVc.view) return cell } } extension LTContentView : UICollectionViewDelegate{ } extension LTContentView : LTTitleVIewDelegate{ func titleView(_ titleView: LTTitleVIew, targetIndex: Int) { let indexPath = IndexPath(item: targetIndex, section:0) collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false) } }
efbffbb9ab8dc757c2825b4044c7f7ef
23.95614
121
0.654833
false
false
false
false
linbin00303/Dotadog
refs/heads/master
DotaDog/DotaDog/Classes/Video/View/DDogLiveCell.swift
mit
1
// // DDogLiveCell.swift // DotaDog // // Created by 林彬 on 16/6/6. // Copyright © 2016年 linbin. All rights reserved. // import UIKit class DDogLiveCell: UITableViewCell { @IBOutlet weak var pic: UIImageView! @IBOutlet weak var img: UIImageView! @IBOutlet weak var title: UILabel! @IBOutlet weak var subtitle: UILabel! var model : DDogLiveModel?{ didSet{ guard let model = model else { return } pic.sd_setImageWithURL(NSURL(string: model.pic), placeholderImage: UIImage(named: "empty_picture")) img.sd_setImageWithURL(NSURL(string: model.image), placeholderImage: UIImage(named: "empty_picture")) title.text = model.title subtitle.text = model.subtitle } } override func awakeFromNib() { super.awakeFromNib() let imageView = UIImageView(image: UIImage(named: "livecellBackground")) imageView.frame = self.contentView.bounds self.backgroundView = imageView } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // override var frame: CGRect{ // set{ // frame.origin.x = 5 // frame.size.width -= 10 //// super.frame = frame // } // // get{ //// let frame = self.frame // return super.frame // } // } // }
f497791aaf6f6085f5f687f9e57a3ca5
23.84375
113
0.555346
false
false
false
false
bringg/customer-sdk-ios-demo
refs/heads/master
Pods/Starscream/Sources/Starscream/WebSocket.swift
apache-2.0
3
////////////////////////////////////////////////////////////////////////////////////////////////// // // Websocket.swift // // Created by Dalton Cherry on 7/16/14. // Copyright (c) 2014-2017 Dalton Cherry. // // 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 CoreFoundation import CommonCrypto public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification" public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification" public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName" //Standard WebSocket close codes public enum CloseCode : UInt16 { case normal = 1000 case goingAway = 1001 case protocolError = 1002 case protocolUnhandledType = 1003 // 1004 reserved. case noStatusReceived = 1005 //1006 reserved. case encoding = 1007 case policyViolated = 1008 case messageTooBig = 1009 } public enum ErrorType: Error { case outputStreamWriteError //output stream error during write case compressionError case invalidSSLError //Invalid SSL certificate case writeTimeoutError //The socket timed out waiting to be ready to write case protocolError //There was an error parsing the WebSocket frames case upgradeError //There was an error during the HTTP upgrade case closeError //There was an error during the close (socket probably has been dereferenced) } public struct WSError: Error { public let type: ErrorType public let message: String public let code: Int } //WebSocketClient is setup to be dependency injection for testing public protocol WebSocketClient: class { var delegate: WebSocketDelegate? {get set} var pongDelegate: WebSocketPongDelegate? {get set} var disableSSLCertValidation: Bool {get set} var overrideTrustHostname: Bool {get set} var desiredTrustHostname: String? {get set} var sslClientCertificate: SSLClientCertificate? {get set} #if os(Linux) #else var security: SSLTrustValidator? {get set} var enabledSSLCipherSuites: [SSLCipherSuite]? {get set} #endif var isConnected: Bool {get} func connect() func disconnect(forceTimeout: TimeInterval?, closeCode: UInt16) func write(string: String, completion: (() -> ())?) func write(data: Data, completion: (() -> ())?) func write(ping: Data, completion: (() -> ())?) func write(pong: Data, completion: (() -> ())?) } //implements some of the base behaviors extension WebSocketClient { public func write(string: String) { write(string: string, completion: nil) } public func write(data: Data) { write(data: data, completion: nil) } public func write(ping: Data) { write(ping: ping, completion: nil) } public func write(pong: Data) { write(pong: pong, completion: nil) } public func disconnect() { disconnect(forceTimeout: nil, closeCode: CloseCode.normal.rawValue) } } //SSL settings for the stream public struct SSLSettings { public let useSSL: Bool public let disableCertValidation: Bool public var overrideTrustHostname: Bool public var desiredTrustHostname: String? public let sslClientCertificate: SSLClientCertificate? #if os(Linux) #else public let cipherSuites: [SSLCipherSuite]? #endif } public protocol WSStreamDelegate: class { func newBytesInStream() func streamDidError(error: Error?) } //This protocol is to allow custom implemention of the underlining stream. This way custom socket libraries (e.g. linux) can be used public protocol WSStream { var delegate: WSStreamDelegate? {get set} func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) func write(data: Data) -> Int func read() -> Data? func cleanup() #if os(Linux) || os(watchOS) #else func sslTrust() -> (trust: SecTrust?, domain: String?) #endif } open class FoundationStream : NSObject, WSStream, StreamDelegate { private let workQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: []) private var inputStream: InputStream? private var outputStream: OutputStream? public weak var delegate: WSStreamDelegate? let BUFFER_MAX = 4096 public var enableSOCKSProxy = false public func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) { var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? let h = url.host! as NSString CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream) inputStream = readStream!.takeRetainedValue() outputStream = writeStream!.takeRetainedValue() #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work #else if enableSOCKSProxy { let proxyDict = CFNetworkCopySystemProxySettings() let socksConfig = CFDictionaryCreateMutableCopy(nil, 0, proxyDict!.takeRetainedValue()) let propertyKey = CFStreamPropertyKey(rawValue: kCFStreamPropertySOCKSProxy) CFWriteStreamSetProperty(outputStream, propertyKey, socksConfig) CFReadStreamSetProperty(inputStream, propertyKey, socksConfig) } #endif guard let inStream = inputStream, let outStream = outputStream else { return } inStream.delegate = self outStream.delegate = self if ssl.useSSL { inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work #else var settings = [NSObject: NSObject]() if ssl.disableCertValidation { settings[kCFStreamSSLValidatesCertificateChain] = NSNumber(value: false) } if ssl.overrideTrustHostname { if let hostname = ssl.desiredTrustHostname { settings[kCFStreamSSLPeerName] = hostname as NSString } else { settings[kCFStreamSSLPeerName] = kCFNull } } if let sslClientCertificate = ssl.sslClientCertificate { settings[kCFStreamSSLCertificates] = sslClientCertificate.streamSSLCertificates } inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) #endif #if os(Linux) #else if let cipherSuites = ssl.cipherSuites { #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work #else if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?, let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count) let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count) if resIn != errSecSuccess { completion(WSError(type: .invalidSSLError, message: "Error setting ingoing cypher suites", code: Int(resIn))) } if resOut != errSecSuccess { completion(WSError(type: .invalidSSLError, message: "Error setting outgoing cypher suites", code: Int(resOut))) } } #endif } #endif } CFReadStreamSetDispatchQueue(inStream, workQueue) CFWriteStreamSetDispatchQueue(outStream, workQueue) inStream.open() outStream.open() var out = timeout// wait X seconds before giving up workQueue.async { [weak self] in while !outStream.hasSpaceAvailable { usleep(100) // wait until the socket is ready out -= 100 if out < 0 { completion(WSError(type: .writeTimeoutError, message: "Timed out waiting for the socket to be ready for a write", code: 0)) return } else if let error = outStream.streamError { completion(error) return // disconnectStream will be called. } else if self == nil { completion(WSError(type: .closeError, message: "socket object has been dereferenced", code: 0)) return } } completion(nil) //success! } } public func write(data: Data) -> Int { guard let outStream = outputStream else {return -1} let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self) return outStream.write(buffer, maxLength: data.count) } public func read() -> Data? { guard let stream = inputStream else {return nil} let buf = NSMutableData(capacity: BUFFER_MAX) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) let length = stream.read(buffer, maxLength: BUFFER_MAX) if length < 1 { return nil } return Data(bytes: buffer, count: length) } public func cleanup() { if let stream = inputStream { stream.delegate = nil CFReadStreamSetDispatchQueue(stream, nil) stream.close() } if let stream = outputStream { stream.delegate = nil CFWriteStreamSetDispatchQueue(stream, nil) stream.close() } outputStream = nil inputStream = nil } #if os(Linux) || os(watchOS) #else public func sslTrust() -> (trust: SecTrust?, domain: String?) { guard let outputStream = outputStream else { return (nil, nil) } let trust = outputStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust? var domain = outputStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as! String? if domain == nil, let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { var peerNameLen: Int = 0 SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen) var peerName = Data(count: peerNameLen) let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen) } if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 { domain = peerDomain } } return (trust, domain) } #endif /** Delegate for the stream methods. Processes incoming bytes */ open func stream(_ aStream: Stream, handle eventCode: Stream.Event) { if eventCode == .hasBytesAvailable { if aStream == inputStream { delegate?.newBytesInStream() } } else if eventCode == .errorOccurred { delegate?.streamDidError(error: aStream.streamError) } else if eventCode == .endEncountered { delegate?.streamDidError(error: nil) } } } //WebSocket implementation //standard delegate you should use public protocol WebSocketDelegate: class { func websocketDidConnect(socket: WebSocketClient) func websocketDidDisconnect(socket: WebSocketClient, error: Error?) func websocketDidReceiveMessage(socket: WebSocketClient, text: String) func websocketDidReceiveData(socket: WebSocketClient, data: Data) } //got pongs public protocol WebSocketPongDelegate: class { func websocketDidReceivePong(socket: WebSocketClient, data: Data?) } // A Delegate with more advanced info on messages and connection etc. public protocol WebSocketAdvancedDelegate: class { func websocketDidConnect(socket: WebSocket) func websocketDidDisconnect(socket: WebSocket, error: Error?) func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse) func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse) func websocketHttpUpgrade(socket: WebSocket, request: String) func websocketHttpUpgrade(socket: WebSocket, response: String) } open class WebSocket : NSObject, StreamDelegate, WebSocketClient, WSStreamDelegate { public enum OpCode : UInt8 { case continueFrame = 0x0 case textFrame = 0x1 case binaryFrame = 0x2 // 3-7 are reserved. case connectionClose = 0x8 case ping = 0x9 case pong = 0xA // B-F reserved. } public static let ErrorDomain = "WebSocket" // Where the callback is executed. It defaults to the main UI thread queue. public var callbackQueue = DispatchQueue.main // MARK: - Constants let headerWSUpgradeName = "Upgrade" let headerWSUpgradeValue = "websocket" let headerWSHostName = "Host" let headerWSConnectionName = "Connection" let headerWSConnectionValue = "Upgrade" let headerWSProtocolName = "Sec-WebSocket-Protocol" let headerWSVersionName = "Sec-WebSocket-Version" let headerWSVersionValue = "13" let headerWSExtensionName = "Sec-WebSocket-Extensions" let headerWSKeyName = "Sec-WebSocket-Key" let headerOriginName = "Origin" let headerWSAcceptName = "Sec-WebSocket-Accept" let BUFFER_MAX = 4096 let FinMask: UInt8 = 0x80 let OpCodeMask: UInt8 = 0x0F let RSVMask: UInt8 = 0x70 let RSV1Mask: UInt8 = 0x40 let MaskMask: UInt8 = 0x80 let PayloadLenMask: UInt8 = 0x7F let MaxFrameSize: Int = 32 let httpSwitchProtocolCode = 101 let supportedSSLSchemes = ["wss", "https"] public class WSResponse { var isFin = false public var code: OpCode = .continueFrame var bytesLeft = 0 public var frameCount = 0 public var buffer: NSMutableData? public let firstFrame = { return Date() }() } // MARK: - Delegates /// Responds to callback about new messages coming in over the WebSocket /// and also connection/disconnect messages. public weak var delegate: WebSocketDelegate? /// The optional advanced delegate can be used instead of of the delegate public weak var advancedDelegate: WebSocketAdvancedDelegate? /// Receives a callback for each pong message recived. public weak var pongDelegate: WebSocketPongDelegate? public var onConnect: (() -> Void)? public var onDisconnect: ((Error?) -> Void)? public var onText: ((String) -> Void)? public var onData: ((Data) -> Void)? public var onPong: ((Data?) -> Void)? public var onHttpResponseHeaders: (([String: String]) -> Void)? public var disableSSLCertValidation = false public var overrideTrustHostname = false public var desiredTrustHostname: String? = nil public var sslClientCertificate: SSLClientCertificate? = nil public var enableCompression = true #if os(Linux) #else public var security: SSLTrustValidator? public var enabledSSLCipherSuites: [SSLCipherSuite]? #endif public var isConnected: Bool { mutex.lock() let isConnected = connected mutex.unlock() return isConnected } public var request: URLRequest //this is only public to allow headers, timeout, etc to be modified on reconnect public var currentURL: URL { return request.url! } public var respondToPingWithPong: Bool = true // MARK: - Private private struct CompressionState { var supportsCompression = false var messageNeedsDecompression = false var serverMaxWindowBits = 15 var clientMaxWindowBits = 15 var clientNoContextTakeover = false var serverNoContextTakeover = false var decompressor:Decompressor? = nil var compressor:Compressor? = nil } private var stream: WSStream private var connected = false private var isConnecting = false private let mutex = NSLock() private var compressionState = CompressionState() private var writeQueue = OperationQueue() private var readStack = [WSResponse]() private var inputQueue = [Data]() private var fragBuffer: Data? private var certValidated = false private var didDisconnect = false private var readyToWrite = false private var headerSecKey = "" private var canDispatch: Bool { mutex.lock() let canWork = readyToWrite mutex.unlock() return canWork } /// Used for setting protocols. public init(request: URLRequest, protocols: [String]? = nil, stream: WSStream = FoundationStream()) { self.request = request self.stream = stream if request.value(forHTTPHeaderField: headerOriginName) == nil { guard let url = request.url else {return} var origin = url.absoluteString if let hostUrl = URL (string: "/", relativeTo: url) { origin = hostUrl.absoluteString origin.remove(at: origin.index(before: origin.endIndex)) } self.request.setValue(origin, forHTTPHeaderField: headerOriginName) } if let protocols = protocols, !protocols.isEmpty { self.request.setValue(protocols.joined(separator: ","), forHTTPHeaderField: headerWSProtocolName) } writeQueue.maxConcurrentOperationCount = 1 } public convenience init(url: URL, protocols: [String]? = nil) { var request = URLRequest(url: url) request.timeoutInterval = 5 self.init(request: request, protocols: protocols) } // Used for specifically setting the QOS for the write queue. public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) { self.init(url: url, protocols: protocols) writeQueue.qualityOfService = writeQueueQOS } /** Connect to the WebSocket server on a background thread. */ open func connect() { guard !isConnecting else { return } didDisconnect = false isConnecting = true createHTTPRequest() } /** Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed. If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate. - Parameter forceTimeout: Maximum time to wait for the server to close the socket. - Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket. */ open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) { guard isConnected else { return } switch forceTimeout { case .some(let seconds) where seconds > 0: let milliseconds = Int(seconds * 1_000) callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in self?.disconnectStream(nil) } fallthrough case .none: writeError(closeCode) default: disconnectStream(nil) break } } /** Write a string to the websocket. This sends it as a text frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter string: The string to write. - parameter completion: The (optional) completion handler. */ open func write(string: String, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion) } /** Write binary data to the websocket. This sends it as a binary frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter data: The data to write. - parameter completion: The (optional) completion handler. */ open func write(data: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(data, code: .binaryFrame, writeCompletion: completion) } /** Write a ping to the websocket. This sends it as a control frame. Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s */ open func write(ping: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(ping, code: .ping, writeCompletion: completion) } /** Write a pong to the websocket. This sends it as a control frame. Respond to a Yodel. */ open func write(pong: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(pong, code: .pong, writeCompletion: completion) } /** Private method that starts the connection. */ private func createHTTPRequest() { guard let url = request.url else {return} var port = url.port if port == nil { if supportedSSLSchemes.contains(url.scheme!) { port = 443 } else { port = 80 } } request.setValue(headerWSUpgradeValue, forHTTPHeaderField: headerWSUpgradeName) request.setValue(headerWSConnectionValue, forHTTPHeaderField: headerWSConnectionName) headerSecKey = generateWebSocketKey() request.setValue(headerWSVersionValue, forHTTPHeaderField: headerWSVersionName) request.setValue(headerSecKey, forHTTPHeaderField: headerWSKeyName) if enableCompression { let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15" request.setValue(val, forHTTPHeaderField: headerWSExtensionName) } let hostValue = request.allHTTPHeaderFields?[headerWSHostName] ?? "\(url.host!):\(port!)" request.setValue(hostValue, forHTTPHeaderField: headerWSHostName) var path = url.absoluteString let offset = (url.scheme?.count ?? 2) + 3 path = String(path[path.index(path.startIndex, offsetBy: offset)..<path.endIndex]) if let range = path.range(of: "/") { path = String(path[range.lowerBound..<path.endIndex]) } else { path = "/" if let query = url.query { path += "?" + query } } var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n" if let headers = request.allHTTPHeaderFields { for (key, val) in headers { httpBody += "\(key): \(val)\r\n" } } httpBody += "\r\n" initStreamsWithData(httpBody.data(using: .utf8)!, Int(port!)) advancedDelegate?.websocketHttpUpgrade(socket: self, request: httpBody) } /** Generate a WebSocket key as needed in RFC. */ private func generateWebSocketKey() -> String { var key = "" let seed = 16 for _ in 0..<seed { let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25))) key += "\(Character(uni!))" } let data = key.data(using: String.Encoding.utf8) let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return baseKey! } /** Start the stream connection and write the data to the output stream. */ private func initStreamsWithData(_ data: Data, _ port: Int) { guard let url = request.url else { disconnectStream(nil, runDelegate: true) return } // Disconnect and clean up any existing streams before setting up a new pair disconnectStream(nil, runDelegate: false) let useSSL = supportedSSLSchemes.contains(url.scheme!) #if os(Linux) let settings = SSLSettings(useSSL: useSSL, disableCertValidation: disableSSLCertValidation, overrideTrustHostname: overrideTrustHostname, desiredTrustHostname: desiredTrustHostname), sslClientCertificate: sslClientCertificate #else let settings = SSLSettings(useSSL: useSSL, disableCertValidation: disableSSLCertValidation, overrideTrustHostname: overrideTrustHostname, desiredTrustHostname: desiredTrustHostname, sslClientCertificate: sslClientCertificate, cipherSuites: self.enabledSSLCipherSuites) #endif certValidated = !useSSL let timeout = request.timeoutInterval * 1_000_000 stream.delegate = self stream.connect(url: url, port: port, timeout: timeout, ssl: settings, completion: { [weak self] (error) in guard let self = self else {return} if error != nil { self.disconnectStream(error) return } let operation = BlockOperation() operation.addExecutionBlock { [weak self, weak operation] in guard let sOperation = operation, let self = self else { return } guard !sOperation.isCancelled else { return } // Do the pinning now if needed #if os(Linux) || os(watchOS) self.certValidated = false #else if let sec = self.security, !self.certValidated { let trustObj = self.stream.sslTrust() if let possibleTrust = trustObj.trust { self.certValidated = sec.isValid(possibleTrust, domain: trustObj.domain) } else { self.certValidated = false } if !self.certValidated { self.disconnectStream(WSError(type: .invalidSSLError, message: "Invalid SSL certificate", code: 0)) return } } #endif let _ = self.stream.write(data: data) } self.writeQueue.addOperation(operation) }) self.mutex.lock() self.readyToWrite = true self.mutex.unlock() } /** Delegate for the stream methods. Processes incoming bytes */ public func newBytesInStream() { processInputStream() } public func streamDidError(error: Error?) { disconnectStream(error) } /** Disconnect the stream object and notifies the delegate. */ private func disconnectStream(_ error: Error?, runDelegate: Bool = true) { if error == nil { writeQueue.waitUntilAllOperationsAreFinished() } else { writeQueue.cancelAllOperations() } mutex.lock() cleanupStream() connected = false mutex.unlock() if runDelegate { doDisconnect(error) } } /** cleanup the streams. */ private func cleanupStream() { stream.cleanup() fragBuffer = nil } /** Handles the incoming bytes and sending them to the proper processing method. */ private func processInputStream() { let data = stream.read() guard let d = data else { return } var process = false if inputQueue.count == 0 { process = true } inputQueue.append(d) if process { dequeueInput() } } /** Dequeue the incoming input so it is processed in order. */ private func dequeueInput() { while !inputQueue.isEmpty { autoreleasepool { let data = inputQueue[0] var work = data if let buffer = fragBuffer { var combine = NSData(data: buffer) as Data combine.append(data) work = combine fragBuffer = nil } let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self) let length = work.count if !connected { processTCPHandshake(buffer, bufferLen: length) } else { processRawMessagesInBuffer(buffer, bufferLen: length) } inputQueue = inputQueue.filter{ $0 != data } } } } /** Handle checking the inital connection status */ private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) { let code = processHTTP(buffer, bufferLen: bufferLen) switch code { case 0: break case -1: fragBuffer = Data(bytes: buffer, count: bufferLen) break // do nothing, we are going to collect more data default: doDisconnect(WSError(type: .upgradeError, message: "Invalid HTTP upgrade", code: code)) } } /** Finds the HTTP Packet in the TCP stream, by looking for the CRLF. */ private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var k = 0 var totalSize = 0 for i in 0..<bufferLen { if buffer[i] == CRLFBytes[k] { k += 1 if k == 4 { totalSize = i + 1 break } } else { k = 0 } } if totalSize > 0 { let code = validateResponse(buffer, bufferLen: totalSize) if code != 0 { return code } isConnecting = false mutex.lock() connected = true mutex.unlock() didDisconnect = false if canDispatch { callbackQueue.async { [weak self] in guard let self = self else { return } self.onConnect?() self.delegate?.websocketDidConnect(socket: self) self.advancedDelegate?.websocketDidConnect(socket: self) NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self) } } //totalSize += 1 //skip the last \n let restSize = bufferLen - totalSize if restSize > 0 { processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize) } return 0 //success } return -1 // Was unable to find the full TCP header. } /** Validates the HTTP is a 101 as per the RFC spec. */ private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { guard let str = String(data: Data(bytes: buffer, count: bufferLen), encoding: .utf8) else { return -1 } let splitArr = str.components(separatedBy: "\r\n") var code = -1 var i = 0 var headers = [String: String]() for str in splitArr { if i == 0 { let responseSplit = str.components(separatedBy: .whitespaces) guard responseSplit.count > 1 else { return -1 } if let c = Int(responseSplit[1]) { code = c } } else { let responseSplit = str.components(separatedBy: ":") guard responseSplit.count > 1 else { break } let key = responseSplit[0].trimmingCharacters(in: .whitespaces) let val = responseSplit[1].trimmingCharacters(in: .whitespaces) headers[key.lowercased()] = val } i += 1 } advancedDelegate?.websocketHttpUpgrade(socket: self, response: str) onHttpResponseHeaders?(headers) if code != httpSwitchProtocolCode { return code } if let extensionHeader = headers[headerWSExtensionName.lowercased()] { processExtensionHeader(extensionHeader) } if let acceptKey = headers[headerWSAcceptName.lowercased()] { if acceptKey.count > 0 { if headerSecKey.count > 0 { let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64() if sha != acceptKey as String { return -1 } } return 0 } } return -1 } /** Parses the extension header, setting up the compression parameters. */ func processExtensionHeader(_ extensionHeader: String) { let parts = extensionHeader.components(separatedBy: ";") for p in parts { let part = p.trimmingCharacters(in: .whitespaces) if part == "permessage-deflate" { compressionState.supportsCompression = true } else if part.hasPrefix("server_max_window_bits=") { let valString = part.components(separatedBy: "=")[1] if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { compressionState.serverMaxWindowBits = val } } else if part.hasPrefix("client_max_window_bits=") { let valString = part.components(separatedBy: "=")[1] if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { compressionState.clientMaxWindowBits = val } } else if part == "client_no_context_takeover" { compressionState.clientNoContextTakeover = true } else if part == "server_no_context_takeover" { compressionState.serverNoContextTakeover = true } } if compressionState.supportsCompression { compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits) compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits) } } /** Read a 16 bit big endian value from a buffer */ private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 { return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1]) } /** Read a 64 bit big endian value from a buffer */ private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 { var value = UInt64(0) for i in 0...7 { value = (value << 8) | UInt64(buffer[offset + i]) } return value } /** Write a 16-bit big endian value to a buffer. */ private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) { buffer[offset + 0] = UInt8(value >> 8) buffer[offset + 1] = UInt8(value & 0xff) } /** Write a 64-bit big endian value to a buffer. */ private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) { for i in 0...7 { buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) } } /** Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process. */ private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> { let response = readStack.last guard let baseAddress = buffer.baseAddress else {return emptyBuffer} let bufferLen = buffer.count if response != nil && bufferLen < 2 { fragBuffer = Data(buffer: buffer) return emptyBuffer } if let response = response, response.bytesLeft > 0 { var len = response.bytesLeft var extra = bufferLen - response.bytesLeft if response.bytesLeft > bufferLen { len = bufferLen extra = 0 } response.bytesLeft -= len response.buffer?.append(Data(bytes: baseAddress, count: len)) _ = processResponse(response) return buffer.fromOffset(bufferLen - extra) } else { let isFin = (FinMask & baseAddress[0]) let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0]) let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue) let isMasked = (MaskMask & baseAddress[1]) let payloadLen = (PayloadLenMask & baseAddress[1]) var offset = 2 if compressionState.supportsCompression && receivedOpcode != .continueFrame { compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0 } if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: Int(errCode))) writeError(errCode) return emptyBuffer } let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping) if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame && receivedOpcode != .textFrame && receivedOpcode != .pong) { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "unknown opcode: \(receivedOpcodeRawValue)", code: Int(errCode))) writeError(errCode) return emptyBuffer } if isControlFrame && isFin == 0 { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "control frames can't be fragmented", code: Int(errCode))) writeError(errCode) return emptyBuffer } var closeCode = CloseCode.normal.rawValue if receivedOpcode == .connectionClose { if payloadLen == 1 { closeCode = CloseCode.protocolError.rawValue } else if payloadLen > 1 { closeCode = WebSocket.readUint16(baseAddress, offset: offset) if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) { closeCode = CloseCode.protocolError.rawValue } } if payloadLen < 2 { doDisconnect(WSError(type: .protocolError, message: "connection closed by server", code: Int(closeCode))) writeError(closeCode) return emptyBuffer } } else if isControlFrame && payloadLen > 125 { writeError(CloseCode.protocolError.rawValue) return emptyBuffer } var dataLength = UInt64(payloadLen) if dataLength == 127 { dataLength = WebSocket.readUint64(baseAddress, offset: offset) offset += MemoryLayout<UInt64>.size } else if dataLength == 126 { dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset)) offset += MemoryLayout<UInt16>.size } if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { fragBuffer = Data(bytes: baseAddress, count: bufferLen) return emptyBuffer } var len = dataLength if dataLength > UInt64(bufferLen) { len = UInt64(bufferLen-offset) } if receivedOpcode == .connectionClose && len > 0 { let size = MemoryLayout<UInt16>.size offset += size len -= UInt64(size) } let data: Data if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor { do { data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0) if isFin > 0 && compressionState.serverNoContextTakeover { try decompressor.reset() } } catch { let closeReason = "Decompression failed: \(error)" let closeCode = CloseCode.encoding.rawValue doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode))) writeError(closeCode) return emptyBuffer } } else { data = Data(bytes: baseAddress+offset, count: Int(len)) } if receivedOpcode == .connectionClose { var closeReason = "connection closed by server" if let customCloseReason = String(data: data, encoding: .utf8) { closeReason = customCloseReason } else { closeCode = CloseCode.protocolError.rawValue } doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode))) writeError(closeCode) return emptyBuffer } if receivedOpcode == .pong { if canDispatch { callbackQueue.async { [weak self] in guard let self = self else { return } let pongData: Data? = data.count > 0 ? data : nil self.onPong?(pongData) self.pongDelegate?.websocketDidReceivePong(socket: self, data: pongData) } } return buffer.fromOffset(offset + Int(len)) } var response = readStack.last if isControlFrame { response = nil // Don't append pings. } if isFin == 0 && receivedOpcode == .continueFrame && response == nil { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "continue frame before a binary or text frame", code: Int(errCode))) writeError(errCode) return emptyBuffer } var isNew = false if response == nil { if receivedOpcode == .continueFrame { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: Int(errCode))) writeError(errCode) return emptyBuffer } isNew = true response = WSResponse() response!.code = receivedOpcode! response!.bytesLeft = Int(dataLength) response!.buffer = NSMutableData(data: data) } else { if receivedOpcode == .continueFrame { response!.bytesLeft = Int(dataLength) } else { let errCode = CloseCode.protocolError.rawValue doDisconnect(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: Int(errCode))) writeError(errCode) return emptyBuffer } response!.buffer!.append(data) } if let response = response { response.bytesLeft -= Int(len) response.frameCount += 1 response.isFin = isFin > 0 ? true : false if isNew { readStack.append(response) } _ = processResponse(response) } let step = Int(offset + numericCast(len)) return buffer.fromOffset(step) } } /** Process all messages in the buffer if possible. */ private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) { var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen) repeat { buffer = processOneRawMessage(inBuffer: buffer) } while buffer.count >= 2 if buffer.count > 0 { fragBuffer = Data(buffer: buffer) } } /** Process the finished response of a buffer. */ private func processResponse(_ response: WSResponse) -> Bool { if response.isFin && response.bytesLeft <= 0 { if response.code == .ping { if respondToPingWithPong { let data = response.buffer! // local copy so it is perverse for writing dequeueWrite(data as Data, code: .pong) } } else if response.code == .textFrame { guard let str = String(data: response.buffer! as Data, encoding: .utf8) else { writeError(CloseCode.encoding.rawValue) return false } if canDispatch { callbackQueue.async { [weak self] in guard let self = self else { return } self.onText?(str) self.delegate?.websocketDidReceiveMessage(socket: self, text: str) self.advancedDelegate?.websocketDidReceiveMessage(socket: self, text: str, response: response) } } } else if response.code == .binaryFrame { if canDispatch { let data = response.buffer! // local copy so it is perverse for writing callbackQueue.async { [weak self] in guard let self = self else { return } self.onData?(data as Data) self.delegate?.websocketDidReceiveData(socket: self, data: data as Data) self.advancedDelegate?.websocketDidReceiveData(socket: self, data: data as Data, response: response) } } } readStack.removeLast() return true } return false } /** Write an error to the socket */ private func writeError(_ code: UInt16) { let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) WebSocket.writeUint16(buffer, offset: 0, value: code) dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose) } /** Used to write things to the stream */ private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) { let operation = BlockOperation() operation.addExecutionBlock { [weak self, weak operation] in //stream isn't ready, let's wait guard let self = self else { return } guard let sOperation = operation else { return } var offset = 2 var firstByte:UInt8 = self.FinMask | code.rawValue var data = data if [.textFrame, .binaryFrame].contains(code), let compressor = self.compressionState.compressor { do { data = try compressor.compress(data) if self.compressionState.clientNoContextTakeover { try compressor.reset() } firstByte |= self.RSV1Mask } catch { // TODO: report error? We can just send the uncompressed frame. } } let dataLength = data.count let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize) let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self) buffer[0] = firstByte if dataLength < 126 { buffer[1] = CUnsignedChar(dataLength) } else if dataLength <= Int(UInt16.max) { buffer[1] = 126 WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength)) offset += MemoryLayout<UInt16>.size } else { buffer[1] = 127 WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength)) offset += MemoryLayout<UInt64>.size } buffer[1] |= self.MaskMask let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset) _ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey) offset += MemoryLayout<UInt32>.size for i in 0..<dataLength { buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size] offset += 1 } var total = 0 while !sOperation.isCancelled { if !self.readyToWrite { self.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0)) break } let stream = self.stream let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self) let len = stream.write(data: Data(bytes: writeBuffer, count: offset-total)) if len <= 0 { self.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0)) break } else { total += len } if total >= offset { if let callback = writeCompletion { self.callbackQueue.async { callback() } } break } } } writeQueue.addOperation(operation) } /** Used to preform the disconnect delegate */ private func doDisconnect(_ error: Error?) { guard !didDisconnect else { return } didDisconnect = true isConnecting = false mutex.lock() connected = false mutex.unlock() guard canDispatch else {return} callbackQueue.async { [weak self] in guard let self = self else { return } self.onDisconnect?(error) self.delegate?.websocketDidDisconnect(socket: self, error: error) self.advancedDelegate?.websocketDidDisconnect(socket: self, error: error) let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] } NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo) } } // MARK: - Deinit deinit { mutex.lock() readyToWrite = false cleanupStream() mutex.unlock() writeQueue.cancelAllOperations() } } private extension String { func sha1Base64() -> String { let data = self.data(using: String.Encoding.utf8)! var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) } return Data(bytes: digest).base64EncodedString() } } private extension Data { init(buffer: UnsafeBufferPointer<UInt8>) { self.init(bytes: buffer.baseAddress!, count: buffer.count) } } private extension UnsafeBufferPointer { func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> { return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset) } } private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0) #if swift(>=4) #else fileprivate extension String { var count: Int { return self.characters.count } } #endif
baf2dfd31446e0e40aeaedcf51060ffa
39.501475
226
0.586999
false
false
false
false
TwoRingSoft/SemVer
refs/heads/master
Vendor/Swiftline/SwiftlineTests/SwiftlineTests/AskTests.swift
apache-2.0
1
import Foundation import Quick import Nimble @testable import Swiftline class AskerTest: QuickSpec { override func spec() { var promptPrinter: DummyPromptPrinter! beforeEach { promptPrinter = DummyPromptPrinter() PromptSettings.printer = promptPrinter } it("reads a string from the stdin") { PromptSettings.reader = DummyPromptReader(toReturn: "A String") let res = ask("Enter a string") expect(res).to(equal("A String")) expect(promptPrinter.printed).to(equal("Enter a string\n")) } it("reads an Int from the stdin") { PromptSettings.reader = DummyPromptReader(toReturn: "1") let res = ask("Enter a string", type: Int.self) expect(res).to(equal(1)) expect(promptPrinter.printed).to(equal("Enter a string\n")) } it("keeps asking if entered is not an int") { PromptSettings.reader = DummyPromptReader(toReturn: "x", "y", "1") let res = ask("Enter a string", type: Int.self) let prompt = ["Enter a string", "You must enter a valid Integer.", "? You must enter a valid Integer.", "? "].joinWithSeparator("\n") expect(res).to(equal(1)) expect(promptPrinter.printed).to(equal(prompt)) } it("reads an double from the stdin") { PromptSettings.reader = DummyPromptReader(toReturn: "1") let res = ask("Enter a string", type: Double.self) expect(res).to(equal(1.0)) expect(promptPrinter.printed).to(equal("Enter a string\n")) } it("keeps asking if validation is false") { PromptSettings.reader = DummyPromptReader(toReturn: "1", "2", "3") let res = ask("Enter a string") { s in s.addInvalidCase("Invalid string") { $0 != "3" } } expect(res).to(equal("3")) let prompt = ["Enter a string", "Invalid string", "? Invalid string\n? "].joinWithSeparator("\n") expect(promptPrinter.printed).to(equal(prompt)) } it("ask for confirmation") { PromptSettings.reader = DummyPromptReader(toReturn: "val", "Y") let res = ask("Enter a string") { $0.confirm = true } expect(res).to(equal("val")) expect(promptPrinter.printed).to(equal("Enter a string\nAre you sure? ")) } it("ask for confirmation, if no is passed it keeps asking") { PromptSettings.reader = DummyPromptReader(toReturn: "val", "N", "other val", "y") let res = ask("Enter a string") { $0.confirm = true } expect(res).to(equal("other val")) let prompt = ["Enter a string", "Are you sure? ? Are you sure? "].joinWithSeparator("\n") expect(promptPrinter.printed).to(equal(prompt)) } it("ask for confirmation, and validates input, if no is passed it keeps asking") { PromptSettings.reader = DummyPromptReader(toReturn: "1", "n", "10", "9", "yes") let res = ask("Age?", type: Int.self) { $0.confirm = true $0.addInvalidCase("Age not correct") { $0 == 10 } } expect(res).to(equal(9)) let prompt = ["Age?", "Are you sure? ? Age not correct", "? Are you sure? " ].joinWithSeparator("\n") expect(promptPrinter.printed).to(equal(prompt)) } } }
671d0b51bc274971b1da9dab4a53c279
34.927273
93
0.496711
false
false
false
false
dgollub/pokealmanac
refs/heads/master
PokeAlmanac/PokemonTableCell.swift
mit
1
// // TableCell.swift // PokeAlmanac // // Created by 倉重ゴルプ ダニエル on 2016/04/19. // Copyright © 2016年 Daniel Kurashige-Gollub. All rights reserved. // import Foundation import UIKit public class PokemonTableCell : UITableViewCell { @IBOutlet weak var labelName: UILabel? @IBOutlet weak var thumbnail: UIImageView? @IBOutlet weak var labelInfo: UILabel? public func setPokemonDataJson(pokemonJson: String, thumb: UIImage? = nil) { if let pokemon = Transformer().jsonToPokemonModel(pokemonJson) { setPokemonData(pokemon, thumb: thumb) } else { log("could not load or convert Pokemon for JSON") } } public func setPokemonDataId(pokemonId: Int, thumb: UIImage? = nil) { if let pokemon = Transformer().jsonToPokemonModel(DB().getPokemonJSON(pokemonId)) { setPokemonData(pokemon, thumb: thumb) } else { log("could not load or convert Pokemon for ID \(pokemonId)") } } public func setPokemonData(pokemon: Pokemon, thumb: UIImage? = nil) { labelName!.text = pokemon.name.capitalizedString if let image = thumb { thumbnail!.image = image } else if let image = Downloader().getPokemonSpriteFromCache(pokemon) { thumbnail!.image = image } else { thumbnail!.image = UIImage(named: "IconUnknownPokemon") // TODO(dkg): Should we start downloading the sprite in the background??? // If we do this, we should also queue the downloads somehow! } // TODO(dkg): show more/different info labelInfo!.text = "Height: \(pokemon.height)\nWeight: \(pokemon.weight)" } public func clearCell() { labelName!.text = "" thumbnail!.image = nil labelInfo!.text = "" } }
6a7777df67708f6b1b8a38c915f79175
32.25
91
0.617078
false
false
false
false
johnno1962/eidolon
refs/heads/master
Kiosk/App/Models/Bidder.swift
mit
1
import UIKit import SwiftyJSON final class Bidder: NSObject, JSONAbleType { let id: String let saleID: String var pin: String? init(id: String, saleID: String, pin: String?) { self.id = id self.saleID = saleID self.pin = pin } static func fromJSON(json:[String: AnyObject]) -> Bidder { let json = JSON(json) let id = json["id"].stringValue let saleID = json["sale"]["id"].stringValue let pin = json["pin"].stringValue return Bidder(id: id, saleID: saleID, pin: pin) } }
4dfb67edcd766a60831991835155a41e
23.608696
62
0.59364
false
false
false
false
SergeMaslyakov/audio-player
refs/heads/master
app/src/controllers/music/popover/MusicPickerViewController.swift
apache-2.0
1
// // MusicPickerViewController.swift // AudioPlayer // // Created by Serge Maslyakov on 07/07/2017. // Copyright © 2017 Maslyakov. All rights reserved. // import UIKit import TableKit import Dip import DipUI import SwiftyBeaver import Reusable class MusicPickerViewController: UIViewController, StoryboardSceneBased, Loggable { static let sceneStoryboard = UIStoryboard(name: StoryboardScenes.musicPopoverPicker.rawValue, bundle: nil) var currentMusicState: MusicLibraryState? weak var delegate: MusicPickerViewControllerDelegate? var tableDirector: TableDirector! lazy var animator: MusicPickerAnimator = MusicPickerAnimator() @IBOutlet weak var containerView: UIView! @IBOutlet weak var tableView: UITableView! { didSet { tableDirector = TableDirector(tableView: tableView) installTable() } } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.modalPresentationStyle = UIModalPresentationStyle.custom self.transitioningDelegate = self } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.modalPresentationStyle = UIModalPresentationStyle.custom self.transitioningDelegate = self } override func viewDidLoad() { super.viewDidLoad() } func installTable() { let cellOrder = [ MusicLibraryState.artists, MusicLibraryState.albums, MusicLibraryState.songs, MusicLibraryState.genres, MusicLibraryState.playLists ] let section = TableSection() for state in cellOrder { let row = TableRow<MusicPickerTableViewCell>(item: (state, currentMusicState!)) .on(.click) { [weak self] (options) in guard let strongSelf = self else { return } guard let uDelegate = strongSelf.delegate else { strongSelf.tableDirector.tableView?.deselectRow(at: options.indexPath, animated: true) return } uDelegate.userDidPickMusicController(withState: state, from: self!) } section += row } section.footerHeight = ThemeHeightHelper.MusicPicker.sectionFooterHeight section.headerHeight = ThemeHeightHelper.MusicPicker.sectionHeaderHeight tableDirector += section } } extension MusicPickerViewController: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.presenting = true return animator } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.presenting = false return animator } } extension MusicPickerViewController: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return touch.view == view; } @IBAction func handleTapGestureOnDimmingView(recognizer: UITapGestureRecognizer) { dismiss(animated: true) } }
70d3c4e5946ad768a996dd241ad6d84e
29.920354
177
0.667716
false
false
false
false
qutheory/vapor
refs/heads/main
Sources/Vapor/View/Application+Views.swift
mit
2
extension Application { public var views: Views { .init(application: self) } public var view: ViewRenderer { guard let makeRenderer = self.views.storage.makeRenderer else { fatalError("No renderer configured. Configure with app.views.use(...)") } return makeRenderer(self) } public struct Views { public struct Provider { public static var plaintext: Self { .init { $0.views.use { $0.views.plaintext } } } let run: (Application) -> () public init(_ run: @escaping (Application) -> ()) { self.run = run } } final class Storage { var makeRenderer: ((Application) -> ViewRenderer)? init() { } } struct Key: StorageKey { typealias Value = Storage } let application: Application public var plaintext: PlaintextRenderer { return .init( fileio: self.application.fileio, viewsDirectory: self.application.directory.viewsDirectory, logger: self.application.logger, eventLoopGroup: self.application.eventLoopGroup ) } public func use(_ provider: Provider) { provider.run(self.application) } public func use(_ makeRenderer: @escaping (Application) -> (ViewRenderer)) { self.storage.makeRenderer = makeRenderer } func initialize() { self.application.storage[Key.self] = .init() self.use(.plaintext) } var storage: Storage { guard let storage = self.application.storage[Key.self] else { fatalError("Views not configured. Configure with app.views.initialize()") } return storage } } }
78ae90f6881e60f5cb96886c5f7cef69
27.617647
89
0.527749
false
true
false
false
nekrich/Localize-Swift
refs/heads/master
Sources/Localize.swift
mit
1
// // Localize.swift // Localize // // Created by Roy Marmelstein on 05/08/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation /// Internal current language key let LCLCurrentLanguageKey = "LCLCurrentLanguageKey" /// Default language. English. If English is unavailable defaults to base localization. let LCLDefaultLanguage = "en" /// Base bundle as fallback. let LCLBaseBundle = "Base" /// Name for language change notification public let LCLLanguageChangeNotification = "LCLLanguageChangeNotification" // MARK: Localization Syntax /** Swift 1.x friendly localization syntax, replaces NSLocalizedString - Parameter string: Key to be localized. - Returns: The localized string. */ public func Localized(_ string: String) -> String { return string.localized() } /** Swift 1.x friendly localization syntax with format arguments, replaces String(format:NSLocalizedString) - Parameter string: Key to be localized. - Returns: The formatted localized string with arguments. */ public func Localized(_ string: String, arguments: CVarArg...) -> String { return String(format: string.localized(), arguments: arguments) } /** Swift 1.x friendly plural localization syntax with a format argument - parameter string: String to be formatted - parameter argument: Argument to determine pluralisation - returns: Pluralized localized string. */ public func LocalizedPlural(_ string: String, argument: CVarArg) -> String { return string.localizedPlural(argument) } public extension String { /** Swift 2 friendly localization syntax, replaces NSLocalizedString - Returns: The localized string. */ func localized() -> String { return localized(using: nil, in: .main) } /** Swift 2 friendly localization syntax with format arguments, replaces String(format:NSLocalizedString) - Returns: The formatted localized string with arguments. */ func localizedFormat(_ arguments: CVarArg...) -> String { return String(format: localized(), arguments: arguments) } /** Swift 2 friendly plural localization syntax with a format argument - parameter argument: Argument to determine pluralisation - returns: Pluralized localized string. */ func localizedPlural(_ argument: CVarArg) -> String { return NSString.localizedStringWithFormat(localized() as NSString, argument) as String } } // MARK: Language Setting Functions open class Localize: NSObject { /** List available languages - Returns: Array of available languages. */ open class func availableLanguages(_ excludeBase: Bool = false) -> [String] { var availableLanguages = Bundle.main.localizations // If excludeBase = true, don't include "Base" in available languages if let indexOfBase = availableLanguages.index(of: "Base") , excludeBase == true { availableLanguages.remove(at: indexOfBase) } return availableLanguages } /** Current language - Returns: The current language. String. */ open class func currentLanguage() -> String { if let currentLanguage = UserDefaults.standard.object(forKey: LCLCurrentLanguageKey) as? String { return currentLanguage } return defaultLanguage() } /** Change the current language - Parameter language: Desired language. */ open class func setCurrentLanguage(_ language: String) { let selectedLanguage = availableLanguages().contains(language) ? language : defaultLanguage() if (selectedLanguage != currentLanguage()){ UserDefaults.standard.set(selectedLanguage, forKey: LCLCurrentLanguageKey) UserDefaults.standard.synchronize() NotificationCenter.default.post(name: Notification.Name(rawValue: LCLLanguageChangeNotification), object: nil) } } /** Default language - Returns: The app's default language. String. */ open class func defaultLanguage() -> String { var defaultLanguage: String = String() guard let preferredLanguage = Bundle.main.preferredLocalizations.first else { return LCLDefaultLanguage } let availableLanguages: [String] = self.availableLanguages() if (availableLanguages.contains(preferredLanguage)) { defaultLanguage = preferredLanguage } else { defaultLanguage = LCLDefaultLanguage } return defaultLanguage } /** Resets the current language to the default */ open class func resetCurrentLanguageToDefault() { setCurrentLanguage(self.defaultLanguage()) } /** Get the current language's display name for a language. - Parameter language: Desired language. - Returns: The localized string. */ open class func displayNameForLanguage(_ language: String) -> String { let locale : NSLocale = NSLocale(localeIdentifier: currentLanguage()) if let displayName = (locale as NSLocale).displayName(forKey: NSLocale.Key.languageCode, value: language) { return displayName } return String() } }
d5024f4473adc0d6440dfc2dc98ca0b9
30.54491
122
0.681283
false
false
false
false
jopamer/swift
refs/heads/master
test/SILGen/initializers.swift
apache-2.0
1
// RUN: %target-swift-emit-silgen -enable-sil-ownership -disable-objc-attr-requires-foundation-module -enable-objc-interop %s -module-name failable_initializers | %FileCheck %s // High-level tests that silgen properly emits code for failable and thorwing // initializers. //// // 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() } init?(failBeforeInitialization: ()) { return nil } init?(failAfterPartialInitialization: ()) { x = Canary() return nil } init?(failAfterFullInitialization: ()) { x = Canary() y = Canary() return nil } init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableStruct(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 '!' } // 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() } init?(failBeforeInitialization: ()) { return nil } init?(failAfterPartialInitialization: ()) { x = T() return nil } 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() } 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(throwsToOptionalThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowStruct(noFail: ()) } init(failDuringSelfReplacement: Int) throws { try self = ThrowStruct(fail: ()) } 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 //// //// // Classes with failable initializers //// class FailableBaseClass { var member: Canary init(noFail: ()) { member = Canary() } init?(failBeforeFullInitialization: ()) { return nil } init?(failAfterFullInitialization: ()) { member = Canary() return nil } convenience init?(failBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden @$S21failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfc : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> { // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableBaseClass): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // CHECK: [[TAKE_SELF:%.*]] = load [take] [[PB_BOX]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[TAKE_SELF]]) : $@convention(method) (@owned FailableBaseClass) -> @owned FailableBaseClass // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: br bb2([[RESULT]] : $Optional<FailableBaseClass>) // CHECK: bb2([[RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[RESULT]] // CHECK: } // end sil function '$S21failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfc convenience init?(failAfterDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional // // CHECK-LABEL: sil hidden @$S21failable_initializers17FailableBaseClassC20failDuringDelegationACSgyt_tcfc : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> { // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableBaseClass): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // CHECK: [[TAKE_SELF:%.*]] = load [take] [[PB_BOX]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[TAKE_SELF]]) : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> // CHECK: cond_br {{.*}}, [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB:bb[0-9]+]]: // CHECK: destroy_value [[NEW_SELF]] // CHECK: br [[FAIL_EPILOG_BB:bb[0-9]+]] // // CHECK: [[SUCC_BB]]: // CHECK: [[UNWRAPPED_NEW_SELF:%.*]] = unchecked_enum_data [[NEW_SELF]] : $Optional<FailableBaseClass>, #Optional.some!enumelt.1 // CHECK: store [[UNWRAPPED_NEW_SELF]] to [init] [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt.1, [[RESULT]] // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[FAIL_EPILOG_BB]]: // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: br [[EPILOG_BB]]([[WRAPPED_RESULT]] // // CHECK: [[EPILOG_BB]]([[WRAPPED_RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[WRAPPED_RESULT]] convenience init?(failDuringDelegation: ()) { self.init(failBeforeFullInitialization: ()) } // IUO to optional // // CHECK-LABEL: sil hidden @$S21failable_initializers17FailableBaseClassC21failDuringDelegation2ACSgyt_tcfc : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> { // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableBaseClass): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // CHECK-NEXT: [[TAKE_SELF:%.*]] = load [take] [[PB_BOX]] // CHECK-NOT: [[OLD_SELF]] // CHECK-NOT: copy_value // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[TAKE_SELF]]) : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> // CHECK: switch_enum [[NEW_SELF]] : $Optional<FailableBaseClass>, case #Optional.some!enumelt.1: [[SUCC_BB:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK: unreachable // // CHECK: [[SUCC_BB]]([[RESULT:%.*]] : @owned $FailableBaseClass): // CHECK: store [[RESULT]] to [init] [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt.1, [[RESULT]] : $FailableBaseClass // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[EPILOG_BB]]([[WRAPPED_RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[WRAPPED_RESULT]] // CHECK: } // end sil function '$S21failable_initializers17FailableBaseClassC21failDuringDelegation2ACSgyt_tcfc' 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 @$S21failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> { // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableDerivedClass): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // CHECK-NEXT: br bb1 // // CHECK: bb1: // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2([[RESULT]] // // CHECK: bb2([[RESULT:%.*]] : @owned $Optional<FailableDerivedClass>): // CHECK-NEXT: return [[RESULT]] init?(derivedFailBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden @$S21failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> { // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableDerivedClass): init?(derivedFailDuringDelegation: ()) { // First initialize the lvalue for self. // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // // Then assign canary to other member using a borrow. // CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_BOX]] // CHECK: [[CANARY_VALUE:%.*]] = apply // CHECK: [[CANARY_GEP:%.*]] = ref_element_addr [[BORROWED_SELF]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[CANARY_GEP]] : $*Canary // CHECK: assign [[CANARY_VALUE]] to [[WRITE]] self.otherMember = Canary() // Finally, begin the super init sequence. // CHECK: [[LOADED_SELF:%.*]] = load [take] [[PB_BOX]] // CHECK: [[UPCAST_SELF:%.*]] = upcast [[LOADED_SELF]] // CHECK: [[OPT_NEW_SELF:%.*]] = apply {{.*}}([[UPCAST_SELF]]) : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> // CHECK: [[IS_NIL:%.*]] = select_enum [[OPT_NEW_SELF]] // CHECK: cond_br [[IS_NIL]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // And then return nil making sure that we do not insert any extra values anywhere. // CHECK: [[SUCC_BB]]: // CHECK: [[NEW_SELF:%.*]] = unchecked_enum_data [[OPT_NEW_SELF]] // CHECK: [[DOWNCAST_NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK: store [[DOWNCAST_NEW_SELF]] to [init] [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt.1, [[RESULT]] // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[FAIL_BB]]: // CHECK: destroy_value [[MARKED_SELF_BOX]] 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 {} required init(throwingCanary: Canary) throws {} init(canary: Canary) {} init(noFail: ()) {} init(fail: Int) throws {} init(noFail: Int) {} } class ThrowDerivedClass : ThrowBaseClass { var canary: Canary? required init(throwingCanary: Canary) throws { } required init() throws { try super.init() } override init(noFail: ()) { try! super.init() } override init(fail: Int) throws {} override init(noFail: Int) {} // ---- Delegating to super // CHECK-LABEL: sil hidden @$S21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegationACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Then initialize the canary with nil. We are able to borrow the initialized self to avoid retain/release overhead. // CHECK: [[CANARY_FUNC:%.*]] = function_ref @$S21failable_initializers17ThrowDerivedClassC6canaryAA6CanaryCSgvpfi : // CHECK: [[OPT_CANARY:%.*]] = apply [[CANARY_FUNC]]() // CHECK: [[SELF:%.*]] = load_borrow [[PROJ]] // CHECK: [[CANARY_ADDR:%.*]] = ref_element_addr [[SELF]] // CHECK: [[CANARY_ACCESS:%.*]] = begin_access [modify] [dynamic] [[CANARY_ADDR]] // CHECK: assign [[OPT_CANARY]] to [[CANARY_ACCESS]] // CHECK: end_access [[CANARY_ACCESS]] // CHECK: end_borrow [[SELF]] from [[PROJ]] // // Now we perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S21failable_initializers6unwrapyS2iKF : $@convention(thin) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // CHECK: [[NORMAL_BB]]( // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[SELF_BASE:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[BASE_INIT_FN:%.*]] = function_ref @$S21failable_initializers14ThrowBaseClassC6noFailACyt_tcfc : $@convention(method) // CHECK: [[SELF_INIT_BASE:%.*]] = apply [[BASE_INIT_FN]]([[SELF_BASE]]) // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[SELF_INIT_BASE]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // CHECK: [[SELF:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[SELF]] // // Finally the error BB. We do not touch self since self is still in the // box implying that destroying MARK_UNINIT will destroy it for us. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$S21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegationACSi_tKcfc' init(delegatingFailBeforeDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: ()) } // CHECK-LABEL: sil hidden @$S21failable_initializers17ThrowDerivedClassC41delegatingFailDuringDelegationArgEmissionACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Then initialize the canary with nil. We are able to borrow the initialized self to avoid retain/release overhead. // CHECK: [[CANARY_FUNC:%.*]] = function_ref @$S21failable_initializers17ThrowDerivedClassC6canaryAA6CanaryCSgvpfi : // CHECK: [[OPT_CANARY:%.*]] = apply [[CANARY_FUNC]]() // CHECK: [[SELF:%.*]] = load_borrow [[PROJ]] // CHECK: [[CANARY_ADDR:%.*]] = ref_element_addr [[SELF]] // CHECK: [[CANARY_ACCESS:%.*]] = begin_access [modify] [dynamic] [[CANARY_ADDR]] // CHECK: assign [[OPT_CANARY]] to [[CANARY_ACCESS]] // CHECK: end_access [[CANARY_ACCESS]] // CHECK: end_borrow [[SELF]] from [[PROJ]] // // Now we begin argument emission where we perform the unwrap. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S21failable_initializers6unwrapyS2iKF : $@convention(thin) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Now we emit the call to the initializer. Notice how we return self back to // its memory locatio nbefore any other work is done. // CHECK: [[NORMAL_BB]]( // CHECK: [[INIT_FN:%.*]] = function_ref @$S21failable_initializers14ThrowBaseClassC6noFailACSi_tcfc : $@convention(method) // CHECK: [[BASE_SELF_INIT:%.*]] = apply [[INIT_FN]]({{%.*}}, [[BASE_SELF]]) // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[BASE_SELF_INIT]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // // Handle the return value. // CHECK: [[SELF:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[SELF]] // // When the error is thrown, we need to: // 1. Store self back into the "conceptually" uninitialized box. // 2. destroy the box. // 3. Perform the rethrow. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[BASE_SELF]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$S21failable_initializers17ThrowDerivedClassC41delegatingFailDuringDelegationArgEmissionACSi_tKcfc' init(delegatingFailDuringDelegationArgEmission : Int) throws { super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) } // CHECK-LABEL: sil hidden @$S21failable_initializers17ThrowDerivedClassC34delegatingFailDuringDelegationCallACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Call the initializer. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[INIT_FN:%.*]] = function_ref @$S21failable_initializers14ThrowBaseClassCACyKcfc : $@convention(method) // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) : $@convention(method) (@owned ThrowBaseClass) -> (@owned ThrowBaseClass, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Insert the return statement into the normal block... // CHECK: [[NORMAL_BB]]([[BASE_SELF_INIT:%.*]] : @owned $ThrowBaseClass): // CHECK: [[OUT_SELF:%.*]] = unchecked_ref_cast [[BASE_SELF_INIT]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[OUT_SELF]] to [init] [[PROJ]] // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARK_UNINIT]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$S21failable_initializers17ThrowDerivedClassC34delegatingFailDuringDelegationCallACSi_tKcfc' init(delegatingFailDuringDelegationCall : Int) throws { try super.init() } // CHECK-LABEL: sil hidden @$S21failable_initializers17ThrowDerivedClassC29delegatingFailAfterDelegationACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Call the initializer and then store the new self back into its memory slot. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[INIT_FN:%.*]] = function_ref @$S21failable_initializers14ThrowBaseClassC6noFailACyt_tcfc : $@convention(method) // CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) : $@convention(method) (@owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF_CAST:%.*]] = unchecked_ref_cast [[NEW_SELF]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[NEW_SELF_CAST]] to [init] [[PROJ]] // // Finally perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Insert the return statement into the normal block... // CHECK: [[NORMAL_BB]]( // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARK_UNINIT]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$S21failable_initializers17ThrowDerivedClassC29delegatingFailAfterDelegationACSi_tKcfc' init(delegatingFailAfterDelegation : Int) throws { super.init(noFail: ()) try unwrap(delegatingFailAfterDelegation) } // CHECK-LABEL: sil hidden @$S21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegation0fg6DuringI11ArgEmissionACSi_SitKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // Create our box. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // // Perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[UNWRAP_NORMAL_BB:bb[0-9]+]], error [[UNWRAP_ERROR_BB:bb[0-9]+]] // // Now we begin argument emission where we perform another unwrap. // CHECK: [[UNWRAP_NORMAL_BB]]( // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[SELF_CAST:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[UNWRAP_FN2:%.*]] = function_ref @$S21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error) // CHECK: try_apply [[UNWRAP_FN2]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[UNWRAP_NORMAL_BB2:bb[0-9]+]], error [[UNWRAP_ERROR_BB2:bb[0-9]+]] // // Then since this example has a // CHECK: [[UNWRAP_NORMAL_BB2]]([[INT:%.*]] : @trivial $Int): // CHECK: [[INIT_FN2:%.*]] = function_ref @$S21failable_initializers14ThrowBaseClassC6noFailACSi_tcfc : $@convention(method) (Int, @owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF_CAST:%.*]] = apply [[INIT_FN2]]([[INT]], [[SELF_CAST]]) : $@convention(method) (Int, @owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF_CAST]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[NEW_SELF]] to [init] [[PROJ]] // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[UNWRAP_ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: br [[ERROR_JOIN:bb[0-9]+]]([[ERROR]] // // CHECK: [[UNWRAP_ERROR_BB2]]([[ERROR:%.*]] : @owned $Error): // CHECK: [[SELF_CASTED_BACK:%.*]] = unchecked_ref_cast [[SELF_CAST]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF_CASTED_BACK]] to [init] [[PROJ]] // CHECK: br [[ERROR_JOIN]]([[ERROR]] // // CHECK: [[ERROR_JOIN]]([[ERROR_PHI:%.*]] : @owned $Error): // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR_PHI]] // CHECK: } // end sil function '$S21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegation0fg6DuringI11ArgEmissionACSi_SitKcfc' init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationCall : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init() } init(delegatingFailBeforeDelegation : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: ()) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int) throws { try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailAfterDelegation : Int) throws { super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try super.init() try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init() try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } // ---- Delegating to other self method. convenience init(chainingFailBeforeDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: ()) } convenience init(chainingFailDuringDelegationArgEmission : Int) throws { self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailDuringDelegationCall : Int) throws { try self.init() } convenience init(chainingFailAfterDelegation : Int) throws { self.init(noFail: ()) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationCall : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init() } convenience init(chainingFailBeforeDelegation : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: ()) try unwrap(chainingFailAfterDelegation) } // CHECK-LABEL: sil hidden @$S21failable_initializers17ThrowDerivedClassC39chainingFailDuringDelegationArgEmission0fghI4CallACSi_SitKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0({{.*}}, [[OLD_SELF:%.*]] : @owned $ThrowDerivedClass): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // CHECK: [[MOVE_ONLY_SELF:%.*]] = load [take] [[PB_BOX]] // CHECK: try_apply {{.*}}({{.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[SUCC_BB1:bb[0-9]+]], error [[ERROR_BB1:bb[0-9]+]] // // CHECK: [[SUCC_BB1]]( // CHECK: try_apply {{.*}}({{.*}}, [[MOVE_ONLY_SELF]]) : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error), normal [[SUCC_BB2:bb[0-9]+]], error [[ERROR_BB2:bb[0-9]+]] // // CHECK: [[SUCC_BB2]]([[NEW_SELF:%.*]] : @owned $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [init] [[PB_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: return [[RESULT]] // // CHECK: [[ERROR_BB1]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: store [[MOVE_ONLY_SELF]] to [init] [[PB_BOX]] // CHECK-NEXT: br [[THROWING_BB:bb[0-9]+]]([[ERROR]] // // CHECK: [[ERROR_BB2]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: br [[THROWING_BB]]([[ERROR]] // // CHECK: [[THROWING_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int) throws { try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailAfterDelegation : Int) throws { self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } // CHECK-LABEL: sil hidden @$S21failable_initializers17ThrowDerivedClassC32chainingFailDuringDelegationCall0fg5AfterI0ACSi_SitKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0({{.*}}, [[OLD_SELF:%.*]] : @owned $ThrowDerivedClass): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // CHECK: [[MOVE_ONLY_SELF:%.*]] = load [take] [[PB_BOX]] // CHECK: try_apply {{.*}}([[MOVE_ONLY_SELF]]) : $@convention(method) (@owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error), normal [[SUCC_BB1:bb[0-9]+]], error [[ERROR_BB1:bb[0-9]+]] // // CHECK: [[SUCC_BB1]]([[NEW_SELF:%.*]] : @owned $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [init] [[PB_BOX]] // CHECK-NEXT: // function_ref // CHECK-NEXT: function_ref @ // CHECK-NEXT: try_apply {{.*}}({{.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[SUCC_BB2:bb[0-9]+]], error [[ERROR_BB2:bb[0-9]+]] // // CHECK: [[SUCC_BB2]]( // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: return [[RESULT]] // // CHECK: [[ERROR_BB1]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: br [[THROWING_BB:bb[0-9]+]]([[ERROR]] // // CHECK: [[ERROR_BB2]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: br [[THROWING_BB]]([[ERROR]] // // CHECK: [[THROWING_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$S21failable_initializers17ThrowDerivedClassC28chainingFailBeforeDelegation0fg6DuringI11ArgEmission0fgjI4CallACSi_S2itKcfC' convenience init(chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try self.init() try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init() try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } } //// // 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 '!' } } //// // type(of: self) with uninitialized self //// func use(_ a : Any) {} class DynamicTypeBase { var x: Int init() { use(type(of: self)) x = 0 } convenience init(a : Int) { use(type(of: self)) self.init() } } class DynamicTypeDerived : DynamicTypeBase { override init() { use(type(of: self)) super.init() } convenience init(a : Int) { use(type(of: self)) self.init() } } struct DynamicTypeStruct { var x: Int init() { use(type(of: self)) x = 0 } init(a : Int) { use(type(of: self)) self.init() } } class InOutInitializer { // CHECK-LABEL: sil hidden @$S21failable_initializers16InOutInitializerC1xACSiz_tcfC : $@convention(method) (@inout Int, @thick InOutInitializer.Type) -> @owned InOutInitializer { // CHECK: bb0(%0 : @trivial $*Int, %1 : @trivial $@thick InOutInitializer.Type): init(x: inout Int) {} }
673a494979120e4ce1a6145c549909c8
37.071745
249
0.658097
false
false
false
false
Totopolis/monik.ios
refs/heads/master
sources/monik/MonikLoggerTransport.swift
mit
1
// // MonikLoggerTransport.swift // Pods // // Created by Sergey Pestov on 20/01/2017. // // import Foundation import RMQClient private func debugPrint(_ text: String) { #if DEBUG Swift.print(text) #else #endif } extension MonikLogger { open class Transport: NSObject { init(config: Config, connectedBlock: ((Bool) -> Void)?) { self.config = config self.connectedBlock = connectedBlock super.init() debugPrint("Connect with uri: \(config.uri)") conn = RMQConnection(uri: config.uri, verifyPeer: true, delegate: self) connect() } @objc private func reconnectIfNeeded() { guard !isConnected, !isConnecting else { return } isConnecting = true reconnect() } deinit { disconnect() } private func connect() { conn.start() { self.isConnected = true debugPrint("!!! [CONNECTED] !!!") } let ch = conn.createChannel() ch.confirmSelect() channel = ch let opt: RMQExchangeDeclareOptions = config.durable ? [.durable] : [] exchange = ch.fanout(config.exchange, options: opt) } /// Close and forget. open func disconnect() { conn?.close() conn = nil } open func reconnect() { self.nackCount = 0 disconnect() conn = RMQConnection(uri: config.uri, delegate: self, recoverAfter: NSNumber(value: config.reconnectTimeout)) connect() } open func afterConfirmed(_ handler: @escaping (Set<NSNumber>, Set<NSNumber>) -> Void) { channel.afterConfirmed(NSNumber(value: 0)) { (ack, nack) in handler(ack, nack) guard self.isConnected else { return } if nack.isEmpty { self.nackCount = 0 } else { self.nackCount += 1 if self.nackCount == 3 { // Reconnect if cannot send messages 3 times when connected. self.reconnect() } } } } open func publish(_ data: Data) -> Int? { return exchange.publish(data, routingKey: "", persistent: true )?.intValue } private let config: Config private var conn: RMQConnection! private var exchange: RMQExchange! private var channel: RMQChannel! fileprivate (set) var isConnected = false { didSet { isConnecting = false connectedBlock?(isConnected) } } fileprivate (set) var isConnecting = false private var nackCount = 0 private var timer: Timer? var connectedBlock: ((Bool) -> Void)? } } //open class MonikRMQConnectionDelegate: NSObject, RMQConnectionDelegate { extension MonikLogger.Transport: RMQConnectionDelegate { /// @brief Called when a socket cannot be opened, or when AMQP handshaking times out for some reason. public func connection(_ connection: RMQConnection!, failedToConnectWithError error: Error!) { debugPrint("[DISCONNECTED] Failed to connect with error: \(error)") isConnected = false } /// @brief Called when a connection disconnects for any reason public func connection(_ connection: RMQConnection!, disconnectedWithError error: Error!) { debugPrint("[DISCONNECTED] Disconnected with error: \(error)") isConnected = false } /// @brief Called before the configured <a href="http://www.rabbitmq.com/api-guide.html#recovery">automatic connection recovery</a> sleep. public func willStartRecovery(with connection: RMQConnection!) { debugPrint("[DISCONNECTED] Will start recovery with \(connection)") } /// @brief Called after the configured <a href="http://www.rabbitmq.com/api-guide.html#recovery">automatic connection recovery</a> sleep. public func startingRecovery(with connection: RMQConnection!) { debugPrint("[DISCONNECTED] Starting recovery with \(connection)") } /*! * @brief Called when <a href="http://www.rabbitmq.com/api-guide.html#recovery">automatic connection recovery</a> has succeeded. * @param RMQConnection the connection instance that was recovered. */ public func recoveredConnection(_ connection: RMQConnection!) { debugPrint("[CONNECTED] Recovered connection \(connection)") isConnected = true } /// @brief Called with any channel-level AMQP exception. public func channel(_ channel: RMQChannel!, error: Error!) { debugPrint("[???] Channel exception \(error)") } }
5ce1605d5ebfbcd4943b894bf91a8ceb
30.441176
142
0.534705
false
true
false
false
ArnavChawla/InteliChat
refs/heads/master
Carthage/Checkouts/ios-sdk/Source/AlchemyLanguageV1/Models/Emotions.swift
apache-2.0
3
// // Emotions.swift // WatsonDeveloperCloud // // Created by Harrison Saylor on 5/26/16. // Copyright © 2016 Glenn R. Fisher. All rights reserved. // import Foundation import RestKit /** Emotions and their prevalence extracted from a document */ public struct Emotions: JSONDecodable { /** amount of anger extracted */ public let anger: Double? /** amount of disgust extracted */ public let disgust: Double? /** amount of fear extracted */ public let fear: Double? /** amount of joy extracted */ public let joy: Double? /** amount of sadness extracted */ public let sadness: Double? /// Used internally to initialize a Emotions object public init(json: JSON) throws { if let angerString = try? json.getString(at: "anger") { anger = Double(angerString) } else { anger = nil } if let disgustString = try? json.getString(at: "disgust") { disgust = Double(disgustString) } else { disgust = nil } if let fearString = try? json.getString(at: "fear") { fear = Double(fearString) } else { fear = nil } if let joyString = try? json.getString(at: "joy") { joy = Double(joyString) } else { joy = nil } if let sadnessString = try? json.getString(at: "sadness") { sadness = Double(sadnessString) } else { sadness = nil } } }
1c5149c4af0e954569eaa6d0d4c9afe4
26.6
67
0.567852
false
false
false
false
mikemee/SQLite.swift2
refs/heads/master
SQLite/Core/Connection.swift
mit
1
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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 Dispatch import SQLite3 /// A connection to SQLite. public final class Connection { /// The location of a SQLite database. public enum Location { /// An in-memory database (equivalent to `.URI(":memory:")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#sharedmemdb> case InMemory /// A temporary, file-backed database (equivalent to `.URI("")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#temp_db> case Temporary /// A database located at the given URI filename (or path). /// /// See: <https://www.sqlite.org/uri.html> /// /// - Parameter filename: A URI filename case URI(String) } public var handle: COpaquePointer { return _handle } private var _handle: COpaquePointer = nil /// Initializes a new SQLite connection. /// /// - Parameters: /// /// - location: The location of the database. Creates a new database if it /// doesn’t already exist (unless in read-only mode). /// /// Default: `.InMemory`. /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Returns: A new database connection. public init(_ location: Location = .InMemory, readonly: Bool = false) throws { let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE try check(sqlite3_open_v2(location.description, &_handle, flags | SQLITE_OPEN_FULLMUTEX, nil)) dispatch_queue_set_specific(queue, Connection.queueKey, queueContext, nil) } /// Initializes a new connection to a database. /// /// - Parameters: /// /// - filename: The location of the database. Creates a new database if /// it doesn’t already exist (unless in read-only mode). /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Throws: `Result.Error` iff a connection cannot be established. /// /// - Returns: A new database connection. public convenience init(_ filename: String, readonly: Bool = false) throws { try self.init(.URI(filename), readonly: readonly) } deinit { sqlite3_close(handle) } // MARK: - /// Whether or not the database was opened in a read-only state. public var readonly: Bool { return sqlite3_db_readonly(handle, nil) == 1 } /// The last rowid inserted into the database via this connection. public var lastInsertRowid: Int64? { let rowid = sqlite3_last_insert_rowid(handle) return rowid > 0 ? rowid : nil } /// The last number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var changes: Int { return Int(sqlite3_changes(handle)) } /// The total number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var totalChanges: Int { return Int(sqlite3_total_changes(handle)) } // MARK: - Execute /// Executes a batch of SQL statements. /// /// - Parameter SQL: A batch of zero or more semicolon-separated SQL /// statements. /// /// - Throws: `Result.Error` if query execution fails. public func execute(SQL: String) throws { try sync { try self.check(sqlite3_exec(self.handle, SQL, nil, nil, nil)) } } // MARK: - Prepare /// Prepares a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result public func prepare(statement: String, _ bindings: Binding?...) throws -> Statement { if !bindings.isEmpty { return try prepare(statement, bindings) } return try Statement(self, statement) } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result public func prepare(statement: String, _ bindings: [Binding?]) throws -> Statement { return try prepare(statement).bind(bindings) } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result public func prepare(statement: String, _ bindings: [String: Binding?]) throws -> Statement { return try prepare(statement).bind(bindings) } // MARK: - Run /// Runs a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. public func run(statement: String, _ bindings: Binding?...) throws -> Statement { return try run(statement, bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. public func run(statement: String, _ bindings: [Binding?]) throws -> Statement { return try prepare(statement).run(bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. public func run(statement: String, _ bindings: [String: Binding?]) throws -> Statement { return try prepare(statement).run(bindings) } // MARK: - Scalar /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result public func scalar(statement: String, _ bindings: Binding?...) -> Binding? { return scalar(statement, bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result public func scalar(statement: String, _ bindings: [Binding?]) -> Binding? { return try! prepare(statement).scalar(bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result public func scalar(statement: String, _ bindings: [String: Binding?]) -> Binding? { return try! prepare(statement).scalar(bindings) } // MARK: - Transactions /// The mode in which a transaction acquires a lock. public enum TransactionMode : String { /// Defers locking the database till the first read/write executes. case Deferred = "DEFERRED" /// Immediately acquires a reserved lock on the database. case Immediate = "IMMEDIATE" /// Immediately acquires an exclusive lock on all databases. case Exclusive = "EXCLUSIVE" } // TODO: Consider not requiring a throw to roll back? /// Runs a transaction with the given mode. /// /// - Note: Transactions cannot be nested. To nest transactions, see /// `savepoint()`, instead. /// /// - Parameters: /// /// - mode: The mode in which a transaction acquires a lock. /// /// Default: `.Deferred` /// /// - block: A closure to run SQL statements within the transaction. /// The transaction will be committed when the block returns. The block /// must throw to roll the transaction back. /// /// - Throws: `Result.Error`, and rethrows. public func transaction(mode: TransactionMode = .Deferred, block: () throws -> Void) throws { try transaction("BEGIN \(mode.rawValue) TRANSACTION", block, "COMMIT TRANSACTION", or: "ROLLBACK TRANSACTION") } // TODO: Consider not requiring a throw to roll back? // TODO: Consider removing ability to set a name? /// Runs a transaction with the given savepoint name (if omitted, it will /// generate a UUID). /// /// - SeeAlso: `transaction()`. /// /// - Parameters: /// /// - savepointName: A unique identifier for the savepoint (optional). /// /// - block: A closure to run SQL statements within the transaction. /// The savepoint will be released (committed) when the block returns. /// The block must throw to roll the savepoint back. /// /// - Throws: `SQLite.Result.Error`, and rethrows. public func savepoint(name: String = NSUUID().UUIDString, block: () throws -> Void) throws { let name = name.quote("'") let savepoint = "SAVEPOINT \(name)" try transaction(savepoint, block, "RELEASE \(savepoint)", or: "ROLLBACK TO \(savepoint)") } private func transaction(begin: String, _ block: () throws -> Void, _ commit: String, or rollback: String) throws { return try sync { try self.run(begin) do { try block() } catch { try self.run(rollback) throw error } try self.run(commit) } } /// Interrupts any long-running queries. public func interrupt() { sqlite3_interrupt(handle) } // MARK: - Handlers /// The number of seconds a connection will attempt to retry a statement /// after encountering a busy signal (lock). public var busyTimeout: Double = 0 { didSet { sqlite3_busy_timeout(handle, Int32(busyTimeout * 1_000)) } } /// Sets a handler to call after encountering a busy signal (lock). /// /// - Parameter callback: This block is executed during a lock in which a /// busy error would otherwise be returned. It’s passed the number of /// times it’s been called for this lock. If it returns `true`, it will /// try again. If it returns `false`, no further attempts will be made. public func busyHandler(callback: ((tries: Int) -> Bool)?) { guard let callback = callback else { sqlite3_busy_handler(handle, nil, nil) busyHandler = nil return } let box: BusyHandler = { callback(tries: Int($0)) ? 1 : 0 } sqlite3_busy_handler(handle, { callback, tries in unsafeBitCast(callback, BusyHandler.self)(tries) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) busyHandler = box } private typealias BusyHandler = @convention(block) Int32 -> Int32 private var busyHandler: BusyHandler? /// Sets a handler to call when a statement is executed with the compiled /// SQL. /// /// - Parameter callback: This block is invoked when a statement is executed /// with the compiled SQL as its argument. /// /// db.trace { SQL in print(SQL) } public func trace(callback: (String -> Void)?) { guard let callback = callback else { sqlite3_trace(handle, nil, nil) trace = nil return } let box: Trace = { callback(String.fromCString($0)!) } sqlite3_trace(handle, { callback, SQL in unsafeBitCast(callback, Trace.self)(SQL) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) trace = box } private typealias Trace = @convention(block) UnsafePointer<Int8> -> Void private var trace: Trace? /// Registers a callback to be invoked whenever a row is inserted, updated, /// or deleted in a rowid table. /// /// - Parameter callback: A callback invoked with the `Operation` (one of /// `.Insert`, `.Update`, or `.Delete`), database name, table name, and /// rowid. public func updateHook(callback: ((operation: Operation, db: String, table: String, rowid: Int64) -> Void)?) { guard let callback = callback else { sqlite3_update_hook(handle, nil, nil) updateHook = nil return } let box: UpdateHook = { callback( operation: Operation(rawValue: $0), db: String.fromCString($1)!, table: String.fromCString($2)!, rowid: $3 ) } sqlite3_update_hook(handle, { callback, operation, db, table, rowid in unsafeBitCast(callback, UpdateHook.self)(operation, db, table, rowid) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) updateHook = box } private typealias UpdateHook = @convention(block) (Int32, UnsafePointer<Int8>, UnsafePointer<Int8>, Int64) -> Void private var updateHook: UpdateHook? /// Registers a callback to be invoked whenever a transaction is committed. /// /// - Parameter callback: A callback invoked whenever a transaction is /// committed. If this callback throws, the transaction will be rolled /// back. public func commitHook(callback: (() throws -> Void)?) { guard let callback = callback else { sqlite3_commit_hook(handle, nil, nil) commitHook = nil return } let box: CommitHook = { do { try callback() } catch { return 1 } return 0 } sqlite3_commit_hook(handle, { callback in unsafeBitCast(callback, CommitHook.self)() }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) commitHook = box } private typealias CommitHook = @convention(block) () -> Int32 private var commitHook: CommitHook? /// Registers a callback to be invoked whenever a transaction rolls back. /// /// - Parameter callback: A callback invoked when a transaction is rolled /// back. public func rollbackHook(callback: (() -> Void)?) { guard let callback = callback else { sqlite3_rollback_hook(handle, nil, nil) rollbackHook = nil return } let box: RollbackHook = { callback() } sqlite3_rollback_hook(handle, { callback in unsafeBitCast(callback, RollbackHook.self)() }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) rollbackHook = box } private typealias RollbackHook = @convention(block) () -> Void private var rollbackHook: RollbackHook? /// Creates or redefines a custom SQL function. /// /// - Parameters: /// /// - function: The name of the function to create or redefine. /// /// - argumentCount: The number of arguments that the function takes. If /// `nil`, the function may take any number of arguments. /// /// Default: `nil` /// /// - deterministic: Whether or not the function is deterministic (_i.e._ /// the function always returns the same result for a given input). /// /// Default: `false` /// /// - block: A block of code to run when the function is called. The block /// is called with an array of raw SQL values mapped to the function’s /// parameters and should return a raw SQL value (or nil). public func createFunction(function: String, argumentCount: UInt? = nil, deterministic: Bool = false, _ block: (args: [Binding?]) -> Binding?) { let argc = argumentCount.map { Int($0) } ?? -1 let box: Function = { context, argc, argv in let arguments: [Binding?] = (0..<Int(argc)).map { idx in let value = argv[idx] switch sqlite3_value_type(value) { case SQLITE_BLOB: return Blob(bytes: sqlite3_value_blob(value), length: Int(sqlite3_value_bytes(value))) case SQLITE_FLOAT: return sqlite3_value_double(value) case SQLITE_INTEGER: return sqlite3_value_int64(value) case SQLITE_NULL: return nil case SQLITE_TEXT: return String.fromCString(UnsafePointer(sqlite3_value_text(value)))! case let type: fatalError("unsupported value type: \(type)") } } let result = block(args: arguments) if let result = result as? Blob { sqlite3_result_blob(context, result.bytes, Int32(result.bytes.count), nil) } else if let result = result as? Double { sqlite3_result_double(context, result) } else if let result = result as? Int64 { sqlite3_result_int64(context, result) } else if let result = result as? String { sqlite3_result_text(context, result, Int32(result.characters.count), SQLITE_TRANSIENT) } else if result == nil { sqlite3_result_null(context) } else { fatalError("unsupported result type: \(result)") } } var flags = SQLITE_UTF8 if deterministic { flags |= SQLITE_DETERMINISTIC } sqlite3_create_function_v2(handle, function, Int32(argc), flags, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { context, argc, value in unsafeBitCast(sqlite3_user_data(context), Function.self)(context, argc, value) }, nil, nil, nil) if functions[function] == nil { self.functions[function] = [:] } functions[function]?[argc] = box } private typealias Function = @convention(block) (COpaquePointer, Int32, UnsafeMutablePointer<COpaquePointer>) -> Void private var functions = [String: [Int: Function]]() /// The return type of a collation comparison function. public typealias ComparisonResult = NSComparisonResult /// Defines a new collating sequence. /// /// - Parameters: /// /// - collation: The name of the collation added. /// /// - block: A collation function that takes two strings and returns the /// comparison result. public func createCollation(collation: String, _ block: (lhs: String, rhs: String) -> ComparisonResult) { let box: Collation = { lhs, rhs in Int32(block(lhs: String.fromCString(UnsafePointer<Int8>(lhs))!, rhs: String.fromCString(UnsafePointer<Int8>(rhs))!).rawValue) } try! check(sqlite3_create_collation_v2(handle, collation, SQLITE_UTF8, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { callback, _, lhs, _, rhs in unsafeBitCast(callback, Collation.self)(lhs, rhs) }, nil)) collations[collation] = box } private typealias Collation = @convention(block) (UnsafePointer<Void>, UnsafePointer<Void>) -> Int32 private var collations = [String: Collation]() // MARK: - Error Handling func sync<T>(block: () throws -> T) rethrows -> T { var success: T? var failure: ErrorType? let box: () -> Void = { do { success = try block() } catch { failure = error } } if dispatch_get_specific(Connection.queueKey) == queueContext { box() } else { dispatch_sync(queue, box) // FIXME: rdar://problem/21389236 } if let failure = failure { try { () -> Void in throw failure }() } return success! } func check(resultCode: Int32, statement: Statement? = nil) throws -> Int32 { guard let error = Result(errorCode: resultCode, connection: self, statement: statement) else { return resultCode } throw error } private var queue = dispatch_queue_create("SQLite.Database", DISPATCH_QUEUE_SERIAL) private static let queueKey = unsafeBitCast(Connection.self, UnsafePointer<Void>.self) private lazy var queueContext: UnsafeMutablePointer<Void> = unsafeBitCast(self, UnsafeMutablePointer<Void>.self) } extension Connection : CustomStringConvertible { public var description: String { return String.fromCString(sqlite3_db_filename(handle, nil))! } } extension Connection.Location : CustomStringConvertible { public var description: String { switch self { case .InMemory: return ":memory:" case .Temporary: return "" case .URI(let URI): return URI } } } /// An SQL operation passed to update callbacks. public enum Operation { /// An INSERT operation. case Insert /// An UPDATE operation. case Update /// A DELETE operation. case Delete private init(rawValue: Int32) { switch rawValue { case SQLITE_INSERT: self = .Insert case SQLITE_UPDATE: self = .Update case SQLITE_DELETE: self = .Delete default: fatalError("unhandled operation code: \(rawValue)") } } } public enum Result : ErrorType { private static let successCodes: Set = [SQLITE_OK, SQLITE_ROW, SQLITE_DONE] case Error(message: String, code: Int32, statement: Statement?) init?(errorCode: Int32, connection: Connection, statement: Statement? = nil) { guard !Result.successCodes.contains(errorCode) else { return nil } let message = String.fromCString(sqlite3_errmsg(connection.handle))! self = Error(message: message, code: errorCode, statement: statement) } } extension Result : CustomStringConvertible { public var description: String { switch self { case let .Error(message, _, statement): guard let statement = statement else { return message } return "\(message) (\(statement))" } } }
09cb6bbf67c561cc0bdd6f5fad732a0f
34.642336
161
0.605734
false
false
false
false
russbishop/swift
refs/heads/master
test/Constraints/function.swift
apache-2.0
1
// RUN: %target-parse-verify-swift func f0(_ x: Float) -> Float {} func f1(_ x: Float) -> Float {} func f2(_ x: @autoclosure () -> Float) {} var f : Float _ = f0(f0(f)) _ = f0(1) _ = f1(f1(f)) f2(f) f2(1.0) func call_lvalue(_ rhs: @autoclosure () -> Bool) -> Bool { return rhs() } // Function returns func weirdCast<T, U>(_ x: T) -> U {} func ff() -> (Int) -> (Float) { return weirdCast } // Block <-> function conversions var funct: (Int) -> Int = { $0 } var block: @convention(block) (Int) -> Int = funct funct = block block = funct // Application of implicitly unwrapped optional functions var optFunc: ((String) -> String)! = { $0 } var s: String = optFunc("hi") // <rdar://problem/17652759> Default arguments cause crash with tuple permutation func testArgumentShuffle(_ first: Int = 7, third: Int = 9) { } testArgumentShuffle(third: 1, 2) // expected-error {{unnamed parameter #1 must precede argument 'third'}} {{21-29=2}} {{31-32=third: 1}} func rejectsAssertStringLiteral() { assert("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}} precondition("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}} } // <rdar://problem/22243469> QoI: Poor error message with throws, default arguments, & overloads func process(_ line: UInt = #line, _ fn: () -> Void) {} func process(_ line: UInt = #line) -> Int { return 0 } func dangerous() throws {} func test() { process { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'}} try dangerous() test() } } // <rdar://problem/19962010> QoI: argument label mismatches produce not-great diagnostic class A { func a(_ text:String) { } func a(_ text:String, something:Int?=nil) { } } A().a(text:"sometext") // expected-error{{extraneous argument label 'text:' in call}}{{7-12=}} // <rdar://problem/22451001> QoI: incorrect diagnostic when argument to print has the wrong type func r22451001() -> AnyObject {} print(r22451001(5)) // expected-error {{argument passed to call that takes no arguments}} // SR-590 Passing two parameters to a function that takes one argument of type Any crashes the compiler // SR-1028: Segmentation Fault: 11 when superclass init takes parameter of type 'Any' func sr590(_ x: Any) {} sr590(3,4) // expected-error {{extra argument in call}} sr590() // expected-error {{missing argument for parameter #1 in call}} // Make sure calling with structural tuples still works. sr590(()) sr590((1, 2))
4ce559989f6c1b64b0785b317ea2a8d9
29.541176
152
0.66641
false
false
false
false
blg-andreasbraun/Operations
refs/heads/development
Sources/Cloud/CKModifyRecordZonesOperation.swift
mit
2
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import CloudKit /// A generic protocol which exposes the properties used by Apple's CKModifyRecordZonesOperation. public protocol CKModifyRecordZonesOperationProtocol: CKDatabaseOperationProtocol { /// - returns: the record zones to save var recordZonesToSave: [RecordZone]? { get set } /// - returns: the record zone IDs to delete var recordZoneIDsToDelete: [RecordZoneID]? { get set } /// - returns: the modify record zones completion block var modifyRecordZonesCompletionBlock: (([RecordZone]?, [RecordZoneID]?, Error?) -> Void)? { get set } } public struct ModifyRecordZonesError<RecordZone, RecordZoneID>: CloudKitError, CloudKitBatchModifyError { public let underlyingError: Error public let saved: [RecordZone]? public let deleted: [RecordZoneID]? } extension CKModifyRecordZonesOperation: CKModifyRecordZonesOperationProtocol, AssociatedErrorProtocol { // The associated error type public typealias AssociatedError = ModifyRecordZonesError<RecordZone, RecordZoneID> } extension CKProcedure where T: CKModifyRecordZonesOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError { public var recordZonesToSave: [T.RecordZone]? { get { return operation.recordZonesToSave } set { operation.recordZonesToSave = newValue } } public var recordZoneIDsToDelete: [T.RecordZoneID]? { get { return operation.recordZoneIDsToDelete } set { operation.recordZoneIDsToDelete = newValue } } func setModifyRecordZonesCompletionBlock(_ block: @escaping CloudKitProcedure<T>.ModifyRecordZonesCompletionBlock) { operation.modifyRecordZonesCompletionBlock = { [weak self] saved, deleted, error in if let strongSelf = self, let error = error { strongSelf.append(fatalError: ModifyRecordZonesError(underlyingError: error, saved: saved, deleted: deleted)) } else { block(saved, deleted) } } } } extension CloudKitProcedure where T: CKModifyRecordZonesOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError { internal typealias ModifyRecordZonesCompletion = ([T.RecordZone]?, [T.RecordZoneID]?) /// A typealias for the block types used by CloudKitOperation<CKModifyRecordZonesOperation> public typealias ModifyRecordZonesCompletionBlock = ([T.RecordZone]?, [T.RecordZoneID]?) -> Void /// - returns: the record zones to save public var recordZonesToSave: [T.RecordZone]? { get { return current.recordZonesToSave } set { current.recordZonesToSave = newValue appendConfigureBlock { $0.recordZonesToSave = newValue } } } /// - returns: the record zone IDs to delete public var recordZoneIDsToDelete: [T.RecordZoneID]? { get { return current.recordZoneIDsToDelete } set { current.recordZoneIDsToDelete = newValue appendConfigureBlock { $0.recordZoneIDsToDelete = newValue } } } /** Before adding the CloudKitOperation instance to a queue, set a completion block to collect the results in the successful case. Setting this completion block also ensures that error handling gets triggered. - parameter block: a ModifyRecordZonesCompletionBlock block */ public func setModifyRecordZonesCompletionBlock(block: @escaping ModifyRecordZonesCompletionBlock) { appendConfigureBlock { $0.setModifyRecordZonesCompletionBlock(block) } } }
17a7a4758244610e2e296e34ab851452
37.553191
137
0.716887
false
false
false
false
jinseokpark6/u-team
refs/heads/master
Code/Controllers/ExistingEventViewController.swift
apache-2.0
1
// // ExistingEventViewController.swift // Layer-Parse-iOS-Swift-Example // // Created by Jin Seok Park on 2015. 8. 27.. // Copyright (c) 2015년 layer. All rights reserved. // import UIKit var needReload = false class ExistingEventViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var resultsTable: UITableView! override func viewDidLoad() { super.viewDidLoad() self.resultsTable.tableFooterView = UIView(frame: CGRectZero) // if status == "Coach" { let title = NSLocalizedString("Edit", comment: "") let detailsItem = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("editButtonTapped")) self.navigationItem.setRightBarButtonItem(detailsItem, animated: false) // } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { if needReload { let query = PFQuery(className:"Schedule") query.whereKey("objectId", equalTo:selectedEvent[0].objectId!) query.getFirstObjectInBackgroundWithBlock { (object, error) -> Void in if error == nil { selectedEvent.removeAll(keepCapacity: false) selectedEvent.append(object!) self.resultsTable.reloadData() } } } } func editButtonTapped() { isEditing = true let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let controller = storyboard.instantiateViewControllerWithIdentifier("NewEventVC") as! NewEventVC let nav: UINavigationController = UINavigationController() nav.addChildViewController(controller) self.presentViewController(nav, animated: true, completion: nil) } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 0 { return 175 } if indexPath.section == 1 { return 50 } if indexPath.section == 2 { return UITableViewAutomaticDimension } else { return 30 } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { // if status == "Coach" { return 6 // } // if status == "Player" { // return 4 // } // else { // return 1 // } } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "" } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! existingEventCell if indexPath.section == 0 { cell.titleLabel.text = selectedEvent[0].objectForKey("Title") as? String let startDate = selectedEvent[0].objectForKey("startTime") as! NSDate let endDate = selectedEvent[0].objectForKey("endTime") as! NSDate let dateFormatter1 = NSDateFormatter() let dateFormatter2 = NSDateFormatter() dateFormatter1.dateStyle = NSDateFormatterStyle.MediumStyle dateFormatter2.timeStyle = NSDateFormatterStyle.ShortStyle let date1 = dateFormatter1.stringFromDate(startDate) let date2 = dateFormatter1.stringFromDate(endDate) let startTime = dateFormatter2.stringFromDate(startDate) let endTime = dateFormatter2.stringFromDate(endDate) if date1 == date2 { cell.dateLabel.text = "\(date1)" } else { cell.dateLabel.text = "\(date1) to \(date2)" } cell.timeLabel.text = "\(startTime) to \(endTime)" cell.selectionStyle = UITableViewCellSelectionStyle.None; } if indexPath.section == 1 { if let location = selectedEvent[0].objectForKey("Location") as? String { cell.textLabel!.text = "Location" cell.locationLabel.text = "\(location)" } else { cell.locationLabel.text = "Location" } cell.selectionStyle = UITableViewCellSelectionStyle.None; } if indexPath.section == 2 { if let note = selectedEvent[0].objectForKey("Description") as? String { cell.titleLabel.text = "Notes" cell.dateLabel.text = "\(note)" } else { cell.textLabel!.text = "Notes" } } if indexPath.section == 3 { cell.titleLabel.text = "Participants" var nameLabel = "" if let participants = selectedEvent[0].objectForKey("Participants") as? [String] { if eventParticipantArray.count != 0 { eventParticipantIdArray.removeAll(keepCapacity: false) eventParticipantArray.removeAll(keepCapacity: false) } eventParticipantIdArray = participants for var i=0; i<eventParticipantIdArray.count; i++ { let query = PFUser.query() let object = query?.getObjectWithId(eventParticipantIdArray[i]) as? PFUser eventParticipantArray.append(object) } for var i=0; i<eventParticipantArray.count; i++ { if i != eventParticipantArray.count - 1 { nameLabel += eventParticipantArray[i]?.objectForKey("firstName") as! String + ", " } else { nameLabel += eventParticipantArray[i]?.objectForKey("firstName") as! String } } } cell.dateLabel.text = nameLabel } if indexPath.section == 4 { cell.textLabel?.textAlignment = NSTextAlignment.Center cell.textLabel!.text = "Notify Participants" cell.textLabel?.textColor = UIColor.blueColor() } if indexPath.section == 5 { cell.textLabel?.textAlignment = NSTextAlignment.Center cell.textLabel!.text = "Delete Event" cell.textLabel?.textColor = UIColor.redColor() } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.section == 2 { // if status == "Coach" { // // } // // if status == "Player" { let infoAlert = UIAlertController(title: "Add Notes", message: "Please Type Notes", preferredStyle: UIAlertControllerStyle.Alert) infoAlert.addTextFieldWithConfigurationHandler { (textField:UITextField!) -> Void in textField.placeholder = "Notes" } infoAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action:UIAlertAction!) -> Void in let noteTF = infoAlert.textFields?.first if let noteTF = noteTF { let note = noteTF.text if note != "" { let query = PFQuery(className:"Schedule") print(selectedEvent[0].objectId!) query.getObjectInBackgroundWithId(selectedEvent[0].objectId!, block: { (pfObject, error) -> Void in print("object: \(pfObject)") if error == nil { let currentUser = PFUser.currentUser() let first = currentUser?.objectForKey("firstName") as! String let last = currentUser?.objectForKey("lastName") as! String if let oldNote = pfObject!.objectForKey("Description") as? String { let newNote = "\(oldNote)" + "\r\n" + "\(first) \(last) - \(note)" pfObject!["Description"] = newNote } else { pfObject!["Description"] = note } pfObject!.saveInBackgroundWithBlock { (success:Bool, error:NSError?) -> Void in if error == nil { let currentUser = PFUser.currentUser() let firstName = currentUser?.objectForKey("firstName") as! String let lastName = currentUser?.objectForKey("lastName") as! String let title = selectedEvent[0].objectForKey("Title") as! String let date = selectedEvent[0].createdAt! let announcement = PFObject(className: "Team_Announcement") announcement["name"] = "\(firstName) \(lastName)" announcement["type"] = "Add Note" announcement["title"] = title announcement["date"] = date announcement["eventId"] = selectedEvent[0].objectId! announcement["teamId"] = selectedTeamId announcement.saveInBackgroundWithBlock({ (success, error) -> Void in if error == nil { self.resultsTable.reloadData() } }) } } } }) } } })) infoAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action:UIAlertAction!) -> Void in })) self.presentViewController(infoAlert, animated: true, completion: nil) // } } if indexPath.section == 3 { isEvent = true isAllUsers = false eventParticipantArray.removeAll(keepCapacity: false) let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let controller = storyboard.instantiateViewControllerWithIdentifier("ConversationDetailVC") as! ConversationDetailVC self.navigationController?.pushViewController(controller, animated: true) } if indexPath.section == 4 { let infoAlert = UIAlertController(title: "Notification", message: "Do you want to notify players of this event?", preferredStyle: UIAlertControllerStyle.Alert) infoAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action:UIAlertAction!) -> Void in let teamName = selectedTeamObject[0].objectForKey("name") as! String print("PARTICIPANTS: \(eventParticipantIdArray)") for var i=0; i<eventParticipantIdArray.count; i++ { let uQuery:PFQuery = PFUser.query()! uQuery.whereKey("objectId", equalTo: eventParticipantIdArray[i]) let pushQuery:PFQuery = PFInstallation.query()! pushQuery.whereKey("user", matchesQuery: uQuery) let startDate = selectedEvent[0].objectForKey("startTime") as! NSDate let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "EEE, MMM d, h:mm a" let date = dateFormatter.stringFromDate(startDate) let data = ["alert" : "\(selectedTeamName) Schedule Notification for \(date)" ,"sound" : "notification_sound.caf"] let push:PFPush = PFPush() push.setQuery(pushQuery) push.setData(data) push.sendPushInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in if (error == nil) { print("push sent") } else { print("Error sending push: \(error!.description)."); } }) } })) infoAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action:UIAlertAction!) -> Void in })) self.presentViewController(infoAlert, animated: true, completion: nil) } if indexPath.section == 5 { let infoAlert = UIAlertController(title: "Delete Event", message: "Are you sure you want to delete this event?", preferredStyle: UIAlertControllerStyle.Alert) infoAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action:UIAlertAction!) -> Void in let query = PFQuery(className:"Schedule") query.whereKey("objectId", equalTo: selectedEvent[0].objectId!) query.whereKey("teamId", equalTo: selectedTeamId) query.getFirstObjectInBackgroundWithBlock({ (object:PFObject?, error:NSError?) -> Void in object!.delete() print("deleted") self.dismissViewControllerAnimated(true, completion: nil) }) })) infoAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action:UIAlertAction!) -> Void in })) self.presentViewController(infoAlert, animated: true, completion: nil) } } @IBAction func cancelBtn_click(sender: AnyObject) { noteText = "" self.dismissViewControllerAnimated(true, completion: nil) } /* // 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. } */ }
77ecebc38479ded610873926ee14ec5c
29.776842
163
0.557083
false
false
false
false
RemyDCF/tpg-offline
refs/heads/master
tpg offline/Departures/Cells/StopsTableViewCell.swift
mit
1
// // StopsTableViewself.swift // tpgoffline // // Created by Rémy Da Costa Faro on 29/06/2017. // Copyright © 2018 Rémy Da Costa Faro DA COSTA FARO. All rights reserved. // import UIKit class StopsTableViewCell: UITableViewCell { var stop: Stop? var isFavorite: Bool = false var isNearestStops: Bool = false func configure(with stop: Stop) { self.stop = stop self.accessoryType = .disclosureIndicator self.backgroundColor = .white if App.darkMode { self.backgroundColor = App.cellBackgroundColor let selectedView = UIView() selectedView.backgroundColor = .black self.selectedBackgroundView = selectedView } else { self.backgroundColor = App.cellBackgroundColor let selectedView = UIView() selectedView.backgroundColor = UIColor.white.darken(by: 0.1) self.selectedBackgroundView = selectedView } let titleAttributes: [NSAttributedString.Key: Any] let subtitleAttributes: [NSAttributedString.Key: Any] let headlineFont = UIFont.preferredFont(forTextStyle: .headline) let subheadlineFont = UIFont.preferredFont(forTextStyle: .subheadline) if stop.subTitle != "", !isNearestStops { titleAttributes = [NSAttributedString.Key.font: subheadlineFont, NSAttributedString.Key.foregroundColor: App.textColor] as [NSAttributedString.Key: Any] subtitleAttributes = [NSAttributedString.Key.font: headlineFont, NSAttributedString.Key.foregroundColor: App.textColor] as [NSAttributedString.Key: Any] } else { titleAttributes = [NSAttributedString.Key.font: headlineFont, NSAttributedString.Key.foregroundColor: App.textColor] as [NSAttributedString.Key: Any] subtitleAttributes = [NSAttributedString.Key.font: subheadlineFont, NSAttributedString.Key.foregroundColor: App.textColor] as [NSAttributedString.Key: Any] } self.textLabel?.numberOfLines = 0 self.detailTextLabel?.numberOfLines = 0 self.textLabel?.attributedText = NSAttributedString(string: stop.title, attributes: titleAttributes) self.detailTextLabel?.attributedText = NSAttributedString(string: stop.subTitle, attributes: subtitleAttributes) if isNearestStops { self.textLabel?.attributedText = NSAttributedString(string: stop.name, attributes: titleAttributes) let walkDuration = Int(stop.distance / 1000 / 5 * 60) let walkDurationString = Text.distance(meters: stop.distance, minutes: walkDuration) self.detailTextLabel?.attributedText = NSAttributedString(string: walkDurationString, attributes: subtitleAttributes) self.detailTextLabel?.accessibilityLabel = walkDuration == 0 ? String(format: "%@m".localized, "\(Int(stop.distance))"): String(format: "%@ meters, about %@ minutes to walk".localized, "\(Int(stop.distance))", "\(walkDuration)") } } }
5274fd8cf36248747d5a7626d67c0fbc
37.573171
82
0.6595
false
false
false
false
BalestraPatrick/Tweetometer
refs/heads/develop
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/ViewControllers/StoryboardViewController.swift
apache-2.0
4
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class StoryboardViewController: UIViewController, ListAdapterDataSource, StoryboardLabelSectionControllerDelegate { @IBOutlet weak var collectionView: UICollectionView! lazy var adapter: ListAdapter = { return ListAdapter(updater: ListAdapterUpdater(), viewController: self) }() lazy var people = [ Person(pk: 1, name: "Littlefinger"), Person(pk: 2, name: "Tommen Baratheon"), Person(pk: 3, name: "Roose Bolton"), Person(pk: 4, name: "Brienne of Tarth"), Person(pk: 5, name: "Bronn"), Person(pk: 6, name: "Gilly"), Person(pk: 7, name: "Theon Greyjoy"), Person(pk: 8, name: "Jaqen H'ghar"), Person(pk: 9, name: "Cersei Lannister"), Person(pk: 10, name: "Jaime Lannister"), Person(pk: 11, name: "Tyrion Lannister"), Person(pk: 12, name: "Melisandre"), Person(pk: 13, name: "Missandei"), Person(pk: 14, name: "Jorah Mormont"), Person(pk: 15, name: "Khal Moro"), Person(pk: 16, name: "Daario Naharis"), Person(pk: 17, name: "Jon Snow"), Person(pk: 18, name: "Arya Stark"), Person(pk: 19, name: "Bran Stark"), Person(pk: 20, name: "Sansa Stark"), Person(pk: 21, name: "Daenerys Targaryen"), Person(pk: 22, name: "Samwell Tarly"), Person(pk: 23, name: "Tormund"), Person(pk: 24, name: "Margaery Tyrell"), Person(pk: 25, name: "Varys"), Person(pk: 26, name: "Renly Baratheon"), Person(pk: 27, name: "Joffrey Baratheon"), Person(pk: 28, name: "Stannis Baratheon"), Person(pk: 29, name: "Hodor"), Person(pk: 30, name: "Tywin Lannister"), Person(pk: 31, name: "The Hound"), Person(pk: 32, name: "Ramsay Bolton") ] override func viewDidLoad() { super.viewDidLoad() adapter.collectionView = collectionView adapter.dataSource = self } // MARK: ListAdapterDataSource func objects(for listAdapter: ListAdapter) -> [ListDiffable] { return people } func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController { let sectionController = StoryboardLabelSectionController() sectionController.delegate = self return sectionController } func emptyView(for listAdapter: ListAdapter) -> UIView? { return nil } func removeSectionControllerWantsRemoved(_ sectionController: StoryboardLabelSectionController) { let section = adapter.section(for: sectionController) people.remove(at: Int(section)) adapter.performUpdates(animated: true) } }
8298ee5e5f0a3496496d5c0db5a8d55c
38.255814
121
0.655213
false
false
false
false
charles-oder/Project-Euler-Swift
refs/heads/master
ProjectEulerSwift/Fibonacci.swift
apache-2.0
1
// // Fibonacci.swift // ProjectEulerSwift // // Created by Charles Oder on 4/2/15. // Copyright (c) 2015 Charles Oder. All rights reserved. // import Foundation public class Fibonacci { public var count: Int public var max: Int convenience init(){ self.init(count: Int.max) } init(count: Int) { self.count = count self.max = Int.max } public func getSequence() -> [Int]{ var output: [Int] = [] var lastTwo = [0, 1] var currentValue = lastTwo[1] while (output.count < count && currentValue <= max) { output.append(currentValue) lastTwo[0] = lastTwo[1] lastTwo[1] = currentValue currentValue = lastTwo[0] + lastTwo[1] } return output } }
f3299ee80bde340bcb696e3111d4ac70
21.027027
61
0.54914
false
false
false
false
hyp/NUIGExam
refs/heads/master
NUIGExam/KeychainService.swift
mit
1
// A service used to store and retrieve the login information import Foundation let userAccount = "NUIGExams" class KeychainService { class func save(service: String, _ value: String) { var data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! var request = NSMutableDictionary() request.setValue(kSecClassGenericPassword, forKey: kSecClass) request.setValue(service, forKey: kSecAttrService) request.setValue(userAccount, forKey: kSecAttrAccount) request.setValue(data, forKey: kSecValueData) SecItemDelete(request as CFDictionaryRef) let _ = SecItemAdd(request as CFDictionaryRef, nil) } class func load(service: String) -> String? { var request = NSMutableDictionary() request.setValue(kSecClassGenericPassword, forKey: kSecClass) request.setValue(service, forKey: kSecAttrService) request.setValue(userAccount, forKey: kSecAttrAccount) request.setValue(kCFBooleanTrue, forKey: kSecReturnData) request.setValue(kSecMatchLimitOne, forKey: kSecMatchLimit) var result: Unmanaged<AnyObject>? = nil let status = SecItemCopyMatching(request, &result) if status == errSecSuccess { if let op = result?.toOpaque() { let retrievedData = Unmanaged<NSData>.fromOpaque(op).takeUnretainedValue() return NSString(data: retrievedData, encoding: NSUTF8StringEncoding) } } return nil } }
8e6688f5d53140ed58fb8dfb4828455b
36.439024
94
0.688396
false
false
false
false
dclelland/AudioKit
refs/heads/master
AudioKit/Common/MIDI/Enums/AKMIDIStatus.swift
mit
3
// // AKMIDIStatus.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // /// Potential MIDI Status messages /// /// - NoteOff: /// something resembling a keyboard key release /// - NoteOn: /// triggered when a new note is created, or a keyboard key press /// - PolyphonicAftertouch: /// rare MIDI control on controllers in which every key has separate touch sensing /// - ControllerChange: /// wide range of control types including volume, expression, modulation /// and a host of unnamed controllers with numbers /// - ProgramChange: /// messages are associated with changing the basic character of the sound preset /// - ChannelAftertouch: /// single aftertouch for all notes on a given channel (most common aftertouch type in keyboards) /// - PitchWheel: /// common keyboard control that allow for a pitch to be bent up or down a given number of semitones /// - SystemCommand: /// differ from system to system /// public enum AKMIDIStatus: Int { /// Note off is something resembling a keyboard key release case NoteOff = 8 /// Note on is triggered when a new note is created, or a keyboard key press case NoteOn = 9 /// Polyphonic aftertouch is a rare MIDI control on controllers in which /// every key has separate touch sensing case PolyphonicAftertouch = 10 /// Controller changes represent a wide range of control types including volume, /// expression, modulation and a host of unnamed controllers with numbers case ControllerChange = 11 /// Program change messages are associated with changing the basic character of the sound preset case ProgramChange = 12 /// A single aftertouch for all notes on a given channel /// (most common aftertouch type in keyboards) case ChannelAftertouch = 13 /// A pitch wheel is a common keyboard control that allow for a pitch to be /// bent up or down a given number of semitones case PitchWheel = 14 /// System commands differ from system to system case SystemCommand = 15 }
d13dc0fe3ef2205b9d54ce756ddfdadd
40.54902
103
0.714353
false
false
false
false
aleksei-z/Delivery
refs/heads/master
Tests/KeyboardParametersTests.swift
mit
1
// // KeyboardParametersTests.swift // // Copyright (c) 2018 Aleksei Zaikin // // 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. // @testable import Delivery import XCTest final class KeyboardParametersTests: XCTestCase { func testAccessorsReturnNotificationValues() { let frameBegin = CGRect(origin: .zero, size: CGSize(width: 100.0, height: 100.0)) let frameEnd = CGRect(origin: .zero, size: CGSize(width: 100.0, height: 100.0)) let userInfo: [AnyHashable: Any] = [ UIResponder.keyboardFrameBeginUserInfoKey: NSValue(cgRect: frameBegin), UIResponder.keyboardFrameEndUserInfoKey: NSValue(cgRect: frameEnd), UIResponder.keyboardAnimationDurationUserInfoKey: NSNumber(value: 0.3), UIResponder.keyboardAnimationCurveUserInfoKey: NSNumber(value: UIView.AnimationOptions.curveEaseIn.rawValue) ] let note = Notification(name: UIResponder.keyboardWillShowNotification, object: nil, userInfo: userInfo) let parameters = KeyboardParameters(note: note) XCTAssertEqual(parameters.frameBegin, frameBegin) XCTAssertEqual(parameters.frameEnd, frameEnd) XCTAssertTrue(abs(parameters.duration - 0.3) < 0.0001) XCTAssertEqual(parameters.curve, .curveEaseIn) XCTAssertEqual(parameters.frameBeginConverted(for: UIView()), frameBegin) XCTAssertEqual(parameters.frameEndConverted(for: UIView()), frameEnd) } func testAccessorsReturnDefaultValues() { let parameters = KeyboardParameters(note: Notification(name: UIResponder.keyboardWillChangeFrameNotification)) XCTAssertEqual(parameters.frameBegin, .zero) XCTAssertEqual(parameters.frameEnd, .zero) XCTAssertTrue(abs(parameters.duration - 0.25) < 0.0001) XCTAssertEqual(parameters.curve, .curveEaseInOut) XCTAssertEqual(parameters.frameBeginConverted(for: UIView()), .zero) XCTAssertEqual(parameters.frameEndConverted(for: UIView()), .zero) } }
211c1883671f320b869d8cffb9408ac8
49.583333
120
0.73575
false
true
false
false
Incipia/Conduction
refs/heads/master
Conduction/Classes/ConductionResource.swift
mit
1
// // ConductionResource.swift // Bindable // // Created by Leif Meyer on 11/16/17. // import Foundation public enum ConductionResourceState<Parameter, Input, Resource> { case empty case fetching(id: ConductionResourceTaskID, priority: Int?, parameter: Parameter?) case processing(id: ConductionResourceTaskID, priority: Int?, input: Input?) case fetched(Resource?) case invalid(Resource?) // MARK: - Public Properties public var priority: Int? { switch self { case .fetching(_, let priority, _): return priority case .processing(_, let priority, _): return priority default: return nil } } public var parameter: Parameter? { switch self { case .fetching(_, _, let parameter): return parameter default: return nil } } public var input: Input? { switch self { case .processing(_, _, let input): return input default: return nil } } public var resource: Resource? { switch self { case .fetched(let resource): return resource default: return nil } } } public typealias ConductionResourceObserver = UUID public typealias ConductionResourceTaskID = UUID public typealias ConductionResourceFetchBlock<Parameter, Input> = (_ parameter: Parameter?, _ priority: Int?, _ completion: @escaping (_ fetchedInput: Input?) -> Void) -> Void public typealias ConductionResourceTransformBlock<Input, Resource> = (_ input: Input?, _ priority: Int?, _ completion: @escaping (_ resource: Resource?) -> Void) -> Void public typealias ConductionResourceCommitBlock<Parameter, Input, Resource> = (_ state: ConductionResourceState<Parameter, Input, Resource>, _ nextState: ConductionResourceState<Parameter, Input, Resource>) -> ConductionResourceState<Parameter, Input, Resource>? public typealias ConductionResourceObserverBlock<Resource> = (_ resource: Resource?) -> Void fileprivate typealias ConductionResourceObserverEntry<Resource> = (id: ConductionResourceObserver, priority: Int, block: ConductionResourceObserverBlock<Resource>) open class ConductionBaseResource<Parameter, Input, Resource> { // MARK: - Private Properties private var _getBlocks: [ConductionResourceObserverEntry<Resource>] = [] private var _observerBlocks: [ConductionResourceObserverEntry<Resource>] = [] private var _stateObserverBlocks: [(id: ConductionResourceObserver, priority: Int, block: (_ oldState: ConductionResourceState<Parameter, Input, Resource>, _ newState: ConductionResourceState<Parameter, Input, Resource>) -> Void)] = [] private var _getHistory: [ConductionResourceObserver] = [] private var _dispatchKey = DispatchSpecificKey<Void>() // MARK: - Public Properties public private(set) var state: ConductionResourceState<Parameter, Input, Resource> = .empty { didSet { _stateObserverBlocks.sorted { $0.priority > $1.priority }.forEach { $0.block(oldValue, state) } } } public let dispatchQueue: DispatchQueue public let defaultPriority: Int public let fetchBlock: ConductionResourceFetchBlock<Parameter, Input>? public let transformBlock: ConductionResourceTransformBlock<Input, Resource>? public let commitBlock: ConductionResourceCommitBlock<Parameter, Input, Resource> public private(set) var parameter: Parameter? public private(set) var input: Input? public private(set) var resource: Resource? // MARK: - Init public init(dispatchQueue: DispatchQueue = .main, defaultPriority: Int = 0, fetchBlock: ConductionResourceFetchBlock<Parameter, Input>? = nil, transformBlock: ConductionResourceTransformBlock<Input, Resource>? = nil, commitBlock: @escaping ConductionResourceCommitBlock<Parameter, Input, Resource> = { _, nextState in return nextState }) { dispatchQueue.setSpecific(key: _dispatchKey, value: ()) self.dispatchQueue = dispatchQueue self.defaultPriority = defaultPriority self.fetchBlock = fetchBlock self.transformBlock = transformBlock self.commitBlock = commitBlock } // MARK: - Public @discardableResult public func get(observer: ConductionResourceObserver? = nil, parameter: Parameter? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ resource: Resource?) -> Void) -> ConductionResourceObserver { let observer = observer ?? ConductionResourceObserver() dispatch { self.directGet(observer: observer, parameter: parameter, priority: priority, callNow: callNow, completion: completion) } return observer } @discardableResult public func observe(observer: ConductionResourceObserver? = nil, parameter: Parameter? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ resource: Resource?) -> Void) -> ConductionResourceObserver { let observer = observer ?? ConductionResourceObserver() dispatch { self.directObserve(observer: observer, parameter: parameter, priority: priority, callNow: callNow, completion: completion) } return observer } @discardableResult public func observeState(observer: ConductionResourceObserver? = nil, parameter: Parameter? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ oldState: ConductionResourceState<Parameter, Input, Resource>, _ newState: ConductionResourceState<Parameter, Input, Resource>) -> Void) -> ConductionResourceObserver { let observer = observer ?? ConductionResourceObserver() dispatch { self.directObserveState(observer: observer, priority: priority, callNow: callNow, completion: completion) } return observer } public func forget(_ observer: ConductionResourceObserver) { dispatch { self.directForget(observer) } } public func forgetAll() { dispatch { self.directForgetAll() } } public func check(completion: @escaping (_ state: ConductionResourceState<Parameter, Input, Resource>, _ priority: Int?, _ parameter: Parameter?, _ input: Input?, _ resource: Resource?) -> Void) { dispatch { self.directCheck(completion: completion) } } public func load(parameter: Parameter? = nil) { dispatch { self.directLoad(parameter: parameter) } } public func reload(parameter: Parameter? = nil) { dispatch { self.directReload(parameter: parameter) } } public func clear() { dispatch { self.directClear() } } public func expire() { dispatch { self.directExpire() } } public func invalidate() { dispatch { self.directInvalidate() } } public func setParameter( _ parameter: Parameter?) { dispatch { self.directSetParameter(parameter) } } public func setInput( _ input: Input?) { dispatch { self.directSetInput(input) } } public func setResource(_ resource: Resource?) { dispatch { self.directSetResource(resource) } } public func dispatch(_ block: @escaping () -> Void) { if DispatchQueue.getSpecific(key: _dispatchKey) != nil { block() } else { dispatchQueue.async { block() } } } // MARK: - Direct open func directTransition(newState: ConductionResourceState<Parameter, Input, Resource>) { let oldState = state guard let nextState = commitBlock(oldState, newState) else { return } state = nextState switch state { case .invalid(let resource): self.resource = resource _callWaitingBlocks() forgetAll() case .empty: break case .fetching(let id, _, let parameter): self.parameter = parameter switch oldState { case .fetching(let oldID, _, _): guard id != oldID else { return } default: break } _fetch(id: id) case .processing(let id, _, let input): self.input = input switch oldState { case .processing(let oldID, _, _): guard id != oldID else { return } default: break } _process(id: id) case .fetched(let resource): self.resource = resource _callWaitingBlocks() } } @discardableResult open func directGet(observer: ConductionResourceObserver? = nil, parameter: Parameter? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ resource: Resource?) -> Void) -> ConductionResourceObserver { let observer = observer ?? ConductionResourceObserver() guard !_getHistory.contains(observer) else { return observer } guard !callNow else { completion(resource) return observer } switch state { case .invalid: return observer case .fetched: guard parameter != nil else { completion(resource) return observer } fallthrough default: let oldPriority = _priority() _getBlocks = _getBlocks.filter { $0.id != observer } _getBlocks.append((id: observer, priority: priority ?? defaultPriority, block: completion)) switch state { case .fetching, .processing: guard parameter != nil else { _updatePriority(oldPriority: oldPriority) return observer } fallthrough default: directTransition(newState: .fetching(id: ConductionResourceTaskID(), priority: _priority(), parameter: parameter)) } } return observer } @discardableResult open func directObserve(observer: ConductionResourceObserver? = nil, parameter: Parameter? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ resource: Resource?) -> Void) -> ConductionResourceObserver { let observer = observer ?? ConductionResourceObserver() switch state { case .invalid: return observer default: let oldPriority = _priority() _observerBlocks = _observerBlocks.filter { $0.id != observer } _observerBlocks.append((id: observer, priority: priority ?? defaultPriority, block: completion)) _updatePriority(oldPriority: oldPriority) if let parameter = parameter { directTransition(newState: .fetching(id: ConductionResourceTaskID(), priority: _priority(), parameter: parameter)) } else if callNow { completion(resource) } else { switch state { case .fetched: completion(resource) default: break } } } return observer } @discardableResult open func directObserveState(observer: ConductionResourceObserver? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ oldState: ConductionResourceState<Parameter, Input, Resource>, _ newState: ConductionResourceState<Parameter, Input, Resource>) -> Void) -> ConductionResourceObserver { let observer = observer ?? ConductionResourceObserver() switch state { case .invalid: return observer default: let oldPriority = _priority() _stateObserverBlocks = _stateObserverBlocks.filter { $0.id != observer } _stateObserverBlocks.append((id: observer, priority: priority ?? defaultPriority, block: completion)) _updatePriority(oldPriority: oldPriority) if callNow { completion(state, state) } } return observer } open func directForget(_ observer: ConductionResourceObserver) { let oldPriority = _priority() _getBlocks = _getBlocks.filter { $0.id != observer } _observerBlocks = _observerBlocks.filter { $0.id != observer } _stateObserverBlocks = _stateObserverBlocks.filter { $0.id != observer } _getHistory = _getHistory.filter { $0 != observer } _updatePriority(oldPriority: oldPriority) } open func directForgetAll() { let oldPriority = _priority() _getBlocks = [] _observerBlocks = [] _stateObserverBlocks = [] _getHistory = [] _updatePriority(oldPriority: oldPriority) } open func directCheck(completion: (_ state: ConductionResourceState<Parameter, Input, Resource>, _ priority: Int?, _ parameter: Parameter?, _ input: Input?, _ resource: Resource?) -> Void) { completion(state, _priority(), parameter, input, resource) } open func directLoad(parameter: Parameter? = nil) { switch state { case .invalid: return case .empty: directTransition(newState: .fetching(id: ConductionResourceTaskID(), priority: _priority(), parameter: parameter)) default: break } } open func directReload(parameter: Parameter? = nil) { switch state { case .invalid: return default: directTransition(newState: .fetching(id: ConductionResourceTaskID(), priority: _priority(), parameter: parameter)) } } open func directClear() { parameter = nil input = nil resource = nil directExpire() } open func directExpire() { switch state { case .invalid: return case .empty: return default: directTransition(newState: .empty) } } open func directInvalidate() { switch state { case .invalid: return default: directTransition(newState: .invalid(nil)) } } open func directSetParameter(_ parameter: Parameter?) { directTransition(newState: .fetching(id: ConductionResourceTaskID(), priority: _priority(), parameter: parameter)) } open func directSetInput(_ input: Input?) { directTransition(newState: .processing(id: ConductionResourceTaskID(), priority: _priority(), input: input)) } open func directSetResource(_ resource: Resource?) { directTransition(newState: .fetched(resource)) } // MARK: - Life Cycle deinit { dispatchQueue.setSpecific(key: _dispatchKey, value: nil) } // MARK: - Private private func _priority() -> Int? { var priority: Int? = nil priority = _getBlocks.reduce(priority) { result, tuple in guard let result = result else { return tuple.priority } return max(result, tuple.priority) } priority = _observerBlocks.reduce(priority) { result, tuple in guard let result = result else { return tuple.priority } return max(result, tuple.priority) } priority = _stateObserverBlocks.reduce(priority) { result, tuple in guard let result = result else { return tuple.priority } return max(result, tuple.priority) } return priority } private func _updatePriority(oldPriority: Int?) { let newPriority = _priority() guard oldPriority != newPriority else { return } switch state { case .fetching(let id, let priority, let parameter): guard priority != newPriority else { return } directTransition(newState: .fetching(id: id, priority: newPriority, parameter: parameter)) case .processing(let id, let priority, let input): guard priority != newPriority else { return } directTransition(newState: .processing(id: id, priority: newPriority, input: input)) default: break } } private func _fetch(id: ConductionResourceTaskID) { guard let fetchBlock = fetchBlock else { directTransition(newState: .processing(id: ConductionResourceTaskID(), priority: _priority(), input: state.parameter as? Input)) return } fetchBlock(state.parameter, state.priority) { input in self.dispatch { switch self.state { case .fetching(let newID, _, _): guard id == newID else { return } self.directTransition(newState: .processing(id: ConductionResourceTaskID(), priority: self._priority(), input: input)) default: break } } } } private func _process(id: ConductionResourceTaskID) { guard let transformBlock = transformBlock else { directTransition(newState: .fetched(state.input as? Resource)) return } transformBlock(state.input, state.priority) { resource in self.dispatch { switch self.state { case .processing(let newID, _, _): guard id == newID else { return } self.directTransition(newState: .fetched(resource)) default: break } } } } private func _callWaitingBlocks() { var waitingBlocks: [ConductionResourceObserverEntry<Resource>] = _getBlocks waitingBlocks.append(contentsOf: _observerBlocks) waitingBlocks.sort { $0.priority > $1.priority } _getHistory.append(contentsOf: _getBlocks.map { return $0.id }) _getBlocks = [] waitingBlocks.forEach { $0.block(resource) } } } open class ConductionTransformedResource<Input, Resource>: ConductionBaseResource<Void, Input, Resource> { public init(dispatchQueue: DispatchQueue = .main, defaultPriority: Int = 0, commitBlock: @escaping ConductionResourceCommitBlock<Void, Input, Resource> = { _, nextState in return nextState }, fetchBlock: @escaping ConductionResourceFetchBlock<Void, Input>, transformBlock: @escaping ConductionResourceTransformBlock<Input, Resource>) { super.init(dispatchQueue: dispatchQueue, defaultPriority: defaultPriority, fetchBlock: fetchBlock, transformBlock: transformBlock, commitBlock: commitBlock) } } open class ConductionResource<Resource>: ConductionBaseResource<Void, Resource, Resource> { public init(dispatchQueue: DispatchQueue = .main, defaultPriority: Int = 0, commitBlock: @escaping ConductionResourceCommitBlock<Void, Resource, Resource> = { _, nextState in return nextState }, fetchBlock: @escaping ConductionResourceFetchBlock<Void, Resource>) { super.init(dispatchQueue: dispatchQueue, defaultPriority: defaultPriority, fetchBlock: fetchBlock, commitBlock: commitBlock) } }
00741e0c0a0869384081e82bf5d70a0b
37.519149
359
0.659357
false
false
false
false
AnthonyOliveri/bms-clientsdk-swift-push
refs/heads/master
Tests/Unit Tests/BMSPushTests/BMSResponseTests.swift
apache-2.0
2
/* *     Copyright 2016 IBM Corp. *     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 XCTest @testable import BMSPush import BMSCore class BMSResponseTests: XCTestCase { var responseArray = NSMutableArray() var responseDictionary = NSMutableDictionary() func testSubscriptions () { let response = "{\"subscriptions\":[{\"tagName\":\"some tag name\",\"subscriptionId\":\"some subscription ID\",\"deviceId\":\"some device ID\",\"href\":\" https:// mybluemix.net\"},{\"tagName\":\"Push.ALL\",\"userId\":\"\",\"subscriptionId\":\"some subscription ID\",\"deviceId\":\"some device ID\",\"href\":\"https:// mybluemix.net\"}]}" #if swift(>=3.0) let responseData = response.data(using: String.Encoding.utf8) let httpURLResponse = HTTPURLResponse(url: NSURL(string: "http://example.com")! as URL, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: ["key": "value"]) #else let responseData = response.dataUsingEncoding(NSUTF8StringEncoding) let httpURLResponse = NSHTTPURLResponse(URL: NSURL(string: "http://example.com")!, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: ["key": "value"]) #endif let testResponse = Response(responseData: responseData!, httpResponse: httpURLResponse, isRedirect: true) responseArray = testResponse.subscriptions() NSLog("\(responseArray)") } func testSubscribeStatus () { let response = "{\"tagsNotFound\":{\"tags\":[],\"message\":\"Not Found - Targeted resource 'tagNames' does not exist. Check the 'tags' parameter\",\"code\":\"FPWSE0001E\"},\"subscriptionExists\":[],\"subscribed\":[{\"tagName\":\"some tag name\",\"subscriptionId\":\"some subscription ID\",\"deviceId\":\"some device ID\",\"href\":\"https://mybluemix.net\"}]}" #if swift(>=3.0) let responseData = response.data(using: String.Encoding.utf8) let httpURLResponse = HTTPURLResponse(url: NSURL(string: "http://example.com")! as URL, statusCode: 207, httpVersion: "HTTP/1.1", headerFields: ["key": "value"]) #else let responseData = response.dataUsingEncoding(NSUTF8StringEncoding) let httpURLResponse = NSHTTPURLResponse(URL: NSURL(string: "http://example.com")!, statusCode: 207, HTTPVersion: "HTTP/1.1", headerFields: ["key": "value"]) #endif let testResponse = Response(responseData: responseData!, httpResponse: httpURLResponse, isRedirect: true) responseDictionary = testResponse.subscribeStatus() NSLog("\(responseDictionary)") } func testUnsubscribeStatus () { let response = "{\"tagsNotFound\":{\"tags\":[\"Push.ALL\"],\"message\":\"Not Found - Targeted resource 'tagNames' does not exist. Check the 'tags' parameter\",\"code\":\"FPWSE0001E\"},\"subscriptionExists\":[{\"tagName\":\"Some Tag Name\",\"subscriptionId\":\"some subscription ID\",\"deviceId\":\"some device ID\",\"href\":\"https://mybluemix.net\"}],\"subscribed\":[]}" #if swift(>=3.0) let responseData = response.data(using: String.Encoding.utf8) let httpURLResponse = HTTPURLResponse(url: NSURL(string: "http://example.com")! as URL, statusCode: 207, httpVersion: "HTTP/1.1", headerFields: ["key": "value"]) #else let responseData = response.dataUsingEncoding(NSUTF8StringEncoding) let httpURLResponse = NSHTTPURLResponse(URL: NSURL(string: "http://example.com")!, statusCode: 207, HTTPVersion: "HTTP/1.1", headerFields: ["key": "value"]) #endif let testResponse = Response(responseData: responseData!, httpResponse: httpURLResponse, isRedirect: true) responseDictionary = testResponse.unsubscribeStatus() NSLog("\(responseDictionary)") } func testAvailableTags () { let response = "{\"tags\":[{\"uri\":\"https://mybluemix.net/tags/tagname\",\"name\":\"tagname\",\"createdTime\":\"2016-03-21T10:32:27Z\",\"lastUpdatedTime\":\"2016-03-21T10:32:27Z\",\"createdMode\":\"API\",\"href\":\"https://mybluemix.net\"}]}" #if swift(>=3.0) let responseData = response.data(using: String.Encoding.utf8) let httpURLResponse = HTTPURLResponse(url: NSURL(string: "http://example.com")! as URL, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: ["key": "value"]) #else let responseData = response.dataUsingEncoding(NSUTF8StringEncoding) let httpURLResponse = NSHTTPURLResponse(URL: NSURL(string: "http://example.com")!, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: ["key": "value"]) #endif let testResponse = Response(responseData: responseData!, httpResponse: httpURLResponse, isRedirect: true) responseArray = testResponse.availableTags() NSLog("\(responseArray)") } }
82eccf7f7d0b5181bbb41ef8e892edf0
51.53271
379
0.628358
false
true
false
false
kevinmeresse/sefi-ios
refs/heads/master
sefi/DateFormatter.swift
apache-2.0
1
// // DateFormatter.swift // sefi // // Created by Kevin Meresse on 4/20/15. // Copyright (c) 2015 KM. All rights reserved. // import Foundation /** Creates display text from a Date object. */ class DateFormatter { static let localeId = "fr_FR" /** Returns a date formatted like: dd/mm/yyyy */ class func getSimpleDate(date: NSDate) -> String { let dateFormatter = NSDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: localeId) dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle return dateFormatter.stringFromDate(date) } }
3709f0a5e7d3e4cfa4e937bf28271a1d
27.083333
67
0.686478
false
false
false
false
dhardiman/Fetch
refs/heads/master
Tests/FetchTests/SessionActivityMonitorTests.swift
mit
1
// // SessionActivityMonitorTests.swift // FetchTests // // Created by David Hardiman on 17/11/2017. // Copyright © 2017 David Hardiman. All rights reserved. // @testable import Fetch import Nimble import XCTest class SessionActivityMonitorTests: XCTestCase { func testIncrementingTheCountCallsTheHandler() { var valueReceived: Bool? let exp = expectation(description: "Waiting") SessionActivityMonitor.sessionActivityChanged = { isActive in valueReceived = isActive exp.fulfill() } let monitor = SessionActivityMonitor() monitor.incrementCount() waitForExpectations(timeout: 1.0, handler: nil) expect(valueReceived).to(beTrue()) } func testDecrementingTheCountCallsTheHandler() { var valueReceived: Bool = true let monitor = SessionActivityMonitor(initialValue: 1) let exp = expectation(description: "Waiting") SessionActivityMonitor.sessionActivityChanged = { isActive in valueReceived = isActive exp.fulfill() } monitor.decrementCount() waitForExpectations(timeout: 1.0, handler: nil) expect(valueReceived).to(beFalse()) } func testWhenIncrementingItOnlyNotifiesIfTheValueChanges() { var callCount = 0 SessionActivityMonitor.sessionActivityChanged = { _ in callCount += 1 } let monitor = SessionActivityMonitor(isAsynchronous: false) monitor.incrementCount() monitor.incrementCount() expect(callCount).to(equal(1)) } func testWhenDecrementingItOnlyNotifiesIfTheValueChanges() { let monitor = SessionActivityMonitor(initialValue: 2, isAsynchronous: false) var callCount = 0 SessionActivityMonitor.sessionActivityChanged = { _ in callCount += 1 } monitor.decrementCount() monitor.decrementCount() monitor.decrementCount() expect(callCount).to(equal(1)) } }
d1e771462119d5c3a08ba58e3141e880
30.578125
84
0.661059
false
true
false
false
PJayRushton/stats
refs/heads/master
Stats/User.swift
mit
1
// // User.swift // TeacherTools // // Created by Parker Rushton on 1/3/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import Firebase import Marshal struct User: Identifiable, Unmarshaling { var avatarURLString: String? var creationDate: Date var email: String? var id: String var lastStatViewDates = [String: Date]() var ownedTeamIds = Set<String>() var managedTeamIds = Set<String>() var fanTeamIds = Set<String>() var currentTeamId: String? var allTeamIds: [String] { return [ownedTeamIds, managedTeamIds, fanTeamIds].flatMap { $0 } } init(id: String, avatarURLString: String? = nil, email: String? = nil, ownedTeamIds: [String] = [], managedTeamIds: [String] = [], fanTeamIds: [String] = []) { self.id = id self.avatarURLString = avatarURLString self.creationDate = Date() self.email = email self.ownedTeamIds = Set(ownedTeamIds) self.managedTeamIds = Set(managedTeamIds) self.fanTeamIds = Set(fanTeamIds) } init(object: MarshaledObject) throws { avatarURLString = try object.value(for: avatarKey) creationDate = try object.value(for: creationDateKey) ?? Date() email = try object.value(for: emailKey) id = try object.value(for: idKey) if let statViewDatesObject: [String: String] = try object.value(for: lastStatViewDatesKey) { statViewDatesObject.forEach { self.lastStatViewDates[$0.key] = $0.value.date } } if let ownedTeamsObject: JSONObject = try object.value(for: ownedTeamIdsKey) { ownedTeamIds = Set(ownedTeamsObject.keys) } if let managedTeamsObject: JSONObject = try object.value(for: managedTeamIdsKey) { managedTeamIds = Set(managedTeamsObject.keys) } if let fanTeamsObject: JSONObject = try object.value(for: fanTeamIdsKey) { fanTeamIds = Set(fanTeamsObject.keys) } currentTeamId = try object.value(for: currentTeamIdKey) } // MARK - Internal func statViewDate(forTeam teamId: String) -> Date? { return lastStatViewDates[teamId] } func isOwnerOrManager(of team: Team) -> Bool { return [ownedTeamIds, managedTeamIds].joined().contains(team.id) } func owns(_ team: Team) -> Bool { return ownedTeamIds.contains(team.id) } } // MARK: - Marshaling extension User: JSONMarshaling { func jsonObject() -> JSONObject { var json = JSONObject() json[avatarKey] = avatarURLString json[creationDateKey] = creationDate.iso8601String json[idKey] = id json[emailKey] = email var datesObject = JSONObject() lastStatViewDates.forEach { datesObject[$0.key] = $0.value.iso8601String } json[lastStatViewDatesKey] = datesObject json[ownedTeamIdsKey] = ownedTeamIds.marshaled() json[managedTeamIdsKey] = managedTeamIds.marshaled() json[fanTeamIdsKey] = fanTeamIds.marshaled() json[currentTeamIdKey] = currentTeamId ?? NSNull() return json } } extension User { var ref: DatabaseReference { return StatsRefs.usersRef.child(id) } }
ee37694c45c8f439a57bfe1e335db43e
28.891892
163
0.627486
false
false
false
false
ChrisAU/Swacman
refs/heads/master
Swacman/Extensions.swift
mit
1
// // Extensions.swift // Swacman // // Created by Chris Nevin on 21/06/2015. // Copyright (c) 2015 CJNevin. All rights reserved. // import SpriteKit extension CGFloat { func toDegrees() -> CGFloat { return self * CGFloat(180) / CGFloat(M_PI) } func toRadians() -> CGFloat { return self * CGFloat(M_PI) / CGFloat(180) } } extension UIBezierPath { func pathByRotating(degrees: CGFloat) -> UIBezierPath { let radians = degrees.toRadians() let bounds = CGPathGetBoundingBox(self.CGPath) let center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds)) var transform = CGAffineTransformIdentity transform = CGAffineTransformTranslate(transform, center.x, center.y) transform = CGAffineTransformRotate(transform, radians) transform = CGAffineTransformTranslate(transform, -center.x, -center.y) return UIBezierPath(CGPath:CGPathCreateCopyByTransformingPath(self.CGPath, &transform)!) } }
b7f010c9ba7a5da17a36e26a1a6bbd73
28.709677
90
0.744843
false
false
false
false
Ivacker/swift
refs/heads/master
test/1_stdlib/SpriteKit.swift
apache-2.0
10
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // watchOS does not have SpriteKit. // UNSUPPORTED: OS=watchos import Foundation import SpriteKit // SKColor is NSColor on OS X and UIColor on iOS. var r = CGFloat(0) var g = CGFloat(0) var b = CGFloat(0) var a = CGFloat(0) var color = SKColor.redColor() color.getRed(&r, green:&g, blue:&b, alpha:&a) print("color \(r) \(g) \(b) \(a)") // CHECK: color 1.0 0.0 0.0 1.0 #if os(OSX) func f(c: NSColor) { print("colortastic") } #endif #if os(iOS) || os(tvOS) func f(c: UIColor) { print("colortastic") } #endif f(color) // CHECK: colortastic
f0a27a7ecba986981620d8efc2733a74
18.117647
49
0.661538
false
false
false
false
valen90/scoreket
refs/heads/master
Sources/App/Helpers/GameHelper.swift
mit
1
// // GameHelper.swift // scoket // // Created by Valen on 29/03/2017. // // import Vapor import Fluent import Foundation final class GameHelper{ private static let multPointsWinner = 10 private static let multPointsLosers = -5 static func updateScores(message: Message)throws { var scGame: Game = try message.returnGame() scGame.result1 = message.resultOne scGame.result2 = message.resultTwo var teamW = try scGame.teamone() var teamL = try scGame.teamtwo() var gr = message.resultOne var ls = message.resultTwo var grtusers: [User]? = try scGame.teamone()?.users().all() var lssusers: [User]? = try scGame.teamtwo()?.users().all() if(message.resultOne<message.resultTwo){ gr = message.resultTwo ls = message.resultOne let userAux = grtusers grtusers = lssusers lssusers = userAux let teamAux = teamW teamW = teamL teamL = teamAux } teamW?.wins += 1 teamL?.losses += 1 teamW?.totalGames += 1 teamL?.totalGames += 1 scGame.winner = teamW?.id?.int try teamW?.save() try teamL?.save() try GameHelper.addPoints(winners: grtusers!, losers: lssusers!, dif: (gr-ls)) scGame.ended = true scGame.winner = teamW?.id?.int try message.delete() try scGame.save() } static func createMessage (user: User, game: Game, pointsOne: Int, pointsTwo: Int)throws { let te = try user.team()?.first() var mesteam: Team if try game.teamone()?.id == te?.id { mesteam = try game.teamtwo()! }else { mesteam = try game.teamone()! } let gameInMessage: Message? = try Message.query().filter("game",(game.id?.int)!).first() if gameInMessage == nil{ var mes = try Message(game: (game.id?.int)!, resultOne: pointsOne, resultTwo: pointsTwo, scteam_id: (mesteam.id?.int)!) try mes.save() } } static func addPoints(winners: [User], losers: [User], dif: Int) throws{ for user in winners{ var us = user us.score += ((GameHelper.multPointsWinner) * (dif)) try us.save() } for user in losers{ var us = user us.score += ((GameHelper.multPointsLosers) * (dif)) try us.save() } } static func dateFromString(_ dateAsString: String?) -> Date? { guard let string = dateAsString else { return nil } let dateformatter = DateFormatter() dateformatter.timeZone = TimeZone.init(identifier: "UTC") dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let val = dateformatter.date(from: string) return val } static func dateToString(_ dateIn: Date?) -> String? { guard let date = dateIn else { return nil } let dateformatter = DateFormatter() dateformatter.timeZone = TimeZone.init(identifier: "UTC") dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let val = dateformatter.string(from: date) return val } }
2809c8da35ba53befd8c84a6c68d3497
30.371429
131
0.562234
false
false
false
false
ChrisStayte/Pokedex
refs/heads/master
Pokedex/Pokemon.swift
mit
1
// // Pokemon.swift // Pokedex // // Created by ChrisStayte on 1/23/16. // Copyright © 2016 ChrisStayte. All rights reserved. // import Foundation import Alamofire class Pokemon { private var _name: String! private var _pokedexID: Int! private var _description: String! private var _type: String! private var _defense: String! private var _height: String! private var _weight: String! private var _attack: String! private var _nextEvolutionName: String! private var _nextEvolutionID: String! private var _nextEvolutionLevel: String! private var _pokemonUrl: String! private var _moves = [Move]() var name: String { if _name == nil { _name = "" } return _name } var pokedexID: Int { if _pokedexID == nil { _pokedexID = 0 } return _pokedexID } var description: String { if _description == nil { _description = "" } return _description } var type: String { if _type == nil{ _type = "" } return _type } var defense: String { if _defense == nil { _defense = "" } return _defense } var height: String { if _height == nil { _height = "" } return _height } var weight: String { if _weight == nil { _weight = "" } return _weight } var attack: String { if _attack == nil { _attack = "" } return _attack } var nextEvolutionName: String { if _nextEvolutionName == nil { _nextEvolutionName = "" } return _nextEvolutionName } var nextEvolutionID: String { if _nextEvolutionID == nil { _nextEvolutionID = "" } return _nextEvolutionID } var nextEvoltionLevel: String { if _nextEvolutionLevel == nil { _nextEvolutionLevel = "" } return _nextEvolutionLevel } var moves: [Move] { return _moves } init(name: String, pokedexID: Int) { self._name = name self._pokedexID = pokedexID self._pokemonUrl = "\(URL_BASE)\(URL_POKEMON)\(self.pokedexID)/" } func downloadPokemonDetails(completed: DownloadComplete) { let url = NSURL(string: _pokemonUrl)! Alamofire.request(.GET, url).responseJSON {response in let result = response.result if let dict = result.value as? Dictionary<String, AnyObject> { if let weight = dict["weight"] as? String { self._weight = weight } if let height = dict["height"] as? String { self._height = height } if let attack = dict["attack"] as? Int{ self._attack = "\(attack)" } if let defense = dict["defense"] as? Int { self._defense = "\(defense)" } if let types = dict["types"] as? [Dictionary<String, String>] where types.count > 0 { if let name = types[0]["name"] { self._type = name.capitalizedString } if types.count > 1 { for x in 1 ..< types.count { if let name = types[x]["name"] { self._type! += " / \(name.capitalizedString)" } } } print(self._type) } else { self._type = "" } if let descArr = dict["descriptions"] as? [Dictionary<String, String>] { if let url = descArr[0]["resource_uri"] where descArr.count > 0 { let nsurl = NSURL(string: "\(URL_BASE)\(url)")! Alamofire.request(.GET, nsurl).responseJSON { response in let result = response.result if let descDict = result.value as? Dictionary<String, AnyObject> { if let description = descDict["description"] as? String { self._description = description print(self._description) } } completed() } } }else { self._description = "" } if let evolutions = dict["evolutions"] as? [Dictionary<String, AnyObject>] where evolutions.count > 0 { if let to = evolutions[0]["to"] as? String { // Can't Support Mega Pokemon right now but // api still has mega data if to.rangeOfString("mega") == nil { if let uri = evolutions[0]["resource_uri"] as? String { let string = uri.stringByReplacingOccurrencesOfString("/api/v1/pokemon/", withString: "") let pokemonID = string.stringByReplacingOccurrencesOfString("/", withString: "") self._nextEvolutionID = pokemonID self._nextEvolutionName = to if let lvl = evolutions[0]["level"] as? Int { self._nextEvolutionLevel = "\(lvl)" } } } } } self._moves.removeAll() if let moves = dict["moves"] as? [Dictionary<String, AnyObject>] where moves.count > 0 { if let moveName = moves[0]["name"] as? String { if let learnType = moves[0]["learn_type"] as? String { if let learnLevel = moves[0]["level"] as? Int { self._moves.append(Move(name: moveName, learnType: learnType, level: "\(learnLevel)")) } else { self._moves.append(Move(name: moveName, learnType: learnType, level: "")) } } if moves.count > 1 { for x in 1 ..< moves.count { if let moveName = moves[x]["name"] as? String { if let learnType = moves[x]["learn_type"] as? String { if let learnLevel = moves[x]["level"] as? Int { self._moves.append(Move(name: moveName, learnType: learnType, level: "\(learnLevel)")) } else { self._moves.append(Move(name: moveName, learnType: learnType, level: "")) } } } } } } } } } } }
7f286ce75ffd7c4c249f2a710a18838c
33.369565
130
0.399798
false
false
false
false
mihaicris/digi-cloud
refs/heads/develop
Digi Cloud/Controller/Views/RenameUtilitiesButton.swift
mit
1
// // RenameUtilitiesButton.swift // Digi Cloud // // Created by Mihai Cristescu on 01/02/2017. // Copyright © 2017 Mihai Cristescu. All rights reserved. // import UIKit final class RenameUtilitiesButton: UIButton { // MARK: - Initializers and Deinitializers required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Overridden Methods and Properties init(title: String, delegate: Any?, selector: Selector, tag: Int) { super.init(frame: CGRect.zero) self.tag = tag translatesAutoresizingMaskIntoConstraints = false contentHorizontalAlignment = .left layer.cornerRadius = 5 backgroundColor = UIColor(white: 0.98, alpha: 1.0) setTitleColor(UIColor.defaultColor, for: .normal) setTitleColor(UIColor.defaultColor.withAlphaComponent(0.3), for: .highlighted) titleLabel?.font = UIFont.systemFont(ofSize: UIFont.systemFontSize) contentEdgeInsets = UIEdgeInsets(top: 7, left: 10, bottom: 7, right: 10) setTitle(title, for: .normal) addTarget(delegate, action: selector, for: .touchUpInside) sizeToFit() titleLabel?.textColor = .black } }
3a79e398caec5ac55657f3a2cac28e50
31.473684
86
0.67423
false
false
false
false
geowarsong/UG-Lemondo
refs/heads/master
Simple-Calculator/Simple Calculator/Simple Calculator/Controller/MainScreen.swift
apache-2.0
1
// // MainScreen.swift // Simple Calculator // // Created by C0mrade on 5/24/17. // Copyright © 2017 C0mrade. All rights reserved. // import UIKit class MainScreen: UIViewController { // MARK: - IBOutlets @IBOutlet weak var lblMain: UILabel! // MARK: - Properties var isFirstDigit = true var calculatedNumOne = 0.0 var arithmetic = 0 // MARK: - View LifeCycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } // MARK: - IBActions @IBAction func equalButtonTapped(_ sender: UIButton) { if !lblMain.text!.isEmpty { let number = getCalculatedValue(num0: arithmetic, num1: calculatedNumOne, num2: Double(lblMain.text!)!) lblMain.text = "\(number)" } else { print("Could not make math operation because text is empty") } } @IBAction func clearAllTapped(_ sender: UIButton) { lblMain.text = "" // will clear label } @IBAction func arithmeticButtonTapped(_ sender: UIButton) { if !lblMain.text!.isEmpty { arithmetic = sender.tag // will store math operator calculatedNumOne = Double(lblMain.text!)! // cast string to double lblMain.text = "" } else { print("Could not select math operator because text is empty") } } @IBAction func calculatorNumberTapped(_ sender: UIButton) { // if user clicks on the button, first it will add number as main, // following numbers will be concatinated from right to left lblMain.text = isFirstDigit ? "\(sender.tag)" : lblMain.text! + "\(sender.tag)" } func getCalculatedValue (num0 op: Int, num1: Double, num2: Double) -> Double { switch op { case 0: return num1 + num2 case 1: return num1 - num2 case 2: return num1 / num2 case 3: return num1 * num2 default: break } return 0.0 } }
99b34d26e59047ed6b58f03f4aae85d9
27.5
115
0.57468
false
false
false
false
szehnder/AERecord
refs/heads/master
AERecord/AERecordOSX.swift
mit
1
// // AERecord.swift // // Copyright (c) 2014 Marko Tadic - http://markotadic.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. // import Foundation //import UIKit import CoreData let kAERecordPrintLog = true // MARK: - AERecord (AEStack.sharedInstance Shortcuts) public class AERecord { // MARK: Properties class var defaultContext: NSManagedObjectContext { return AEStack.sharedInstance.defaultContext } // context for current thread class var mainContext: NSManagedObjectContext { return AEStack.sharedInstance.mainContext } // context for main thread class var backgroundContext: NSManagedObjectContext { return AEStack.sharedInstance.backgroundContext } // context for background thread class var persistentStoreCoordinator: NSPersistentStoreCoordinator? { return AEStack.sharedInstance.persistentStoreCoordinator } // MARK: Setup Stack class func storeURLForName(name: String) -> NSURL { return AEStack.storeURLForName(name) } class func loadCoreDataStack(managedObjectModel: NSManagedObjectModel = AEStack.defaultModel, storeType: String = NSSQLiteStoreType, configuration: String? = nil, storeURL: NSURL = AEStack.defaultURL, options: [NSObject : AnyObject]? = nil) -> NSError? { return AEStack.sharedInstance.loadCoreDataStack(managedObjectModel: managedObjectModel, storeType: storeType, configuration: configuration, storeURL: storeURL, options: options) } class func destroyCoreDataStack(storeURL: NSURL = AEStack.defaultURL) { AEStack.sharedInstance.destroyCoreDataStack(storeURL: storeURL) } class func truncateAllData(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.truncateAllData(context: context) } // MARK: Context Execute class func executeFetchRequest(request: NSFetchRequest, context: NSManagedObjectContext? = nil) -> [NSManagedObject] { return AEStack.sharedInstance.executeFetchRequest(request, context: context) } // MARK: Context Save class func saveContext(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.saveContext(context: context) } class func saveContextAndWait(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.saveContextAndWait(context: context) } } // MARK: - CoreData Stack (AERecord heart:) private class AEStack { // MARK: Shared Instance class var sharedInstance: AEStack { struct Singleton { static let instance = AEStack() } return Singleton.instance } // MARK: Default settings class var bundleIdentifier: String { return NSBundle.mainBundle().bundleIdentifier! } class var defaultURL: NSURL { return storeURLForName(bundleIdentifier) } class var defaultModel: NSManagedObjectModel { return NSManagedObjectModel.mergedModelFromBundles(nil)! } // MARK: Properties var managedObjectModel: NSManagedObjectModel? var persistentStoreCoordinator: NSPersistentStoreCoordinator? var mainContext: NSManagedObjectContext! var backgroundContext: NSManagedObjectContext! var defaultContext: NSManagedObjectContext { if NSThread.isMainThread() { return mainContext } else { return backgroundContext } } // MARK: Setup Stack class func storeURLForName(name: String) -> NSURL { let applicationDocumentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as NSURL let storeName = "\(name).sqlite" return applicationDocumentsDirectory.URLByAppendingPathComponent(storeName) } func loadCoreDataStack(managedObjectModel: NSManagedObjectModel = defaultModel, storeType: String = NSSQLiteStoreType, configuration: String? = nil, storeURL: NSURL = defaultURL, options: [NSObject : AnyObject]? = nil) -> NSError? { self.managedObjectModel = managedObjectModel // setup main and background contexts mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) // create the coordinator and store persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) if let coordinator = persistentStoreCoordinator { var error: NSError? if coordinator.addPersistentStoreWithType(storeType, configuration: configuration, URL: storeURL, options: options, error: &error) == nil { let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data." dict[NSUnderlyingErrorKey] = error error = NSError(domain: AEStack.bundleIdentifier, code: 1, userInfo: dict) if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } return error } else { // everything went ok mainContext.persistentStoreCoordinator = coordinator backgroundContext.persistentStoreCoordinator = coordinator startReceivingContextNotifications() return nil } } else { return NSError(domain: AEStack.bundleIdentifier, code: 2, userInfo: [NSLocalizedDescriptionKey : "Could not create NSPersistentStoreCoordinator from given NSManagedObjectModel."]) } } func destroyCoreDataStack(storeURL: NSURL = defaultURL) -> NSError? { // must load this core data stack first loadCoreDataStack(storeURL: storeURL) // because there is no persistentStoreCoordinator if destroyCoreDataStack is called before loadCoreDataStack // also if we're in other stack currently that persistentStoreCoordinator doesn't know about this storeURL stopReceivingContextNotifications() // stop receiving notifications for these contexts // reset contexts mainContext.reset() backgroundContext.reset() // finally, remove persistent store var error: NSError? if let coordinator = persistentStoreCoordinator { if let store = coordinator.persistentStoreForURL(storeURL) { if coordinator.removePersistentStore(store, error: &error) { NSFileManager.defaultManager().removeItemAtURL(storeURL, error: &error) } } } // reset coordinator and model persistentStoreCoordinator = nil managedObjectModel = nil if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } return error ?? nil } func truncateAllData(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext if let mom = managedObjectModel { for entity in mom.entities as [NSEntityDescription] { if let entityType = NSClassFromString(entity.managedObjectClassName) as? NSManagedObject.Type { entityType.deleteAll(context: moc) } } } } deinit { stopReceivingContextNotifications() if kAERecordPrintLog { println("\(NSStringFromClass(self.dynamicType)) deinitialized - function: \(__FUNCTION__) | line: \(__LINE__)\n") } } // MARK: Context Execute func executeFetchRequest(request: NSFetchRequest, context: NSManagedObjectContext? = nil) -> [NSManagedObject] { var fetchedObjects = [NSManagedObject]() let moc = context ?? defaultContext moc.performBlockAndWait { () -> Void in var error: NSError? if let result = moc.executeFetchRequest(request, error: &error) { if let managedObjects = result as? [NSManagedObject] { fetchedObjects = managedObjects } } if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } return fetchedObjects } // MARK: Context Save func saveContext(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext moc.performBlock { () -> Void in var error: NSError? if moc.hasChanges && !moc.save(&error) { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } } } func saveContextAndWait(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext moc.performBlockAndWait { () -> Void in var error: NSError? if moc.hasChanges && !moc.save(&error) { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } } } // MARK: Context Sync func startReceivingContextNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSave:", name: NSManagedObjectContextDidSaveNotification, object: mainContext) NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSave:", name: NSManagedObjectContextDidSaveNotification, object: backgroundContext) } func stopReceivingContextNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self) } @objc func contextDidSave(notification: NSNotification) { if let context = notification.object as? NSManagedObjectContext { let contextToRefresh = context == mainContext ? backgroundContext : mainContext contextToRefresh.performBlock({ () -> Void in contextToRefresh.mergeChangesFromContextDidSaveNotification(notification) }) } } } // MARK: - NSManagedObject Extension extension NSManagedObject { // MARK: General class var entityName: String { var name = NSStringFromClass(self) name = name.componentsSeparatedByString(".").last return name } class func createFetchRequest(predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil) -> NSFetchRequest { // create request let request = NSFetchRequest(entityName: entityName) // set request parameters request.predicate = predicate request.sortDescriptors = sortDescriptors return request } // MARK: Creating class func create(context: NSManagedObjectContext = AERecord.defaultContext) -> Self { let entityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context) let object = self(entity: entityDescription!, insertIntoManagedObjectContext: context) return object } class func createWithAttributes(attributes: [NSObject : AnyObject], context: NSManagedObjectContext = AERecord.defaultContext) -> Self { let object = create(context: context) if attributes.count > 0 { object.setValuesForKeysWithDictionary(attributes) } return object } class func firstOrCreateWithAttribute(attribute: String, value: AnyObject, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject { let predicate = NSPredicate(format: "%K = %@", attribute, value as NSObject) let request = createFetchRequest(predicate: predicate) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? createWithAttributes([attribute : value], context: context) } // MARK: Deleting func delete(context: NSManagedObjectContext = AERecord.defaultContext) { context.deleteObject(self) } class func deleteAll(context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.all(context: context) { for object in objects { context.deleteObject(object) } } } class func deleteAllWithPredicate(predicate: NSPredicate, context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.allWithPredicate(predicate, context: context) { for object in objects { context.deleteObject(object) } } } class func deleteAllWithAttribute(attribute: String, value: AnyObject, context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.allWithAttribute(attribute, value: value, context: context) { for object in objects { context.deleteObject(object) } } } // MARK: Finding First class func first(sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let request = createFetchRequest(sortDescriptors: sortDescriptors) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? nil } class func firstWithPredicate(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let request = createFetchRequest(predicate: predicate, sortDescriptors: sortDescriptors) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? nil } class func firstWithAttribute(attribute: String, value: AnyObject, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let predicate = NSPredicate(format: "%K = %@", attribute, value as NSObject) return firstWithPredicate(predicate!, sortDescriptors: sortDescriptors, context: context) } class func firstOrderedByAttribute(name: String, ascending: Bool = true, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let sortDescriptors = [NSSortDescriptor(key: name, ascending: ascending)] return first(sortDescriptors: sortDescriptors, context: context) } // MARK: Finding All class func all(sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let request = createFetchRequest(sortDescriptors: sortDescriptors) let objects = AERecord.executeFetchRequest(request, context: context) return objects.count > 0 ? objects : nil } class func allWithPredicate(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let request = createFetchRequest(predicate: predicate, sortDescriptors: sortDescriptors) let objects = AERecord.executeFetchRequest(request, context: context) return objects.count > 0 ? objects : nil } class func allWithAttribute(attribute: String, value: AnyObject, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let predicate = NSPredicate(format: "%K = %@", attribute, value as NSObject) return allWithPredicate(predicate!, sortDescriptors: sortDescriptors, context: context) } // MARK: Auto Increment class func autoIncrementedIntegerAttribute(attribute: String, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { let sortDescriptor = NSSortDescriptor(key: attribute, ascending: false) if let object = self.first(sortDescriptors: [sortDescriptor], context: context) { if let max = object.valueForKey(attribute) as? Int { return max + 1 } else { return 0 } } else { return 0 } } // MARK: Batch Updating class func batchUpdate(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, resultType: NSBatchUpdateRequestResultType = .StatusOnlyResultType, context: NSManagedObjectContext = AERecord.defaultContext) -> NSBatchUpdateResult? { // create request let request = NSBatchUpdateRequest(entityName: entityName) // set request parameters request.predicate = predicate request.propertiesToUpdate = properties request.resultType = resultType // execute request var batchResult: NSBatchUpdateResult? = nil context.performBlockAndWait { () -> Void in var error: NSError? if let result = context.executeRequest(request, error: &error) as? NSBatchUpdateResult { batchResult = result } if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } return batchResult } class func objectsCountForBatchUpdate(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { if let result = batchUpdate(predicate: predicate, properties: properties, resultType: .UpdatedObjectsCountResultType, context: context) { if let count = result.result as? Int { return count } else { return 0 } } else { return 0 } } class func batchUpdateAndRefreshObjects(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) { if let result = batchUpdate(predicate: predicate, properties: properties, resultType: .UpdatedObjectIDsResultType, context: context) { if let objectIDS = result.result as? [NSManagedObjectID] { refreshObjects(objectIDS, mergeChanges: true, context: context) } } } class func refreshObjects(objectIDS: [NSManagedObjectID], mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { for objectID in objectIDS { var error: NSError? context.performBlockAndWait({ () -> Void in if let object = context.existingObjectWithID(objectID, error: &error) { // turn managed objects into faults if !object.fault { context.refreshObject(object, mergeChanges: mergeChanges) } } if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } }) } } } // MARK: - CoreData driven UITableViewController class CoreDataTableViewController: UITableViewController, NSFetchedResultsControllerDelegate { // // Swift version of class originaly created for Stanford CS193p Winter 2013. // // This class mostly just copies the code from NSFetchedResultsController's documentation page // into a subclass of UITableViewController. // // Just subclass this and set the fetchedResultsController. // The only UITableViewDataSource method you'll HAVE to implement is tableView:cellForRowAtIndexPath:. // And you can use the NSFetchedResultsController method objectAtIndexPath: to do it. // // Remember that once you create an NSFetchedResultsController, you CANNOT modify its @propertys. // If you want new fetch parameters (predicate, sorting, etc.), // create a NEW NSFetchedResultsController and set this class's fetchedResultsController @property again. // // The controller (this class fetches nothing if this is not set). var fetchedResultsController: NSFetchedResultsController? { didSet { if let frc = fetchedResultsController { if frc != oldValue { frc.delegate = self performFetch() } } else { tableView.reloadData() } } } // Causes the fetchedResultsController to refetch the data. // You almost certainly never need to call this. // The NSFetchedResultsController class observes the context // (so if the objects in the context change, you do not need to call performFetch // since the NSFetchedResultsController will notice and update the table automatically). // This will also automatically be called if you change the fetchedResultsController @property. func performFetch() { if let frc = fetchedResultsController { var error: NSError? if !frc.performFetch(&error) { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } tableView.reloadData() } } // Turn this on before making any changes in the managed object context that // are a one-for-one result of the user manipulating rows directly in the table view. // Such changes cause the context to report them (after a brief delay), // and normally our fetchedResultsController would then try to update the table, // but that is unnecessary because the changes were made in the table already (by the user) // so the fetchedResultsController has nothing to do and needs to ignore those reports. // Turn this back off after the user has finished the change. // Note that the effect of setting this to NO actually gets delayed slightly // so as to ignore previously-posted, but not-yet-processed context-changed notifications, // therefore it is fine to set this to YES at the beginning of, e.g., tableView:moveRowAtIndexPath:toIndexPath:, // and then set it back to NO at the end of your implementation of that method. // It is not necessary (in fact, not desirable) to set this during row deletion or insertion // (but definitely for row moves). private var _suspendAutomaticTrackingOfChangesInManagedObjectContext: Bool = false var suspendAutomaticTrackingOfChangesInManagedObjectContext: Bool { get { return _suspendAutomaticTrackingOfChangesInManagedObjectContext } set (newValue) { if newValue == true { _suspendAutomaticTrackingOfChangesInManagedObjectContext = true } else { dispatch_after(0, dispatch_get_main_queue(), { self._suspendAutomaticTrackingOfChangesInManagedObjectContext = false }) } } } private var beganUpdates: Bool = false // MARK: NSFetchedResultsControllerDelegate func controllerWillChangeContent(controller: NSFetchedResultsController) { if !suspendAutomaticTrackingOfChangesInManagedObjectContext { tableView.beginUpdates() beganUpdates = true } } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { if !suspendAutomaticTrackingOfChangesInManagedObjectContext { switch type { case .Insert: tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { if !suspendAutomaticTrackingOfChangesInManagedObjectContext { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) default: return } } } func controllerDidChangeContent(controller: NSFetchedResultsController) { if beganUpdates { tableView.endUpdates() } } // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return fetchedResultsController?.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = fetchedResultsController?.sections![section] as NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let sectionInfo = fetchedResultsController?.sections![section] as NSFetchedResultsSectionInfo return sectionInfo.name } override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { return fetchedResultsController?.sectionForSectionIndexTitle(title, atIndex: index) ?? 0 } override func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! { return fetchedResultsController?.sectionIndexTitles } } // MARK: - CoreData driven UICollectionViewController class CoreDataCollectionViewController: UICollectionViewController, NSFetchedResultsControllerDelegate { // // Same concept as CoreDataTableViewController, but modified for use with UICollectionViewController. // // This class mostly just copies the code from NSFetchedResultsController's documentation page // into a subclass of UICollectionViewController. // // Just subclass this and set the fetchedResultsController. // The only UICollectionViewDataSource method you'll HAVE to implement is collectionView:cellForItemAtIndexPath. // And you can use the NSFetchedResultsController method objectAtIndexPath: to do it. // // Remember that once you create an NSFetchedResultsController, you CANNOT modify its @propertys. // If you want new fetch parameters (predicate, sorting, etc.), // create a NEW NSFetchedResultsController and set this class's fetchedResultsController @property again. // // The controller (this class fetches nothing if this is not set). var fetchedResultsController: NSFetchedResultsController? { didSet { if let frc = fetchedResultsController { if frc != oldValue { frc.delegate = self performFetch() } } else { collectionView.reloadData() } } } // Causes the fetchedResultsController to refetch the data. // You almost certainly never need to call this. // The NSFetchedResultsController class observes the context // (so if the objects in the context change, you do not need to call performFetch // since the NSFetchedResultsController will notice and update the collection view automatically). // This will also automatically be called if you change the fetchedResultsController @property. func performFetch() { if let frc = fetchedResultsController { var error: NSError? if !frc.performFetch(&error) { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } collectionView.reloadData() } } // Turn this on before making any changes in the managed object context that // are a one-for-one result of the user manipulating cells directly in the collection view. // Such changes cause the context to report them (after a brief delay), // and normally our fetchedResultsController would then try to update the collection view, // but that is unnecessary because the changes were made in the collection view already (by the user) // so the fetchedResultsController has nothing to do and needs to ignore those reports. // Turn this back off after the user has finished the change. // Note that the effect of setting this to NO actually gets delayed slightly // so as to ignore previously-posted, but not-yet-processed context-changed notifications, // therefore it is fine to set this to YES at the beginning of, e.g., collectionView:moveItemAtIndexPath:toIndexPath:, // and then set it back to NO at the end of your implementation of that method. // It is not necessary (in fact, not desirable) to set this during row deletion or insertion // (but definitely for cell moves). private var _suspendAutomaticTrackingOfChangesInManagedObjectContext: Bool = false var suspendAutomaticTrackingOfChangesInManagedObjectContext: Bool { get { return _suspendAutomaticTrackingOfChangesInManagedObjectContext } set (newValue) { if newValue == true { _suspendAutomaticTrackingOfChangesInManagedObjectContext = true } else { dispatch_after(0, dispatch_get_main_queue(), { self._suspendAutomaticTrackingOfChangesInManagedObjectContext = false }) } } } // MARK: NSFetchedResultsControllerDelegate Helpers private var sectionInserts = [Int]() private var sectionDeletes = [Int]() private var sectionUpdates = [Int]() private var objectInserts = [NSIndexPath]() private var objectDeletes = [NSIndexPath]() private var objectUpdates = [NSIndexPath]() private var objectMoves = [NSIndexPath]() private var objectReloads = NSMutableSet() func updateSectionsAndObjects() { // sections if !self.sectionInserts.isEmpty { for sectionIndex in self.sectionInserts { self.collectionView.insertSections(NSIndexSet(index: sectionIndex)) } self.sectionInserts.removeAll(keepCapacity: true) } if !self.sectionDeletes.isEmpty { for sectionIndex in self.sectionDeletes { self.collectionView.deleteSections(NSIndexSet(index: sectionIndex)) } self.sectionDeletes.removeAll(keepCapacity: true) } if !self.sectionUpdates.isEmpty { for sectionIndex in self.sectionUpdates { self.collectionView.reloadSections(NSIndexSet(index: sectionIndex)) } self.sectionUpdates.removeAll(keepCapacity: true) } // objects if !self.objectInserts.isEmpty { self.collectionView.insertItemsAtIndexPaths(self.objectInserts) self.objectInserts.removeAll(keepCapacity: true) } if !self.objectDeletes.isEmpty { self.collectionView.deleteItemsAtIndexPaths(self.objectDeletes) self.objectDeletes.removeAll(keepCapacity: true) } if !self.objectUpdates.isEmpty { self.collectionView.reloadItemsAtIndexPaths(self.objectUpdates) self.objectUpdates.removeAll(keepCapacity: true) } if !self.objectMoves.isEmpty { let moveOperations = objectMoves.count / 2 var index = 0 for i in 0 ..< moveOperations { self.collectionView.moveItemAtIndexPath(self.objectMoves[index], toIndexPath: self.objectMoves[index + 1]) index = index + 2 } self.objectMoves.removeAll(keepCapacity: true) } } // MARK: NSFetchedResultsControllerDelegate func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: sectionInserts.append(sectionIndex) case .Delete: sectionDeletes.append(sectionIndex) case .Update: sectionUpdates.append(sectionIndex) default: break } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: objectInserts.append(newIndexPath!) case .Delete: objectDeletes.append(indexPath!) case .Update: objectUpdates.append(indexPath!) case .Move: objectMoves.append(indexPath!) objectMoves.append(newIndexPath!) objectReloads.addObject(indexPath!) objectReloads.addObject(newIndexPath!) } } func controllerDidChangeContent(controller: NSFetchedResultsController) { if !suspendAutomaticTrackingOfChangesInManagedObjectContext { // do batch updates on collection view collectionView.performBatchUpdates({ () -> Void in self.updateSectionsAndObjects() }, completion: { (finished) -> Void in // reload moved items when finished if self.objectReloads.count > 0 { self.collectionView.reloadItemsAtIndexPaths(self.objectReloads.allObjects) self.objectReloads.removeAllObjects() } }) } } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return fetchedResultsController?.sections?.count ?? 0 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let sectionInfo = fetchedResultsController?.sections![section] as NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } }
df17df01817d13e22cf4b9b6ac51c523
43.993961
258
0.657621
false
false
false
false
UniqHu/Youber
refs/heads/master
Youber/Youber/View/AddPayPage.swift
mit
1
// // AddPayPage.swift // Youber // // Created by uniqhj on 2017/3/22. // Copyright © 2017年 Hujian 😄. All rights reserved. // import UIKit class AddPayPage: YbBasePage,UITableViewDelegate,UITableViewDataSource { @IBOutlet var itableView:UITableView! var datas :[PayInfo]! override func viewDidLoad() { super.viewDidLoad() title = "添加付款方式" setNavigationItem(title: "ub_forms_return.png", selector: #selector(leftItemAction), isRight: false) setNavigationItem(title: "验证", selector: #selector(rightItemAction), isRight: true) itableView.register(UITableViewCell.self, forCellReuseIdentifier: "PAYID") initData() itableView.reloadData() } func initData(){ var data:PayInfo! let dict:[String:String] = [ "百度钱包":"ub_forms_baidu.png", "银联":"ub_forms_yinlian.png", "支付宝":"ub_forms_zhifubao.png", "国际信用卡":"ub_forms_xinyongka.png" ] datas = [] for (key,value) in dict{ data = PayInfo() data.name = key data.icon = value datas.append(data) } } override func leftItemAction() { self.navigationController!.popViewController(animated: true) } override func rightItemAction() { let verifyPage = VerifyPhonePage() navigationController?.pushViewController(verifyPage, animated: true) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datas.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellID: String = "PAYID" let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) let pay = datas[indexPath.row] cell.textLabel?.text = pay.name cell.imageView?.image = UIImage(named: pay.icon) return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /* // 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. } */ }
7f6f93113841969768d384947dab9de4
28.05814
108
0.617447
false
false
false
false
abecker3/SeniorDesignGroup7
refs/heads/master
ProvidenceWayfinding/ProvidenceWayfinding/TutorialViewController.swift
apache-2.0
1
// // TutorialViewController.swift // ProvidenceWayfinding // // Created by Derek Becker on 3/15/16. // Copyright © 2016 GU. All rights reserved. // var flagTut = 0 import UIKit class TutorialViewController: UIViewController, UIPageViewControllerDataSource { var pageViewController: UIPageViewController! var pageTitles: NSArray! var pageImages: NSArray! override func viewDidLoad() { super.viewDidLoad() self.pageTitles = NSArray(objects: "Home", "Directions","Parking","More") self.pageImages = NSArray(objects: "Home.png", "Map.png","Car.png","More.png") self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController self.pageViewController.dataSource = self var startVC = self.viewControllerAtIndex(0) as ContentViewController var viewControllers = NSArray(object: startVC) self.pageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Forward, animated: true, completion: nil) self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width, self.view.frame.size.height - 60) self.addChildViewController(self.pageViewController) self.view.addSubview(self.pageViewController.view) self.pageViewController.didMoveToParentViewController(self) } override func viewDidAppear(animated: Bool) { flagTut = 0 } @IBAction func restartAction(sender: AnyObject) { if (flagTut != 0){ var startVC = self.viewControllerAtIndex(0) as ContentViewController var viewControllers = NSArray(object: startVC) self.pageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Reverse, animated: true, completion: nil) flagTut = 0 } } func viewControllerAtIndex(index: Int) -> ContentViewController { if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count)) { return ContentViewController() } var vc: ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController vc.imageFile = self.pageImages[index]as! String vc.titleText = self.pageTitles[index]as! String vc.pageIndex = index return vc } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { var vc = viewController as! ContentViewController var index = vc.pageIndex as Int if (index == 0 || index == NSNotFound) { return nil } index-- flagTut = index return self.viewControllerAtIndex(index) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { var vc = viewController as! ContentViewController var index = vc.pageIndex as Int if (index == NSNotFound) { return nil } index++ flagTut = index if (index == self.pageTitles.count) { return nil } return self.viewControllerAtIndex(index) } func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int { return self.pageTitles.count } func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int { return 0 } }
32992fb04ab3c768a3318ffac71b7c2b
35.107843
159
0.677708
false
false
false
false
ewhitley/CDAKit
refs/heads/master
CDAKitTests/CCDA_PatientImporterTest.swift
mit
1
// // CCDA_PatientImporterTest.swift // CDAKit // // Created by Eric Whitley on 1/25/16. // Copyright © 2016 Eric Whitley. All rights reserved. // import XCTest @testable import CDAKit import Fuzi class CCDA_PatientImporterTest: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func test_parse_ccda() { let xmlString = TestHelpers.fileHelpers.load_xml_string_from_file("sample_ccda") var doc: XMLDocument! do { doc = try XMLDocument(string: xmlString) doc.definePrefix("cda", defaultNamespace: "urn:hl7-org:v3") doc.definePrefix("sdtc", defaultNamespace: "urn:hl7-org:sdtc") let pi = CDAKImport_CCDA_PatientImporter() let patient = pi.parse_ccda(doc) print(patient) XCTAssertEqual(3, patient.allergies.count) let allergy = patient.allergies.first XCTAssertNotNil(allergy) XCTAssertEqual("247472004", allergy?.reaction?.codes.codes.first?.code) XCTAssertEqual("371924009", allergy?.severity?.codes.codes.first?.code) XCTAssertEqual("416098002", allergy?.type.codes.first?.code) XCTAssertEqual("active", allergy?.status) let condition = patient.conditions.first XCTAssertNotNil(condition) XCTAssertEqual("Complaint", condition?.type) XCTAssertEqual(0, patient.encounters.count) XCTAssertEqual(4, patient.immunizations.count) let medication = patient.medications.first XCTAssertNotNil(medication) XCTAssertEqual("5955009", medication?.vehicle.codes.first?.code) XCTAssertNotNil(medication?.order_information.first) XCTAssertNotNil(medication?.fulfillment_history.first) XCTAssertEqual(3, patient.procedures.count) } catch { print("boom") } } }
f1a3f1f9cec3af15becfde0271b55b7c
25.695652
84
0.679153
false
true
false
false
DigitasLabsParis/UnicornHorn
refs/heads/master
BLE Test/BLEDevice.swift
apache-2.0
3
// // BLEDevice.swift // Adafruit Bluefruit LE Connect // // Used to represent an unconnected peripheral in scanning/discovery list // // Created by Collin Cunningham on 10/17/14. // Copyright (c) 2014 Adafruit Industries. All rights reserved. // import Foundation import CoreBluetooth class BLEDevice { var peripheral: CBPeripheral! var isUART:Bool = false private var advertisementData: [NSObject : AnyObject] var RSSI:NSNumber { didSet { self.deviceCell?.updateSignalImage(RSSI) } } private let nilString = "nil" var connectableBool:Bool { let num = advertisementData[CBAdvertisementDataIsConnectable] as? NSNumber if num != nil { return num!.boolValue } else { return false } } var name:String = "" var deviceCell:DeviceCell? { didSet { deviceCell?.nameLabel.text = self.name deviceCell?.connectButton.hidden = !(self.connectableBool) deviceCell?.updateSignalImage(RSSI) deviceCell?.uartCapableLabel.hidden = !self.isUART } } var localName:String { var nameString = advertisementData[CBAdvertisementDataLocalNameKey] as? NSString if nameString == nil { nameString = nilString } return nameString! } var manufacturerData:String { var newData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? NSData if newData == nil { return nilString } let dataString = newData?.hexRepresentation() return dataString! } var serviceData:String { var dict = advertisementData[CBAdvertisementDataServiceDataKey] as? NSDictionary if dict == nil { return nilString } else { return dict!.description } } var serviceUUIDs:[String] { let svcIDs = advertisementData[CBAdvertisementDataServiceUUIDsKey] as? NSArray if svcIDs == nil { return [nilString] } return self.stringsFromUUIDs(svcIDs!) } var overflowServiceUUIDs:[String] { let ovfIDs = advertisementData[CBAdvertisementDataOverflowServiceUUIDsKey] as? NSArray if ovfIDs == nil { return [nilString] } return self.stringsFromUUIDs(ovfIDs!) } var txPowerLevel:String { let txNum = advertisementData[CBAdvertisementDataTxPowerLevelKey] as? NSNumber if txNum == nil { return nilString } return txNum!.stringValue } var isConnectable:String { let num = advertisementData[CBAdvertisementDataIsConnectable] as? NSNumber if num == nil { return nilString } let verdict = num!.boolValue //Enable connect button according to connectable value if self.deviceCell?.connectButton? != nil { deviceCell?.connectButton.enabled = verdict } return verdict.description } var solicitedServiceUUIDs:[String] { let ssIDs = advertisementData[CBAdvertisementDataSolicitedServiceUUIDsKey] as? NSArray if ssIDs == nil { return [nilString] } return self.stringsFromUUIDs(ssIDs!) } var RSSString:String { return RSSI.stringValue } var identifier:NSUUID? { if self.peripheral == nil { printLog(self, "identifier", "attempting to retrieve peripheral ID before peripheral set") return nil } else { return self.peripheral.identifier } } var UUIDString:String { let str = self.identifier?.UUIDString if str != nil { return str! } else { return nilString } } var advertisementArray:[[String]] = [] init(peripheral:CBPeripheral!, advertisementData:[NSObject : AnyObject]!, RSSI:NSNumber!) { self.peripheral = peripheral self.advertisementData = advertisementData self.RSSI = RSSI var array:[[String]] = [] var entry:[String] = ["Local Name", self.localName] if entry[1] != nilString { array.append(entry) } entry = ["UUID", UUIDString] if entry[1] != nilString { array.append(entry) } entry = ["Manufacturer Data", manufacturerData] if entry[1] != nilString { array.append(entry) } entry = ["Service Data", serviceData] if entry[1] != nilString { array.append(entry) } var completServiceUUIDs:[String] = serviceUUIDs if overflowServiceUUIDs[0] != nilString { completServiceUUIDs += overflowServiceUUIDs } entry = ["Service UUIDs"] + completServiceUUIDs if entry[1] != nilString { array.append(entry) } entry = ["TX Power Level", txPowerLevel] if entry[1] != nilString { array.append(entry) } entry = ["Connectable", isConnectable] if entry[1] != nilString { array.append(entry) } entry = ["Solicited Service UUIDs"] + solicitedServiceUUIDs if entry[1] != nilString { array.append(entry) } advertisementArray = array var nameString = peripheral.name //TODO: Delete //FOR SCREENSHOTS v // if nameString == "Apple TV" { // var rand:String = "\(random())" // rand = rand.stringByPaddingToLength(2, withString: " ", startingAtIndex: 0) // nameString = "UP_\(rand)" // } // else if nameString == "UART" { // var rand:String = "\(random())" // rand = rand.stringByPaddingToLength(1, withString: " ", startingAtIndex: 2) // nameString = nameString + "-\(rand)" // } //FOR SCREENSHOTS ^ if nameString == nil || nameString == "" { nameString = "N/A" } self.name = nameString //Check for UART service for id in completServiceUUIDs { if uartServiceUUID().equalsString(id, caseSensitive: false, omitDashes: true) { isUART = true } } } func stringsFromUUIDs(idArray:NSArray)->[String] { var idStringArray = [String](count: idArray.count, repeatedValue: "") idArray.enumerateObjectsUsingBlock({ (obj:AnyObject!, idx:Int, stop:UnsafeMutablePointer<ObjCBool>) -> Void in let objUUID = obj as? CBUUID let idStr = objUUID!.UUIDString idStringArray[idx] = idStr }) return idStringArray } func printAdData(){ if LOGGING { println("- - - -") for a in advertisementArray { println(a) } println("- - - -") } } }
4a4abff39bd34253f78227f006897731
28.786008
118
0.551472
false
false
false
false
softdevstory/yata
refs/heads/master
yata/Sources/Models/Node.swift
mit
1
// // Node.swift // yata // // Created by HS Song on 2017. 6. 13.. // Copyright © 2017년 HS Song. All rights reserved. // import Foundation import ObjectMapper enum NodeType { case string case nodeElement } /** This abstract object represents a DOM Node. It can be a String which represents a DOM text node or a NodeElement object. */ class Node { let type: NodeType let value: String! let element: NodeElement! init(string: String) { type = NodeType.string value = string element = nil } init(element: NodeElement) { type = NodeType.nodeElement value = nil self.element = element } } extension Node { var string: String { switch type { case .string: return value case .nodeElement: return element.string } } } class NodeArrayTransform: TransformType { typealias Object = [Node] typealias JSON = [Any] func transformFromJSON(_ value: Any?) -> [Node]? { guard let list = value as? [Any], list.count > 0 else { return nil } var node: [Node] = [] for item in list { if let string = item as? String { node.append(Node(string: string)) } else if let dict = item as? [String: Any] { if let nodeElement = NodeElement(JSON: dict) { node.append(Node(element: nodeElement)) } } } return node } func transformToJSON(_ value: [Node]?) -> [Any]? { guard let list = value, list.count > 0 else { return nil } var json: [Any] = [] for node in list { switch node.type { case .string: json.append(node.value) case .nodeElement: json.append(node.element.toJSON()) } } return json } }
072c03822fd714505f0d45237387ef81
20.247312
121
0.524291
false
false
false
false
wilfreddekok/Antidote
refs/heads/master
Antidote/AppCoordinator.swift
mpl-2.0
1
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit class AppCoordinator { private let window: UIWindow private var activeCoordinator: TopCoordinatorProtocol! private var theme: Theme init(window: UIWindow) { self.window = window let filepath = NSBundle.mainBundle().pathForResource("default-theme", ofType: "yaml")! let yamlString = try! NSString(contentsOfFile:filepath, encoding:NSUTF8StringEncoding) as String theme = try! Theme(yamlString: yamlString) applyTheme(theme) } } // MARK: CoordinatorProtocol extension AppCoordinator: TopCoordinatorProtocol { func startWithOptions(options: CoordinatorOptions?) { let storyboard = UIStoryboard(name: "LaunchPlaceholderBoard", bundle: NSBundle.mainBundle()) window.rootViewController = storyboard.instantiateViewControllerWithIdentifier("LaunchPlaceholderController") recreateActiveCoordinator(options: options) } func handleLocalNotification(notification: UILocalNotification) { activeCoordinator.handleLocalNotification(notification) } func handleInboxURL(url: NSURL) { activeCoordinator.handleInboxURL(url) } } extension AppCoordinator: RunningCoordinatorDelegate { func runningCoordinatorDidLogout(coordinator: RunningCoordinator, importToxProfileFromURL: NSURL?) { KeychainManager().deleteActiveAccountData() recreateActiveCoordinator() if let url = importToxProfileFromURL, let coordinator = activeCoordinator as? LoginCoordinator { coordinator.handleInboxURL(url) } } func runningCoordinatorDeleteProfile(coordinator: RunningCoordinator) { let userDefaults = UserDefaultsManager() let profileManager = ProfileManager() let name = userDefaults.lastActiveProfile! do { try profileManager.deleteProfileWithName(name) KeychainManager().deleteActiveAccountData() userDefaults.lastActiveProfile = nil recreateActiveCoordinator() } catch let error as NSError { handleErrorWithType(.DeleteProfile, error: error) } } func runningCoordinatorRecreateCoordinatorsStack(coordinator: RunningCoordinator, options: CoordinatorOptions) { recreateActiveCoordinator(options: options, skipAuthorizationChallenge: true) } } extension AppCoordinator: LoginCoordinatorDelegate { func loginCoordinatorDidLogin(coordinator: LoginCoordinator, manager: OCTManager, password: String) { KeychainManager().toxPasswordForActiveAccount = password recreateActiveCoordinator(manager: manager, skipAuthorizationChallenge: true) } } // MARK: Private private extension AppCoordinator { func applyTheme(theme: Theme) { let linkTextColor = theme.colorForType(.LinkText) UIButton.appearance().tintColor = linkTextColor UISwitch.appearance().onTintColor = linkTextColor UINavigationBar.appearance().tintColor = linkTextColor } func recreateActiveCoordinator(options options: CoordinatorOptions? = nil, manager: OCTManager? = nil, skipAuthorizationChallenge: Bool = false) { if let password = KeychainManager().toxPasswordForActiveAccount { let successBlock: OCTManager -> Void = { [unowned self] manager -> Void in self.activeCoordinator = self.createRunningCoordinatorWithManager(manager, options: options, skipAuthorizationChallenge: skipAuthorizationChallenge) } if let manager = manager { successBlock(manager) } else { let deleteActiveAccountAndRetry: Void -> Void = { [unowned self] in KeychainManager().deleteActiveAccountData() self.recreateActiveCoordinator(options: options, manager: manager, skipAuthorizationChallenge: skipAuthorizationChallenge) } guard let profileName = UserDefaultsManager().lastActiveProfile else { deleteActiveAccountAndRetry() return } let path = ProfileManager().pathForProfileWithName(profileName) guard let configuration = OCTManagerConfiguration.configurationWithBaseDirectory(path) else { deleteActiveAccountAndRetry() return } ToxFactory.createToxWithConfiguration(configuration, encryptPassword: password, successBlock: successBlock, failureBlock: { _ in log("Cannot create tox with configuration \(configuration)") deleteActiveAccountAndRetry() }) } } else { activeCoordinator = createLoginCoordinator(options) } } func createRunningCoordinatorWithManager(manager: OCTManager, options: CoordinatorOptions?, skipAuthorizationChallenge: Bool) -> RunningCoordinator { let coordinator = RunningCoordinator(theme: theme, window: window, toxManager: manager, skipAuthorizationChallenge: skipAuthorizationChallenge) coordinator.delegate = self coordinator.startWithOptions(options) return coordinator } func createLoginCoordinator(options: CoordinatorOptions?) -> LoginCoordinator { let coordinator = LoginCoordinator(theme: theme, window: window) coordinator.delegate = self coordinator.startWithOptions(options) return coordinator } }
c1cb64ad9afd3e99f9ab539c41c3ad4f
38.490798
137
0.612552
false
false
false
false
carloscorreia94/PhotoPick
refs/heads/master
Sources/PickLibraryView.swift
mit
1
// // PickLibraryView.swift // PhotoPick // // Created by carloscorreia on 23/07/17. // Copyright © 2017 carloscorreia94. All rights reserved. // import UIKit import Photos @objc public protocol PickLibraryViewDelegate: class { func albumViewCameraRollUnauthorized() func albumViewCameraRollAuthorized() func getViewController() -> UIViewController } class PickLibraryView : UIView, PHPhotoLibraryChangeObserver, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var scrollView: UIScrollView! let GRID = "GRID".hashValue let CELLS = "CELLS".hashValue var imageView: UIImageView! var gridView: GridView! var gridIsActive = false var collectionViewLayout = CustomImageFlowLayout() var imageManager = PHCachingImageManager() var assets: PHFetchResult<PHAsset>? var optionsLowRes: PHImageRequestOptions! var optionsHighRes: PHImageRequestOptions! var loadingView : LoadingView! weak var delegate: PickLibraryViewDelegate? = nil static func instance() -> PickLibraryView { return UINib(nibName: "PickLibraryView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! PickLibraryView } func initialize() { loadingView = LoadingView(delegate!.getViewController(), origin: CGPoint(x: 0, y: self.center.y)) loadingView.hide() self.backgroundColor = UIColor.darkGray // Init Images Collection View let cellNib = UINib(nibName: "ImageCollectionViewCell", bundle: Bundle(for: self.classForCoder)) collectionView.register(cellNib, forCellWithReuseIdentifier: "imageCell") collectionView.collectionViewLayout = collectionViewLayout collectionView.backgroundColor = UIColor.darkGray collectionView.tag = CELLS collectionView.delegate = self collectionView.dataSource = self // Never load photos Unless the user allows to access to photo album checkPhotoAuth() // Fetch and sort images by date let optionsSort = PHFetchOptions() optionsSort.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] assets = PHAsset.fetchAssets(with: .image, options: optionsSort) scrollView.tag = GRID scrollView.delegate = self // Set double tap zoom let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(scrollViewDoubleTapped(_:))) doubleTapRecognizer.numberOfTapsRequired = 2 doubleTapRecognizer.numberOfTouchesRequired = 1 scrollView.addGestureRecognizer(doubleTapRecognizer) // Set images options for high resolution optionsHighRes = PHImageRequestOptions() optionsHighRes.deliveryMode = .highQualityFormat optionsHighRes.resizeMode = .none optionsHighRes.isSynchronous = false optionsHighRes.isNetworkAccessAllowed = true optionsHighRes.progressHandler = { (progress: Double, error: Error?, stop: UnsafeMutablePointer<ObjCBool>, info: [AnyHashable: Any]?) in print(Int(progress * 100)) } PHPhotoLibrary.shared().register(self) } // Check the status of authorization for PHPhotoLibrary func checkPhotoAuth() { PHPhotoLibrary.requestAuthorization { (status) -> Void in switch status { case .authorized: DispatchQueue.main.async { self.delegate?.albumViewCameraRollAuthorized() self.updateLibrary() } case .restricted, .denied: DispatchQueue.main.async(execute: { () -> Void in self.delegate?.albumViewCameraRollUnauthorized() }) default: break } } } func updateLibrary() { print("call update library!") let optionsSort = PHFetchOptions() optionsSort.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] assets = PHAsset.fetchAssets(with: .image, options: optionsSort) // Setup grid view gridView = GridView(frame: scrollView.frame) gridView.backgroundColor = UIColor.white.withAlphaComponent(0.0) gridView.isUserInteractionEnabled = false collectionView.reloadData() } /** UICollectionView delegate to set numbers of cells needed. - parameter collectionView: UICollectionView - parameter section: number of items in section - returns: number of cells */ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return assets == nil ? 0 : assets!.count } /** UICollectionView delegate to draw the cells with low resolution. - parameter collectionView: UICollectionView - parameter indexPath: cell for item at index path - returns: cell */ func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: ImageCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCollectionViewCell let zeroIndexPath = IndexPath(row: 0, section: 0) if zeroIndexPath == indexPath { let isReady = PHPhotoLibrary.authorizationStatus() == .authorized if isReady && assets!.count > 0 && imageView == nil { let photo = assets![(zeroIndexPath as NSIndexPath).row] showImage(photo) cell.isSelected = true } } let cellWidth = collectionViewLayout.cellWidth let asset = assets![(indexPath as NSIndexPath).row] imageManager.requestImage(for: asset, targetSize: CGSize(width: cellWidth, height: cellWidth), contentMode: .aspectFill, options: nil) { (result, _) in cell.imageView?.image = result } return cell } /** UICollectionView delegate to know what cells was selected and show the image with the best resolution andn set selected state. - parameter collectionView: UICollectionView - parameter indexPath: cell for item at index path */ func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell: ImageCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCollectionViewCell cell.isSelected = true let photo = assets![(indexPath as NSIndexPath).row] let isReady = PHPhotoLibrary.authorizationStatus() == .authorized if isReady { showImage(photo) } } /** UICollectionView delegate to know what cells was deselected and set deselected state. - parameter collectionView: UICollectionView - parameter indexPath: cell for item at index path */ func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cell: ImageCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCollectionViewCell cell.isSelected = false } func displayImage(imageRequested: UIImage) { // Images doesnt have same size, so we need to create a new imageView for each image let imageViewFrame = CGRect(origin: CGPoint(x: 0, y: 0), size: imageRequested.size) imageView?.removeFromSuperview() imageView = UIImageView(frame: imageViewFrame) imageView.backgroundColor = UIColor.darkGray imageView.image = imageRequested scrollView.addSubview(imageView) scrollView.contentSize = imageRequested.size // Calculate the scale range for each image let scrollViewFrame = scrollView.frame let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height let minScale = min(scaleWidth, scaleHeight) scrollView.minimumZoomScale = minScale scrollView.maximumZoomScale = 3.0 scrollView.zoomScale = minScale * 1.3 centerScrollViewContents() } /** Get the image with best resolution and show it on the preview. - parameter asset: image from library */ func showImage(_ asset: PHAsset) { loadingView.show() let imageSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) imageManager.requestImage(for: asset, targetSize: imageSize, contentMode: .aspectFit, options: optionsHighRes, resultHandler: { (result: UIImage?, info: [AnyHashable: Any]?) in self.displayImage(imageRequested: result!) self.loadingView.hide() }) } /** Center scroll view content after zooming. */ func centerScrollViewContents() { let boundsSize = scrollView.bounds.size var contentsFrame = imageView.frame if contentsFrame.size.width < boundsSize.width { contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0 } else { contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundsSize.height { contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0 } else { contentsFrame.origin.y = 0.0 } imageView.frame = contentsFrame } /** Zoom image with a double tap - parameter recognizer: UITapGestureRecognizer */ @objc func scrollViewDoubleTapped(_ recognizer: UITapGestureRecognizer) { let pointInView = recognizer.location(in: imageView) var newZoomScale = scrollView.zoomScale * 1.5 newZoomScale = min(newZoomScale, scrollView.maximumZoomScale) let scrollViewSize = scrollView.bounds.size let w = scrollViewSize.width / newZoomScale let h = scrollViewSize.height / newZoomScale let x = pointInView.x - (w / 2.0) let y = pointInView.y - (h / 2.0) let rectToZoomTo = CGRect(x: x, y: y, width: w, height: h) scrollView.zoom(to: rectToZoomTo, animated: true) } /** UIScrollView delegate when zooming. - parameter scrollView: UIScrollView - returns: image preview */ func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } /** UIScrollView delegate after zooming, center the image. - parameter scrollView: UIScrollView */ func scrollViewDidZoom(_ scrollView: UIScrollView) { centerScrollViewContents() } /** UIScrollView delegate when dragging the image, show the grid. - parameter scrollView: UIScrollView */ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if scrollView.tag == GRID && !gridIsActive { self.addSubview(gridView) gridIsActive = true } } /** UIScrollView delegate after dragging the image, remove the grid. - parameter scrollView: UIScrollView */ func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { gridView?.removeFromSuperview() gridIsActive = false } /** UIScrollView delegate when zooming the image, show the grid. - parameter scrollView: UIScrollView - parameter view: UIView? */ func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { if scrollView.tag == GRID && !gridIsActive { self.addSubview(gridView) gridIsActive = true } } /** UIScrollView delegate after zooming the image, remove the grid. - parameter scrollView: UIScrollView - parameter view: UIView? - parameter scale: CGFloat */ func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { gridView?.removeFromSuperview() gridIsActive = false } /** Crop the image selected in the scroll view. - returns: cropped image */ func cropImage() -> UIImage? { if imageView.image == nil { return nil } UIGraphicsBeginImageContextWithOptions(scrollView.bounds.size, true, UIScreen.main.scale) let offset = scrollView.contentOffset UIGraphicsGetCurrentContext()?.translateBy(x: -offset.x, y: -offset.y) scrollView.layer.render(in: UIGraphicsGetCurrentContext()!) let croppedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // UIImageWriteToSavedPhotosAlbum(croppedImage, nil, nil, nil) return croppedImage } deinit { if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized { PHPhotoLibrary.shared().unregisterChangeObserver(self) } } } extension UIColor { convenience init(red: UInt32, green: UInt32, blue: UInt32, alphaH: UInt32) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") assert(alphaH >= 0 && alphaH <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alphaH) / 255.0) } convenience init(netHex: UInt32) { let mask : UInt32 = 0xff self.init(red: (netHex >> 16) & mask, green: (netHex >> 8) & mask, blue: netHex & mask, alphaH: (netHex >> 24) & mask) } } extension PickLibraryView { //MARK: - PHPhotoLibraryChangeObserver func photoLibraryDidChange(_ changeInstance: PHChange) { updateLibrary() } }
9caa6b9ebc885a3caec6cb4278e63291
32.81128
157
0.597228
false
false
false
false
patrick-sheehan/cwic
refs/heads/master
Source/ImageTextListViewController.swift
gpl-3.0
1
// // ImageTextListViewController.swift // CWIC // // Created by Patrick Sheehan on 12/6/17. // Copyright © 2017 Síocháin Solutions. All rights reserved. // import UIKit class ImageTextListViewController: UIViewController { // MARK: - Member Variables var text: String? var imageLink: String? var tableViewDelegate: UITableViewDelegate? var tableViewDataSource: UITableViewDataSource? // MARK: - IB Outlets @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var textView: UITextView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var textViewHeight: NSLayoutConstraint! // MARK: - View Lifecycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationItem.title = self.title if let link = imageLink { imageView.downloadedFrom(link: link) } if let text = text { textViewHeight.constant = 250 textView.text = text } else { textViewHeight.constant = 0 } } } // MARK: - Table View Methods (for actions at the bottom) extension ImageTextListViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 // return event.actions.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() // return tableView.defaultCell(event.actions[indexPath.row]) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let action = event.actions[indexPath.row] // showPopupInfo("'\(action)' coming soon!") // // tableView.deselectRow(at: indexPath, animated: true) } }
19a1187534dc2b84da5e76565d8faaf5
24.614286
98
0.691578
false
false
false
false
Obisoft2017/BeautyTeamiOS
refs/heads/master
BeautyTeam/BeautyTeam/GroupDetailFirstLineTableViewCell.swift
apache-2.0
1
// // GroupDetailFirstLineTableViewCell.swift // BeautyTeam // // Created by Carl Lee on 5/22/16. // Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved. // import UIKit import SDWebImage class GroupDetailFirstLineTableViewCell: UITableViewCell { var nameLabel = UILabel(frame: CGRectMake(22, 22, 166, 23)) var ownerIndicatorLabel = UILabel(frame: CGRectMake(22, 64, 65, 18)) var ownerButton = UIButton(type: UIButtonType.System) var adminIndicatorLabel = UILabel(frame: CGRectMake(22, 92, 65, 18)) var adminButton = UIButton(type: .System) var groupImageView: UIImageView = UIImageView(frame: CGRectMake(271, 27, 83, 83)) override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // nameLabel self.nameLabel.font = UIFont.systemFontOfSize(20) // Color 199 199 205 // owner self.ownerIndicatorLabel.text = "Owner" self.ownerIndicatorLabel.font = UIFont.systemFontOfSize(18) self.ownerIndicatorLabel.textColor = UIColor(red: 199/255, green: 199/255, blue: 205/255, alpha: 1) self.ownerButton.frame = CGRectMake(87, 64, 100, 18) self.ownerButton.titleLabel?.font = UIFont.systemFontOfSize(18) self.ownerIndicatorLabel.textColor = UIColor(red: 199/255, green: 199/255, blue: 205/255, alpha: 1) // admin self.adminIndicatorLabel.text = "Admin" self.adminIndicatorLabel.font = UIFont.systemFontOfSize(18) self.adminIndicatorLabel.textColor = UIColor(red: 199/255, green: 199/255, blue: 205/255, alpha: 1) self.adminButton.frame = CGRectMake(87, 92, 100, 18) self.adminButton.titleLabel?.font = UIFont.systemFontOfSize(18) // groupImageView self.groupImageView.layer.cornerRadius = self.groupImageView.frame.width / 2 self.groupImageView.layer.masksToBounds = true self.contentView.addSubview(nameLabel) self.contentView.addSubview(ownerIndicatorLabel) self.contentView.addSubview(ownerButton) self.contentView.addSubview(adminIndicatorLabel) self.contentView.addSubview(adminButton) self.contentView.addSubview(groupImageView) } func assignValue(groupName: String, ownerName: String, adminName: String, groupImageURL: NSURL) { self.nameLabel.text = groupName self.ownerButton.setTitle(ownerName, forState: .Normal) self.adminButton.setTitle(adminName, forState: .Normal) // self.groupImageView.sd_setImageWithURL(groupImageURL) self.groupImageView.sd_setImageWithURL(NSURL(string: "https://obisoft.oss-cn-beijing.aliyuncs.com/WebSiteIcon/Icon.jpg")!) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
057623998e7dbd23cf4dc6312a1154cc
37.626506
130
0.680599
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
Habitica API Client/Habitica API Client/Group/FindUsernamesCall.swift
gpl-3.0
1
// // FindUsernameCall.swift // Habitica API Client // // Created by Phillip Thelen on 07.02.19. // Copyright © 2019 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import ReactiveSwift public class FindUsernamesCall: ResponseArrayCall<MemberProtocol, APIMember> { public init(username: String, context: String?, id: String?, stubHolder: StubHolderProtocol? = StubHolder(responseCode: 200, stubFileName: "member.json")) { var url = "members/find/\(username)" if let context = context, let id = id { url += "?context=\(context)&id=\(id)" } super.init(httpMethod: .GET, endpoint: url, stubHolder: stubHolder) } }
52f0941fe83a2b31efef60db74c0518d
32.333333
160
0.681429
false
false
false
false
samodom/TestableCoreLocation
refs/heads/master
TestableCoreLocation/CLLocationManager/CLLocationManagerStartUpdatingLocationSpy.swift
mit
1
// // CLLocationManagerStartUpdatingLocationSpy.swift // TestableCoreLocation // // Created by Sam Odom on 3/6/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import CoreLocation import FoundationSwagger import TestSwagger public extension CLLocationManager { private static let startUpdatingLocationCalledKeyString = UUIDKeyString() private static let startUpdatingLocationCalledKey = ObjectAssociationKey(startUpdatingLocationCalledKeyString) private static let startUpdatingLocationCalledReference = SpyEvidenceReference(key: startUpdatingLocationCalledKey) /// Spy controller for ensuring that a location manager has had `startUpdatingLocation` /// called on it. public enum StartUpdatingLocationSpyController: SpyController { public static let rootSpyableClass: AnyClass = CLLocationManager.self public static let vector = SpyVector.direct public static let coselectors = [ SpyCoselectors( methodType: .instance, original: #selector(CLLocationManager.startUpdatingLocation), spy: #selector(CLLocationManager.spy_startUpdatingLocation) ) ] as Set public static let evidence = [startUpdatingLocationCalledReference] as Set public static let forwardsInvocations = false } /// Spy method that replaces the true implementation of `startUpdatingLocation` dynamic public func spy_startUpdatingLocation() { startUpdatingLocationCalled = true } /// Indicates whether the `startUpdatingLocation` method has been called on this object. public final var startUpdatingLocationCalled: Bool { get { return loadEvidence(with: CLLocationManager.startUpdatingLocationCalledReference) as? Bool ?? false } set { saveEvidence(newValue, with: CLLocationManager.startUpdatingLocationCalledReference) } } }
b27e46c7ea3889daa2bd9a79a81573a7
34.160714
111
0.72067
false
false
false
false
Mazy-ma/DemoBySwift
refs/heads/master
EmotionKeyboard/EmotionKeyboard/GiftBoardView.swift
apache-2.0
1
// // GiftBoardView.swift // EmotionKeyboard // // Created by Mazy on 2017/9/4. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit let giftViewCellID = "GiftViewCellIdentifier" class GiftBoardView: UIView, NibLoadable { var emotionButtonClickClosure: ((UIButton)->Void)? fileprivate var flowLayout: CollectionViewHorizontalFlowLayout! fileprivate var emotionView: EmotionView! fileprivate lazy var emotionsArray: [[String]] = [[String]]() @IBOutlet weak var topSeparatorView: UIView! @IBOutlet weak var sendButton: UIButton! override func awakeFromNib() { super.awakeFromNib() setNeedsLayout() layoutIfNeeded() flowLayout = CollectionViewHorizontalFlowLayout(rows: 2, cols: 4) flowLayout.minimumLineSpacing = 10 flowLayout.minimumInteritemSpacing = 10 flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10) flowLayout.scrollDirection = .horizontal let property = TitleViewProperty() emotionView = EmotionView(frame: CGRect(x: 0, y: topSeparatorView.frame.maxY, width: UIScreen.main.bounds.width, height: bounds.height - topSeparatorView.frame.maxY - sendButton.bounds.height),titles: ["普通","会员", "专属"], layout: flowLayout, property: property) addSubview(emotionView) emotionView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin] emotionView.dataSource = self emotionView.delegate = self emotionView.register(nib: UINib(nibName: "GiftViewCell", bundle: nil), forCellWithReuseIdentifier: giftViewCellID) loadEmotionData() } func loadEmotionData() { guard let normalPath = Bundle.main.path(forResource: "QHNormalEmotionSort.plist", ofType: nil) else { return } let normalEmotions: [String] = NSArray(contentsOfFile: normalPath) as! [String] emotionsArray.append(normalEmotions) guard let giftPath = Bundle.main.path(forResource: "QHSohuGifSort.plist", ofType: nil) else { return } let giftEmotions: [String] = NSArray(contentsOfFile: giftPath) as! [String] emotionsArray.append(giftEmotions) } } extension GiftBoardView: EmotionViewDataSource { func numberOfSections(in emotionView: EmotionView) -> Int { return emotionsArray.count } func numberOfItemsInSection(emotionView: EmotionView, section: Int) -> Int { return emotionsArray[section].count } func collectionView(emotionView: EmotionView, collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: GiftViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: giftViewCellID, for: indexPath) as! GiftViewCell return cell } } extension GiftBoardView: EmotionViewDelegate { func collectionView(collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } }
28778fad54b3cc6dd546251380bf7b20
34.811765
267
0.691853
false
false
false
false
gobetti/Swift
refs/heads/master
Airdrop/Airdrop/ImageViewController.swift
mit
1
// // ImageViewController.swift // Airdrop // // Created by Carlos Butron on 12/04/15. // Copyright (c) 2015 Carlos Butron. All rights reserved. // import UIKit import MediaPlayer import MobileCoreServices class ImageViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var image: UIImageView! @IBAction func send(sender: UIButton) { let im: UIImage = image.image! let controller = UIActivityViewController(activityItems: [im], applicationActivities: nil) self.presentViewController(controller, animated: true, completion: nil) } @IBAction func album(sender: UIButton) { let pickerC = UIImagePickerController() pickerC.delegate = self self.presentViewController(pickerC, animated: true, completion: nil) } @IBAction func useCamera(sender: UIButton) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera //to select only camera controls, not video controls imagePicker.mediaTypes = [kUTTypeImage as String] imagePicker.showsCameraControls = true //imagePicker.allowsEditing = true self.presentViewController(imagePicker, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){ let imagePickerc = info[UIImagePickerControllerOriginalImage] as! UIImage image.image = imagePickerc self.dismissViewControllerAnimated(true, completion: nil) } func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo: UnsafePointer<()>){ if(error != nil){ print("ERROR IMAGE \(error.debugDescription)") } } func imagePickerControllerDidCancel(picker: UIImagePickerController){ self.dismissViewControllerAnimated(true, completion: nil) } /* // 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. } */ }
46612f30a7098178009ff41664603ec4
29.75
122
0.672676
false
false
false
false
ALHariPrasad/iOS-9-Sampler
refs/heads/master
iOS9Sampler/RootViewController.swift
mit
9
// // RootViewController.swift // iOS9Sampler // // Created by Shuichi Tsutsumi on 2015/06/10. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // import UIKit let kItemKeyTitle = "title" let kItemKeyDetail = "detail" let kItemKeyClassPrefix = "prefix" class RootViewController: UITableViewController { var items: [Dictionary<String, String>]! override func viewDidLoad() { super.viewDidLoad() items = [ [ kItemKeyTitle: "Map Customizations", kItemKeyDetail: "Flyover can be selected with new map types, and Traffic, Scale and Compass can be shown.", kItemKeyClassPrefix: "MapCustomizations" ], [ kItemKeyTitle: "Text Detector", kItemKeyDetail: "Text detection using new detector type \"CIDetectorTypeText\".", kItemKeyClassPrefix: "TextDetect" ], [ kItemKeyTitle: "New Image Filters", kItemKeyDetail: "New filters of CIFilter which can be used for Still Images.", kItemKeyClassPrefix: "StillImageFilters", ], [ kItemKeyTitle: "Audio Unit Component Manager", kItemKeyDetail: "Retrieve available audio units using AudioUnitComponentManager and apply them to a sound. If there are some Audio Unit Extensions, they will be also shown.", kItemKeyClassPrefix: "AudioUnitComponentManager", ], [ kItemKeyTitle: "Speech Voices", kItemKeyDetail: "Example for new properties which are added to AVSpeechSynthesisVoice such as language, name, quality...", kItemKeyClassPrefix: "Speech", ], [ kItemKeyTitle: "CASpringAnimation", kItemKeyDetail: "Animation example using CASpringAnimation.", kItemKeyClassPrefix: "Spring" ], [ kItemKeyTitle: "UIStackView", kItemKeyDetail: "Auto Layout example using UIStackView.", kItemKeyClassPrefix: "StackView" ], [ kItemKeyTitle: "Selfies & Screenshots", kItemKeyDetail: "Fetch photos filtered with new subtypes \"SelfPortraits\" and \"Screenshot\" which are added to Photos framework.", kItemKeyClassPrefix: "Photos" ], [ kItemKeyTitle: "String Transform", kItemKeyDetail: "String transliteration examples using new APIs of Foundation framework.", kItemKeyClassPrefix: "StringTransform" ], [ kItemKeyTitle: "Search APIs", kItemKeyDetail: "Example for Search APIs using NSUserActivity and Core Spotlight.", kItemKeyClassPrefix: "SearchAPIs" ], [ kItemKeyTitle: "Content Blockers", kItemKeyDetail: "Example for Content Blocker Extension.", kItemKeyClassPrefix: "ContentBlocker" ], [ kItemKeyTitle: "SFSafariViewController", kItemKeyDetail: "Open web pages with SFSafariViewController.", kItemKeyClassPrefix: "Safari" ], [ kItemKeyTitle: "Attributes of New Filters", kItemKeyDetail: "Extract new filters of CIFilter using \"kCIAttributeFilterAvailable_iOS\".", kItemKeyClassPrefix: "Filters" ], [ kItemKeyTitle: "Low Power Mode", kItemKeyDetail: "Detect changes of \"Low Power Mode\" setting.", kItemKeyClassPrefix: "LowPowerMode" ], [ kItemKeyTitle: "New Fonts", kItemKeyDetail: "Gallery of new fonts.", kItemKeyClassPrefix: "Fonts" ], [ kItemKeyTitle: "Contacts", kItemKeyDetail: "Contacts framework sample.", kItemKeyClassPrefix: "Contacts" ], [ kItemKeyTitle: "Quick Actions", kItemKeyDetail: "Access the shortcut menu on the Home screen using 3D Touch.", kItemKeyClassPrefix: "QuickActions" ], [ kItemKeyTitle: "Force Touch", kItemKeyDetail: "Visualize the forces of touches using new properties of UITouch.", kItemKeyClassPrefix: "ForceTouch" ], ] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // ========================================================================= // MARK: - UITableViewDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! RootViewCell let item = items[indexPath.row] cell.titleLabel!.text = item[kItemKeyTitle] cell.detailLabel!.text = item[kItemKeyDetail] return cell } // ========================================================================= // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = items[indexPath.row] let prefix = item[kItemKeyClassPrefix] let storyboard = UIStoryboard(name: prefix!, bundle: nil) let controller = storyboard.instantiateInitialViewController() self.navigationController?.pushViewController(controller!, animated: true) controller!.title = item[kItemKeyTitle] tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
fcb16d13ca4037dcb4830decfc2ba656
37.252941
190
0.570352
false
false
false
false
Mclarenyang/medicine_aid
refs/heads/master
medicine aid/NewPlayground.playground/Contents.swift
apache-2.0
1
//: Playground - noun: a place where people can play import UIKit import CryptoSwift //-----------加密算法--------------// //密钥字符串(字符串 1)进行 MD5 加密后,得到一组新的字符串(字符串 2),将字符串 2 打散成为 byte 数组,并用此数组对需要加密的字符串(字符串 3)进行 AES 加密,得到加密字符串(字符串 4) //密钥字符串 //let key = "nmid.igds.nick_name" let key = "nmid.igds.phone_number" //let key = "nmid.igds.password" //md5加密 let hash = key.md5() //打散称为Byte let byteKey = Array<UInt8>(hex: hash) let iv:[UInt8] = [] //加密 let aes = try AES(key: byteKey, iv: iv, blockMode: .ECB, padding: PKCS7()) let ps = "1246774880".data(using: String.Encoding.utf8) let encrypted = try aes.encrypt(ps!.bytes) //16进制 let encode = encrypted.toHexString() //-----------解密算法--------------// //密钥字符串(字符串 1)进行 MD5 加密后,得到一组新的字符串(字符串 2), 将字符串 2 打散成为 byte 数组,并用此数组对需要解密的字符串(字符串 4)进行 AES 解密,得到解密字符串(字符串 3) //接收到的数据 let my = "ed3745a30ebda266b134fecdc0e8ba23" let data = Array<UInt8>(hex: my) //解密 let decrypted = try AES(key: byteKey, iv: iv, blockMode: .ECB, padding: PKCS7()).decrypt(data) //转码 let dataStr = NSData(bytes: decrypted, length: decrypted.count) let str = String(data: dataStr as Data, encoding: String.Encoding.utf8)!
a4dde69005f1671d9b36f693aaf2833a
24.977273
108
0.67629
false
false
false
false
StormXX/STTableBoard
refs/heads/master
STTableBoardDemo/BoardCardCell.swift
cc0-1.0
1
// // BoardCardCell.swift // STTableBoardDemo // // Created by DangGu on 15/12/21. // Copyright © 2015年 StormXX. All rights reserved. // import UIKit import STTableBoard class BoardCardCell: STBoardCell { fileprivate lazy var cardView: CardView = { let view = CardView() view.backgroundColor = UIColor.clear return view }() fileprivate lazy var titleLabel: UILabel = { let label = UILabel(frame: CGRect.zero) label.numberOfLines = 2 label.textAlignment = .left label.font = UIFont.systemFont(ofSize: 15.0) label.lineBreakMode = .byTruncatingTail label.textColor = UIColor(red: 56/255.0, green: 56/255.0, blue: 56/255.0, alpha: 1.0) return label }() fileprivate lazy var checkBoxView: CheckBoxView = { let view = CheckBoxView(frame: CGRect.zero) view.checked = false return view }() fileprivate lazy var avatarView: RoundAvatarImageView = { let view = RoundAvatarImageView(frame: CGRect.zero) return view }() fileprivate lazy var badgeListView: BadgeListView = { let view = BadgeListView() return view }() fileprivate var hasLoadTag: Bool = false var titleText: String? { didSet { titleLabel.text = titleText } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupProperty() } func setupProperty() { // backgroundView = backgroundImageView contentView.addSubview(cardView) cardView.addSubview(checkBoxView) cardView.addSubview(avatarView) cardView.addSubview(titleLabel) cardView.addSubview(badgeListView) avatarView.image = UIImage(named: "avatar") setupConstrains() } func setupConstrains() { cardView.translatesAutoresizingMaskIntoConstraints = false checkBoxView.translatesAutoresizingMaskIntoConstraints = false avatarView.translatesAutoresizingMaskIntoConstraints = false titleLabel.translatesAutoresizingMaskIntoConstraints = false badgeListView.translatesAutoresizingMaskIntoConstraints = false let views = ["checkBoxView":checkBoxView, "avatarView":avatarView, "titleLabel":titleLabel] as [String : Any] let leading = 8, trailing = 8, top = 2, bottom = 2 let cardViewHorizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-leading-[cardView]-trailing-|", options: [], metrics: ["leading":leading, "trailing":trailing], views: ["cardView":cardView]) let cardViewVerticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-top-[cardView]-bottom-|", options: [], metrics: ["top":top, "bottom":bottom], views: ["cardView":cardView]) NSLayoutConstraint.activate(cardViewHorizontalConstraints + cardViewVerticalConstraints) let checkBoxWidth: CGFloat = 16.0, avatarWidth: CGFloat = 24.0 let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "|-12-[checkBoxView(==checkBoxWidth)]-8-[avatarView(==avatarWidth)]-8-[titleLabel]-10-|", options: [], metrics: ["checkBoxWidth":checkBoxWidth, "avatarWidth":avatarWidth], views: views) let checkboxHeightConstraint = NSLayoutConstraint(item: checkBoxView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: checkBoxWidth) let avatarHeightConstraints = NSLayoutConstraint(item: avatarView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: avatarWidth) let checkboxTopConstraint = NSLayoutConstraint(item: checkBoxView, attribute: .top, relatedBy: .equal, toItem: cardView, attribute: .top, multiplier: 1.0, constant: 13.0) let avatarTopConstraint = NSLayoutConstraint(item: avatarView, attribute: .top, relatedBy: .equal, toItem: cardView, attribute: .top, multiplier: 1.0, constant: 10.0) let titleLabelTopConstraint = NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: cardView, attribute: .top, multiplier: 1.0, constant: 14.0) let badgeListViewHorizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "|-36-[badgeListView]-8-|", options: [], metrics: nil, views: ["badgeListView":badgeListView]) let badgeListViewTopConstraint = NSLayoutConstraint(item: badgeListView, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1.0, constant: 12.0) NSLayoutConstraint.activate(horizontalConstraints + [checkboxHeightConstraint, checkboxTopConstraint, avatarHeightConstraints, avatarTopConstraint, titleLabelTopConstraint, badgeListViewTopConstraint] + badgeListViewHorizontalConstraints) } override func layoutSubviews() { super.layoutSubviews() if !hasLoadTag { cardView.layoutIfNeeded() let badge: BadgeView = BadgeView(frame: CGRect.zero) badge.image = UIImage(named: "dueDate_icon") badge.backgroundImage = UIImage(named: "dueDate_background") badge.text = "16 Oct" badge.textColor = UIColor.white badge.imageWidth = 8.0 badge.sizeToFit() badge.textFont = UIFont.systemFont(ofSize: 10.0) let bbadge: BadgeView = BadgeView(frame: CGRect.zero) bbadge.image = UIImage(named: "tag_icon") bbadge.backgroundImage = UIImage(named: "tag_background") bbadge.text = "交互设计" bbadge.textColor = UIColor.gray bbadge.imageWidth = 4.0 bbadge.sizeToFit() bbadge.textFont = UIFont.systemFont(ofSize: 10.0) let cbadge: BadgeView = BadgeView(frame: CGRect.zero) cbadge.image = UIImage(named: "subtask_icon") cbadge.imageWidth = 9.0 cbadge.text = "2/3" cbadge.textColor = UIColor.gray cbadge.sizeToFit() cbadge.textFont = UIFont.systemFont(ofSize: 10.0) badgeListView.addBadge(badge) badgeListView.addBadge(bbadge) badgeListView.addBadge(cbadge) hasLoadTag = true } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
dd75f6d74cd08966a18fb27d784d2df9
45.503546
270
0.665853
false
false
false
false
apple/swift-experimental-string-processing
refs/heads/main
Tests/Prototypes/PEG/PEGTranspile.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// @testable import _StringProcessing extension PEG.VM where Input == String { typealias MEProg = MEProgram func transpile() throws -> MEProg { typealias Builder = MEProg.Builder var builder = MEProg.Builder() // Address token info // // TODO: Could builder provide a generalized mapping table? typealias TokenEntry = (Builder.AddressToken, use: InstructionAddress, target: InstructionAddress) var addressTokens = Array<TokenEntry>() for idx in instructions.indices { if let address = instructions[idx].pc { addressTokens.append( (builder.makeAddress(), use: idx, target: address)) } } var nextTokenIdx = addressTokens.startIndex func nextToken() -> Builder.AddressToken { defer { addressTokens.formIndex(after: &nextTokenIdx) } return addressTokens[nextTokenIdx].0 } for idx in instructions.indices { defer { // TODO: Linear is probably fine... for (tok, _, _) in addressTokens.lazy.filter({ $0.target == idx }) { builder.resolve(tok) } } switch instructions[idx] { case .nop: builder.buildNop() case .comment(let s): builder.buildNop(s) case .consume(let n): builder.buildAdvance(Distance(n)) case .branch(_): builder.buildBranch(to: nextToken()) case .condBranch(let condition, _): // TODO: Need to map our registers over... _ = condition fatalError()//builder.buildCondBranch(condition, to: nextToken()) case .save(_): builder.buildSave(nextToken()) case .clear: builder.buildClear() case .restore: builder.buildRestore() case .push(_): fatalError() case .pop: fatalError() case .call(_): builder.buildCall(nextToken()) case .ret: builder.buildRet() case .assert(_,_): fatalError()//builder.buildAssert(e, r) case .assertPredicate(_, _): fatalError()//builder.buildAssertPredicate(p, r) case .match(let e): builder.buildMatch(e) case .matchPredicate(let p): builder.buildConsume { input, bounds in p(input[bounds.lowerBound]) ? input.index(after: bounds.lowerBound) : nil } case .matchHook(_): fatalError()//builder.buildMatchHook(h) case .assertHook(_, _): fatalError()//builder.buildAssertHook(h, r) case .accept: builder.buildAccept() case .fail: builder.buildFail() case .abort(let s): builder.buildAbort(s) } } return try builder.assemble() } } extension PEG.Program where Element == Character { public func transpile( ) throws -> Engine<String> { try Engine(compile(for: String.self).vm.transpile()) } }
81c57f038d62227a91f3e1b4a7660abc
27.101695
81
0.579312
false
false
false
false
DianQK/rx-sample-code
refs/heads/master
PDFExpertContents/ExpandableItem.swift
mit
1
// // ExpandableItem.swift // PDF-Expert-Contents // // Created by DianQK on 17/09/2016. // Copyright © 2016 DianQK. All rights reserved. // import Foundation import RxSwift import RxCocoa import RxDataSources import RxExtensions struct ExpandableItem<Model: IdentifiableType & Hashable> { let model: Model let isExpanded: Variable<Bool> private let _subItems: Variable<[ExpandableItem]> = Variable([]) let canExpanded: Bool private let disposeBag = DisposeBag() var subItems: Observable<[ExpandableItem]> { return self._subItems.asObservable() } init(model: Model, isExpanded: Bool, subItems: [ExpandableItem]) { self.model = model self.canExpanded = !subItems.isEmpty if self.canExpanded { self.isExpanded = Variable(isExpanded) let displaySubItems = Variable<[ExpandableItem]>([]) // 一次绑定 _subItems.asObservable().filter { !$0.isEmpty }.bindTo(displaySubItems).disposed(by: disposeBag) // 1. combine combineSubItems(subItems).asObservable().bindTo(_subItems).disposed(by: disposeBag) // 2. handle expand // 不要交换 1 2 的顺序 self.isExpanded.asObservable() .map { isExpanded in isExpanded ? displaySubItems.value : [] } .bindTo(_subItems) .disposed(by: disposeBag) } else { self.isExpanded = Variable(false) } } let combineSubItems: (_ subItems: [ExpandableItem]) -> Observable<[ExpandableItem]> = { subItems in return subItems.reduce(Observable<[ExpandableItem]>.just([])) { (acc, x) in Observable.combineLatest(acc, Observable.just([x]), x._subItems.asObservable(), resultSelector: { $0 + $1 + $2 }) } } } extension ExpandableItem: IdentifiableType, Equatable, Hashable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func ==(lhs: ExpandableItem, rhs: ExpandableItem) -> Bool { return lhs.model == rhs.model } var hashValue: Int { return model.hashValue } var identity: Model.Identity { return model.identity } }
c7c68f5d27db1a24c2490278810621bd
28.341176
125
0.607458
false
false
false
false
a2/RxSwift
refs/heads/master
RxExample/RxExample/Examples/WikipediaImageSearch/ViewModels/SearchViewModel.swift
mit
13
// // SearchViewModel.swift // Example // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class SearchViewModel { // outputs let rows: Observable<[SearchResultViewModel]> let subscriptions = DisposeBag() // public methods init(searchText: Observable<String>, selectedResult: Observable<SearchResultViewModel>) { let $: Dependencies = Dependencies.sharedDependencies let wireframe = Dependencies.sharedDependencies.wireframe let API = DefaultWikipediaAPI.sharedAPI self.rows = searchText .throttle(0.3, $.mainScheduler) .distinctUntilChanged() .map { query in API.getSearchResults(query) .retry(3) .startWith([]) // clears results on new search term .catchErrorJustReturn([]) } .switchLatest() .map { results in results.map { SearchResultViewModel( searchResult: $0 ) } } selectedResult .subscribeNext { searchResult in wireframe.openURL(searchResult.searchResult.URL) } .addDisposableTo(subscriptions) } }
aeaba2b49e64f3a567ea99c8e208bb7c
25.178571
71
0.551536
false
false
false
false
bitboylabs/selluv-ios
refs/heads/master
selluv-ios/selluv-ios/Classes/Base/Model/Manager/SLVDnImageModel.swift
mit
1
// // SLVDnImageModel.swift // selluv-ios // // Created by 조백근 on 2017. 1. 24.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import UIKit import Foundation import SwiftyJSON import ObjectMapper import AlamofireObjectMapper import Moya import PINRemoteImage import PINCache class SLVDnImageModel: NSObject { static let shared = SLVDnImageModel() let remoteImageManager = PINRemoteImageManager.shared() override init() { super.init() self.resetCache() self.setupRemoteImageManager() self.memoryWarningObserver() } func memoryWarningObserver() { let selector = #selector(SLVDnImageModel.resetCache) Noti.addObserver(self, selector: selector, name: Notification.Name.UIApplicationDidReceiveMemoryWarning, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } func setupRemoteImageManager() { remoteImageManager.setProgressThresholds([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], completion: nil) } func resetCache() { remoteImageManager.cache.removeAllObjects() } func setupImageView(view: UIImageView, from: URL) { view.pin_updateWithProgress = true remoteImageManager.cache.removeObject(forKey: PINRemoteImageManager.shared().cacheKey(for: from, processorKey: nil)) view.pin_setImage(from: from) } func setupProcessingImageView(view: UIImageView, from: URL, size: CGSize) { remoteImageManager.cache.removeObject(forKey: PINRemoteImageManager.shared().cacheKey(for: from, processorKey: nil)) view.pin_setImage(from: from, processorKey: "rounded") { (result, unsafePointer) -> UIImage? in guard let image = result.image else { return nil } let radius : CGFloat = 7.0 let targetSize = size let imageRect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height) UIGraphicsBeginImageContext(imageRect.size) let bezierPath = UIBezierPath(roundedRect: imageRect, cornerRadius: radius) bezierPath.addClip() let widthMultiplier : CGFloat = targetSize.width / image.size.width let heightMultiplier : CGFloat = targetSize.height / image.size.height let sizeMultiplier = max(widthMultiplier, heightMultiplier) var drawRect = CGRect(x: 0, y: 0, width: image.size.width * sizeMultiplier, height: image.size.height * sizeMultiplier) if (drawRect.maxX > imageRect.maxX) { drawRect.origin.x -= (drawRect.maxX - imageRect.maxX) / 2 } if (drawRect.maxY > imageRect.maxY) { drawRect.origin.y -= (drawRect.maxY - imageRect.maxY) / 2 } image.draw(in: drawRect) // UIColor.white.setStroke() // bezierPath.lineWidth = 0 // bezierPath.stroke() let ctx = UIGraphicsGetCurrentContext() // ctx?.setBlendMode(CGBlendMode.normal) // ctx?.setAlpha(0.5) // // let logo = UIImage(named: "") // ctx?.scaleBy(x: 1.0, y: -1.0) // ctx?.translateBy(x: 0.0, y: -drawRect.size.height) // // if let coreGraphicsImage = logo?.cgImage {//로고이미지 합성됨... // ctx?.draw(coreGraphicsImage, in: CGRect(x: 90, y: 10, width: logo!.size.width, height: logo!.size.height)) // } let processedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return processedImage } } func setupImageView(view: UIImageView, fromList: [URL]) { view.pin_setImage(from: fromList) } func loadUserProfile() { } }
c6aa94182c107c1fc56f3151565735f3
33.198276
131
0.600454
false
false
false
false
jmgc/swift
refs/heads/master
test/Constraints/diagnostics.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift protocol P { associatedtype SomeType } protocol P2 { func wonka() } extension Int : P { typealias SomeType = Int } extension Double : P { typealias SomeType = Double } func f0(_ x: Int, _ y: Float) { } func f1(_: @escaping (Int, Float) -> Int) { } func f2(_: (_: (Int) -> Int)) -> Int {} func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {} func f4(_ x: Int) -> Int { } func f5<T : P2>(_ : T) { } // expected-note@-1 {{required by global function 'f5' where 'T' = '(Int) -> Int'}} // expected-note@-2 {{required by global function 'f5' where 'T' = '(Int, String)'}} // expected-note@-3 {{required by global function 'f5' where 'T' = 'Int.Type'}} // expected-note@-4 {{where 'T' = 'Int'}} func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {} var i : Int var d : Double // Check the various forms of diagnostics the type checker can emit. // Tuple size mismatch. f1( f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}} ) // Tuple element unused. f0(i, i, // expected-error@:7 {{cannot convert value of type 'Int' to expected argument type 'Float'}} i) // expected-error{{extra argument in call}} // Cannot conform to protocols. f5(f4) // expected-error {{type '(Int) -> Int' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} f5((1, "hello")) // expected-error {{type '(Int, String)' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} f5(Int.self) // expected-error {{type 'Int.Type' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} // Tuple element not convertible. f0(i, d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}} ) // Function result not a subtype. f1( f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}} ) f3( f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}} ) f4(i, d) // expected-error {{extra argument in call}} // Missing member. i.missingMember() // expected-error{{value of type 'Int' has no member 'missingMember'}} // Generic member does not conform. extension Int { func wibble<T: P2>(_ x: T, _ y: T) -> T { return x } // expected-note {{where 'T' = 'Int'}} func wubble<T>(_ x: (Int) -> T) -> T { return x(self) } } i.wibble(3, 4) // expected-error {{instance method 'wibble' requires that 'Int' conform to 'P2'}} // Generic member args correct, but return type doesn't match. struct A : P2 { func wonka() {} } let a = A() for j in i.wibble(a, a) { // expected-error {{for-in loop requires 'A' to conform to 'Sequence'}} } // Generic as part of function/tuple types func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}} return (c: 0, i: g(())) } func f7() -> (c: Int, v: A) { let g: (Void) -> A = { _ in return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}} return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}} } func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}} // expected-note@-1 {{required by global function 'f8' where 'T' = 'Tup' (aka '(Int, Double)')}} f8(3, f4) // expected-error {{global function 'f8' requires that 'Int' conform to 'P2'}} typealias Tup = (Int, Double) func f9(_ x: Tup) -> Tup { return x } f8((1,2.0), f9) // expected-error {{type 'Tup' (aka '(Int, Double)') cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} // <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals 1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}} [1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}} "awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}} // Does not conform to protocol. f5(i) // expected-error {{global function 'f5' requires that 'Int' conform to 'P2'}} // Make sure we don't leave open existentials when diagnosing. // <rdar://problem/20598568> func pancakes(_ p: P2) { f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}} f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}} } protocol Shoes { static func select(_ subject: Shoes) -> Self } // Here the opaque value has type (metatype_type (archetype_type ... )) func f(_ x: Shoes, asType t: Shoes.Type) { return t.select(x) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } precedencegroup Starry { associativity: left higherThan: MultiplicationPrecedence } infix operator **** : Starry func ****(_: Int, _: String) { } i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} infix operator ***~ : Starry func ***~(_: Int, _: String) { } i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} @available(*, unavailable, message: "call the 'map()' method on the sequence") public func myMap<C : Collection, T>( _ source: C, _ transform: (C.Iterator.Element) -> T ) -> [T] { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "call the 'map()' method on the optional value") public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? { fatalError("unavailable function can't be called") } // <rdar://problem/20142523> func rdar20142523() { myMap(0..<10, { x in // expected-error{{unable to infer complex closure return type; add explicit type to disambiguate}} {{21-21=-> <#Result#> }} {{educational-notes=complex-closure-inference}} () return x }) } // <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral func rdar21080030() { var s = "Hello" // SR-7599: This should be `cannot_call_non_function_value` if s.count() == 0 {} // expected-error{{cannot call value of non-function type 'Int'}} {{13-15=}} } // <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}} r21248136() // expected-error {{generic parameter 'T' could not be inferred}} let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}} // <rdar://problem/17080659> Error Message QOI - wrong return type in an overload func recArea(_ h: Int, w : Int) { return h * w // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong func r17224804(_ monthNumber : Int) { // expected-error@+1:49 {{cannot convert value of type 'Int' to expected argument type 'String'}} let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber) } // <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?' func r17020197(_ x : Int?, y : Int) { if x! { } // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} // <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible if y {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} } // <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different func validateSaveButton(_ text: String) { return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}} expected-note {{did you mean to add a return type?}} } // <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype class r20201968C { func blah() { r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}} } } // <rdar://problem/21459429> QoI: Poor compilation error calling assert func r21459429(_ a : Int) { assert(a != nil, "ASSERT COMPILATION ERROR") // expected-warning @-1 {{comparing non-optional value of type 'Int' to 'nil' always returns true}} } // <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an argument of type 'Int' struct StructWithOptionalArray { var array: [Int]? } func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int { return foo.array[0] // expected-error {{value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'}} // expected-note@-1{{chain the optional using '?' to access member 'subscript' only for non-'nil' base values}}{{19-19=?}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{19-19=!}} } // <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}} // <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf String().asdf // expected-error {{value of type 'String' has no member 'asdf'}} // <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment protocol r21553065Protocol {} class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}} _ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Class' requires that 'r21553065Protocol' be a class type}} // Type variables not getting erased with nested closures struct Toe { let toenail: Nail // expected-error {{cannot find type 'Nail' in scope}} func clip() { toenail.inspect { x in toenail.inspect { y in } } } } // <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic class r21447318 { var x = 42 func doThing() -> r21447318 { return self } } func test21447318(_ a : r21447318, b : () -> r21447318) { a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}} b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}} } // <rdar://problem/20409366> Diagnostics for init calls should print the class name class r20409366C { init(a : Int) {} init?(a : r20409366C) { let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}} } } // <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match func r18800223(_ i : Int) { // 20099385 _ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}} // 19648528 _ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}} var buttonTextColor: String? _ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}} } // <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back _ = { $0 } // expected-error {{unable to infer type of a closure parameter $0 in the current context}} _ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}} _ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}} // <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure. func rdar21784170() { let initial = (1.0 as Double, 2.0 as Double) (Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}} } // Diagnose passing an array in lieu of variadic parameters func variadic(_ x: Int...) {} func variadicArrays(_ x: [Int]...) {} func variadicAny(_ x: Any...) {} struct HasVariadicSubscript { subscript(_ x: Int...) -> Int { get { 0 } } } let foo = HasVariadicSubscript() let array = [1,2,3] let arrayWithOtherEltType = ["hello", "world"] variadic(array) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} variadic([1,2,3]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}} variadic([1,2,3,]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}} {{17-18=}} variadic(0, array, 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} variadic(0, [1,2,3], 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{13-14=}} {{19-20=}} variadic(0, [1,2,3,], 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{13-14=}} {{19-20=}} {{20-21=}} variadic(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}} variadic(1, arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}} // FIXME: SR-11104 variadic(["hello", "world"]) // expected-error 2 {{cannot convert value of type 'String' to expected element type 'Int'}} // expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-2 {{remove brackets to pass array elements directly}} variadic([1] + [2] as [Int]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} foo[array] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} foo[[1,2,3]] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{5-6=}} {{11-12=}} foo[0, [1,2,3], 4] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{8-9=}} {{14-15=}} variadicAny(array) variadicAny([1,2,3]) variadicArrays(array) variadicArrays([1,2,3]) variadicArrays(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type '[Int]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} variadicArrays(1,2,3) // expected-error 3 {{cannot convert value of type 'Int' to expected argument type '[Int]'}} protocol Proto {} func f<T: Proto>(x: [T]) {} func f(x: Int...) {} f(x: [1,2,3]) // TODO(diagnostics): Diagnose both the missing conformance and the disallowed array splat to cover both overloads. // expected-error@-2 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-3 {{remove brackets to pass array elements directly}} // <rdar://problem/21829141> BOGUS: unexpected trailing closure func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } } func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } } let expectType1 = expect(Optional(3))(Optional<Int>.self) let expectType1Check: Int = expectType1 // <rdar://problem/19804707> Swift Enum Scoping Oddity func rdar19804707() { enum Op { case BinaryOperator((Double, Double) -> Double) } var knownOps : Op knownOps = Op.BinaryOperator({$1 - $0}) knownOps = Op.BinaryOperator(){$1 - $0} knownOps = Op.BinaryOperator{$1 - $0} knownOps = .BinaryOperator({$1 - $0}) // rdar://19804707 - trailing closures for contextual member references. knownOps = .BinaryOperator(){$1 - $0} knownOps = .BinaryOperator{$1 - $0} _ = knownOps } // <rdar://problem/20491794> Error message does not tell me what the problem is enum Color { case Red case Unknown(description: String) static func rainbow() -> Color {} static func overload(a : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(a:)')}} // expected-note@-1 {{candidate expects value of type 'Int' for parameter #1}} static func overload(b : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(b:)')}} // expected-note@-1 {{candidate expects value of type 'Int' for parameter #1}} static func frob(_ a : Int, b : inout Int) -> Color {} static var svar: Color { return .Red } } let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error@-1 {{cannot convert value of type 'Array<(Int, _)>' to specified type '(Int, Color)'}} // expected-error@-2 {{cannot infer contextual base in reference to member 'Unknown'}} let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }} let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }} let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }} let _: Color = .Unknown // expected-error {{member 'Unknown(description:)' expects argument of type 'String'}} let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}} // expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'String'}} let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}} let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type '(Double, Float)' to specified type '(Int, Float)'}} let _ : Color = .rainbow // expected-error {{member 'rainbow()' is a function that produces expected type 'Color'; did you mean to call it?}} {{25-25=()}} let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .overload(1.0) // expected-error {{no exact matches in call to static method 'overload'}} let _: Color = .overload(1) // expected-error {{no exact matches in call to static method 'overload'}} let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{28-28=&}} let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}} someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}} someColor = .svar() // expected-error {{cannot call value of non-function type 'Color'}} someColor = .svar(1) // expected-error {{cannot call value of non-function type 'Color'}} func testTypeSugar(_ a : Int) { typealias Stride = Int let x = Stride(a) x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } // <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr func r21974772(_ y : Int) { let x = &(1.0 + y) // expected-error {{use of extraneous '&'}} } // <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc protocol r22020088P {} func r22020088Foo<T>(_ t: T) {} func r22020088bar(_ p: r22020088P?) { r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}} } // <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type func f(_ arguments: [String]) -> [ArraySlice<String>] { return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" }) } struct AOpts : OptionSet { let rawValue : Int } class B { func function(_ x : Int8, a : AOpts) {} func f2(_ a : AOpts) {} static func f1(_ a : AOpts) {} } class GenClass<T> {} struct GenStruct<T> {} enum GenEnum<T> {} func test(_ a : B) { B.f1(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} a.function(42, a: nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} a.function(42, nil) // expected-error {{missing argument label 'a:' in call}} // expected-error@-1 {{'nil' is not compatible with expected argument type 'AOpts'}} a.f2(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} func foo1(_ arg: Bool) -> Int {return nil} func foo2<T>(_ arg: T) -> GenClass<T> {return nil} func foo3<T>(_ arg: T) -> GenStruct<T> {return nil} func foo4<T>(_ arg: T) -> GenEnum<T> {return nil} // expected-error@-4 {{'nil' is incompatible with return type 'Int'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenClass<T>'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenStruct<T>'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenEnum<T>'}} let clsr1: () -> Int = {return nil} let clsr2: () -> GenClass<Bool> = {return nil} let clsr3: () -> GenStruct<String> = {return nil} let clsr4: () -> GenEnum<Double?> = {return nil} // expected-error@-4 {{'nil' is not compatible with closure result type 'Int'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenClass<Bool>'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenStruct<String>'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenEnum<Double?>'}} var number = 0 var genClassBool = GenClass<Bool>() var funcFoo1 = foo1 number = nil genClassBool = nil funcFoo1 = nil // expected-error@-3 {{'nil' cannot be assigned to type 'Int'}} // expected-error@-3 {{'nil' cannot be assigned to type 'GenClass<Bool>'}} // expected-error@-3 {{'nil' cannot be assigned to type '(Bool) -> Int'}} } // <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure typealias MyClosure = ([Int]) -> Bool func r21684487() { var closures = Array<MyClosure>() let testClosure = {(list: [Int]) -> Bool in return true} let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions;}} } // <rdar://problem/18397777> QoI: special case comparisons with nil func r18397777(_ d : r21447318?) { let c = r21447318() if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to 'nil' always returns true}} } if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}} } if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{8-8= == nil)}} } if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{18-18= == nil)}} } } // <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list func r22255907_1<T>(_ a : T, b : Int) {} func r22255907_2<T>(_ x : Int, a : T, b: Int) {} func reachabilityForInternetConnection() { var variable: Int = 42 r22255907_1(&variable, b: 2) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}} r22255907_2(1, a: &variable, b: 2)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}} } // <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}} _ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}} // <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init func r22263468(_ a : String?) { typealias MyTuple = (Int, String) // TODO(diagnostics): This is a regression from diagnosing missing optional unwrap for `a`, we have to // re-think the way errors in tuple elements are detected because it's currently impossible to detect // exactly what went wrong here and aggregate fixes for different elements at the same time. _ = MyTuple(42, a) // expected-error {{tuple type 'MyTuple' (aka '(Int, String)') is not convertible to tuple type '(Int, String?)'}} } // rdar://22470302 - Crash with parenthesized call result. class r22470302Class { func f() {} } func r22470302(_ c: r22470302Class) { print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}} } // <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile extension String { @available(*, unavailable, message: "calling this is unwise") func unavail<T : Sequence> // expected-note {{'unavail' has been explicitly marked unavailable here}} (_ a : T) -> String where T.Iterator.Element == String {} } extension Array { func g() -> String { return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } func h() -> String { return "foo".unavail([0]) // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}} } } // <rdar://problem/22519983> QoI: Weird error when failing to infer archetype func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {} // expected-note @-1 {{in call to function 'safeAssign'}} let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure struct Radar21692808<Element> { init(count: Int, value: Element) {} // expected-note {{'init(count:value:)' declared here}} } func radar21692808() -> Radar21692808<Int> { return Radar21692808<Int>(count: 1) { // expected-error {{trailing closure passed to parameter of type 'Int' that does not accept a closure}} return 1 } } // <rdar://problem/17557899> - This shouldn't suggest calling with (). func someOtherFunction() {} func someFunction() -> () { // Producing an error suggesting that this return someOtherFunction // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic func r23560128() { var a : (Int,Int)? a.0 = 42 // expected-error{{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}} // expected-note@-1{{chain the optional }} } // <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping struct ExampleStruct21890157 { var property = "property" } var example21890157: ExampleStruct21890157? example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' must be unwrapped to refer to member 'property' of wrapped base type 'ExampleStruct21890157'}} // expected-note@-1{{chain the optional }} struct UnaryOp {} _ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}} // expected-note@-1 {{overloads for '-' exist with these partially matching parameter lists: (Double), (Float)}} // <rdar://problem/23433271> Swift compiler segfault in failure diagnosis func f23433271(_ x : UnsafePointer<Int>) {} func segfault23433271(_ a : UnsafeMutableRawPointer) { f23433271(a[0]) // expected-error {{value of type 'UnsafeMutableRawPointer' has no subscripts}} } // <rdar://problem/23272739> Poor diagnostic due to contextual constraint func r23272739(_ contentType: String) { let actualAcceptableContentTypes: Set<String> = [] return actualAcceptableContentTypes.contains(contentType) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets func r23641896() { var g = "Hello World" g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<String.Index>'}} _ = g[12] // expected-error {{'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.}} } // <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note func test17875634() { var match: [(Int, Int)] = [] var row = 1 var col = 2 match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}} } // <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values enum AssocTest { case one(Int) } // FIXME(rdar://problem/65688291) - on iOS simulator this diagnostic is flaky, // either `referencing operator function '==' on 'Equatable'` or `operator function '==' requires` if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{requires that 'AssocTest' conform to 'Equatable'}} // expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}} // <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types func r24251022() { var a = 1 var b: UInt32 = 2 _ = a + b // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UInt32, UInt32)}} a += a + b // expected-error {{cannot convert value of type 'UInt32' to expected argument type 'Int'}} a += b // expected-error@:8 {{cannot convert value of type 'UInt32' to expected argument type 'Int'}} } func overloadSetResultType(_ a : Int, b : Int) -> Int { // https://twitter.com/_jlfischer/status/712337382175952896 // TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}} } postfix operator +++ postfix func +++ <T>(_: inout T) -> T { fatalError() } // <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) { let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}} _ = bytes[i+++] // expected-error {{cannot pass immutable value to mutating operator: 'i' is a 'let' constant}} } // SR-1594: Wrong error description when using === on non-class types class SR1594 { func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) { _ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}} _ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}} _ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}} _ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}} _ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}} _ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}} } } func nilComparison(i: Int, o: AnyObject) { _ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}} _ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}} _ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}} _ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}} // FIXME(integers): uncomment these tests once the < is no longer ambiguous // _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}} _ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}} _ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}} } // <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion func testImplConversion(a : Float?) -> Bool {} func testImplConversion(a : Int?) -> Bool { let someInt = 42 let a : Int = testImplConversion(someInt) // expected-error {{missing argument label 'a:' in call}} {{36-36=a: }} // expected-error@-1 {{cannot convert value of type 'Bool' to specified type 'Int'}} } // <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands class Foo23752537 { var title: String? var message: String? } extension Foo23752537 { func isEquivalent(other: Foo23752537) { // TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" // expected-error@+1 {{unexpected non-void return value in void function}} return (self.title != other.title && self.message != other.message) // expected-note {{did you mean to add a return type?}} } } // <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" func rdar27391581(_ a : Int, b : Int) -> Int { return a == b && b != 0 // expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}} } // <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {} func read<T : BinaryInteger>() -> T? { var buffer : T let n = withUnsafeMutablePointer(to: &buffer) { (p) in read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<T>' to expected argument type 'UnsafeMutableRawPointer'}} } } func f23213302() { var s = Set<Int>() s.subtract(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}} } // <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context func rdar24202058(a : Int) { return a <= 480 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // SR-1752: Warning about unused result with ternary operator struct SR1752 { func foo() {} } let sr1752: SR1752? true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void // Make sure RawRepresentable fix-its don't crash in the presence of type variables class NSCache<K, V> { func object(forKey: K) -> V? {} } class CacheValue { func value(x: Int) -> Int {} // expected-note {{found candidate with type '(Int) -> Int'}} func value(y: String) -> String {} // expected-note {{found candidate with type '(String) -> String'}} } func valueForKey<K>(_ key: K) -> CacheValue? { let cache = NSCache<K, CacheValue>() return cache.object(forKey: key)?.value // expected-error {{no exact matches in reference to instance method 'value'}} } // SR-1255 func foo1255_1() { return true || false // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } func foo1255_2() -> Int { return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}} } // Diagnostic message for initialization with binary operations as right side let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}} let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}} let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}} // SR-2208 struct Foo2208 { func bar(value: UInt) {} } func test2208() { let foo = Foo2208() let a: Int = 1 let b: Int = 2 let result = a / b foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} foo.bar(value: UInt(result)) // Ok } // SR-2164: Erroneous diagnostic when unable to infer generic type struct SR_2164<A, B> { // expected-note 4 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}} init(a: A) {} init(b: B) {} init(c: Int) {} init(_ d: A) {} init(e: A?) {} } struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}} init(_ a: [A]) {} } struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}} init(a: [A: Double]) {} } SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(c: 2) // expected-error@-1 {{generic parameter 'A' could not be inferred}} // expected-error@-2 {{generic parameter 'B' could not be inferred}} // expected-note@-3 {{explicitly specify the generic arguments to fix this issue}} {{8-8=<Any, Any>}} SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}} SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}} let _ = SR_2164<Int, Bool>(a: 0) // Ok let _ = SR_2164<Int, Bool>(b: true) // Ok SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}} SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}} // <rdar://problem/29850459> Swift compiler misreports type error in ternary expression let r29850459_flag = true let r29850459_a: Int = 0 let r29850459_b: Int = 1 func r29850459() -> Bool { return false } let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} // SR-6272: Tailored diagnostics with fixits for numerical conversions func SR_6272_a() { enum Foo: Int { case bar } // expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{35-35=Int(}} {{43-43=)}} let _: Int = Foo.bar.rawValue * Float(0) // expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{18-18=Float(}} {{34-34=)}} let _: Float = Foo.bar.rawValue * Float(0) // expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}} Foo.bar.rawValue * Float(0) } func SR_6272_b() { let lhs = Float(3) let rhs = Int(0) // expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{24-24=Float(}} {{27-27=)}} let _: Float = lhs * rhs // expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{16-16=Int(}} {{19-19=)}} let _: Int = lhs * rhs // expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{none}} // expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}} lhs * rhs } func SR_6272_c() { // expected-error@+1 {{cannot convert value of type 'String' to expected argument type 'Int'}} {{none}} Int(3) * "0" struct S {} // expected-error@+1 {{cannot convert value of type 'S' to expected argument type 'Int'}} {{none}} Int(10) * S() } struct SR_6272_D: ExpressibleByIntegerLiteral { typealias IntegerLiteralType = Int init(integerLiteral: Int) {} static func +(lhs: SR_6272_D, rhs: Int) -> Float { return 42.0 } } func SR_6272_d() { let x: Float = 1.0 // expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}} let _: Float = SR_6272_D(integerLiteral: 42) + x // expected-error@+1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} {{50-50=Int(}} {{54-54=)}} let _: Float = SR_6272_D(integerLiteral: 42) + 42.0 // expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}} let _: Float = SR_6272_D(integerLiteral: 42) + x + 1.0 } // Ambiguous overload inside a trailing closure func ambiguousCall() -> Int {} // expected-note {{found this candidate}} func ambiguousCall() -> Float {} // expected-note {{found this candidate}} func takesClosure(fn: () -> ()) {} takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}} // SR-4692: Useless diagnostics calling non-static method class SR_4692_a { private static func foo(x: Int, y: Bool) { self.bar(x: x) // expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}} } private func bar(x: Int) { } } class SR_4692_b { static func a() { self.f(x: 3, y: true) // expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}} } private func f(a: Int, b: Bool, c: String) { self.f(x: a, y: b) } private func f(x: Int, y: Bool) { } } // rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful struct R32101765 { let prop32101765 = 0 } let _: KeyPath<R32101765, Float> = \.prop32101765 // expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}} let _: KeyPath<R32101765, Float> = \R32101765.prop32101765 // expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}} let _: KeyPath<R32101765, Float> = \.prop32101765.unknown // expected-error@-1 {{type 'Int' has no member 'unknown'}} let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown // expected-error@-1 {{type 'Int' has no member 'unknown'}} // rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider removing 'var' to make it constant}} {{5-9=}} _ = i + 1 } // SR-5045 - Attempting to return result of reduce(_:_:) in a method with no return produces ambiguous error func sr5045() { let doubles: [Double] = [1, 2, 3] return doubles.reduce(0, +) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // rdar://problem/32934129 - QoI: misleading diagnostic class L_32934129<T : Comparable> { init(_ value: T) { self.value = value } init(_ value: T, _ next: L_32934129<T>?) { self.value = value self.next = next } var value: T var next: L_32934129<T>? = nil func length() -> Int { func inner(_ list: L_32934129<T>?, _ count: Int) { guard let list = list else { return count } // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} return inner(list.next, count + 1) } return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}} } } // rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type class C_31671195 { var name: Int { fatalError() } func name(_: Int) { fatalError() } } C_31671195().name(UInt(0)) // expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}} // rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type class AST_28456467 { var hasStateDef: Bool { return false } } protocol Expr_28456467 {} class ListExpr_28456467 : AST_28456467, Expr_28456467 { let elems: [Expr_28456467] init(_ elems:[Expr_28456467] ) { self.elems = elems } override var hasStateDef: Bool { return elems.first(where: { $0.hasStateDef }) != nil // expected-error@-1 {{value of type 'Expr_28456467' has no member 'hasStateDef'}} } } func sr5081() { var a = ["1", "2", "3", "4", "5"] var b = [String]() b = a[2...4] // expected-error {{cannot assign value of type 'ArraySlice<String>' to type '[String]'}} } // TODO(diagnostics):Figure out what to do when expressions are complex and completely broken func rdar17170728() { var i: Int? = 1 var j: Int? var k: Int? = 2 let _ = [i, j, k].reduce(0 as Int?) { $0 && $1 ? $0! + $1! : ($0 ? $0! : ($1 ? $1! : nil)) // expected-error@-1 4 {{optional type 'Int?' cannot be used as a boolean; test for '!= nil' instead}} } let _ = [i, j, k].reduce(0 as Int?) { // expected-error@-1{{missing argument label 'into:' in call}} // expected-error@-2{{cannot convert value of type 'Int?' to expected argument type}} $0 && $1 ? $0 + $1 : ($0 ? $0 : ($1 ? $1 : nil)) // expected-error@-1 {{binary operator '+' cannot be applied to two 'Bool' operands}} } } // https://bugs.swift.org/browse/SR-5934 - failure to emit diagnostic for bad // generic constraints func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {} // expected-note {{where 'U' = 'T'}} func platypus<T>(a: [T]) { _ = elephant(a) // expected-error {{global function 'elephant' requires that 'T' conform to 'Hashable'}} } // Another case of the above. func badTypes() { let sequence:AnySequence<[Int]> = AnySequence() { AnyIterator() { [3] }} // Notes, attached to declarations, explain that there is a difference between Array.init(_:) and // RangeReplaceableCollection.init(_:) which are both applicable in this case. let array = [Int](sequence) // expected-error@-1 {{no exact matches in call to initializer}} } // rdar://34357545 func unresolvedTypeExistential() -> Bool { return (Int.self==_{}) // expected-error@-1 {{'_' can only appear in a pattern or on the left side of an assignment}} } do { struct Array {} let foo: Swift.Array = Array() // expected-error {{cannot convert value of type 'Array' to specified type 'Array<Element>'}} // expected-error@-1 {{generic parameter 'Element' could not be inferred}} struct Error {} let bar: Swift.Error = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz: (Swift.Error) = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz2: Swift.Error = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz3: (Swift.Error) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz4: ((Swift.Error)) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} } // SyntaxSugarTypes with unresolved types func takesGenericArray<T>(_ x: [T]) {} takesGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}} func takesNestedGenericArray<T>(_ x: [[T]]) {} takesNestedGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[[Int]]'}} func takesSetOfGenericArrays<T>(_ x: Set<[T]>) {} takesSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<[Int]>'}} func takesArrayOfSetOfGenericArrays<T>(_ x: [Set<[T]>]) {} takesArrayOfSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Set<[Int]>]'}} func takesArrayOfGenericOptionals<T>(_ x: [T?]) {} takesArrayOfGenericOptionals(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int?]'}} func takesGenericDictionary<T, U>(_ x: [T : U]) {} // expected-note {{in call to function 'takesGenericDictionary'}} takesGenericDictionary(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : U]'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} // expected-error@-2 {{generic parameter 'U' could not be inferred}} typealias Z = Int func takesGenericDictionaryWithTypealias<T>(_ x: [T : Z]) {} // expected-note {{in call to function 'takesGenericDictionaryWithTypealias'}} takesGenericDictionaryWithTypealias(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : Z]'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} func takesGenericFunction<T>(_ x: ([T]) -> Void) {} // expected-note {{in call to function 'takesGenericFunction'}} takesGenericFunction(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T]) -> Void'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} func takesTuple<T>(_ x: ([T], [T])) {} // expected-note {{in call to function 'takesTuple'}} takesTuple(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T], [T])'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} // Void function returns non-void result fix-it func voidFunc() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{16-16= -> <#Return Type#>}} } func voidFuncWithArgs(arg1: Int) { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{33-33= -> <#Return Type#>}} } func voidFuncWithCondFlow() { if Bool.random() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{28-28= -> <#Return Type#>}} } else { return 2 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{28-28= -> <#Return Type#>}} } } func voidFuncWithNestedVoidFunc() { func nestedVoidFunc() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{24-24= -> <#Return Type#>}} } } // Special cases: These should not offer a note + fix-it func voidFuncExplicitType() -> Void { return 1 // expected-error {{unexpected non-void return value in void function}} } class ClassWithDeinit { deinit { return 0 // expected-error {{unexpected non-void return value in void function}} } } class ClassWithVoidProp { var propertyWithVoidType: () { return 5 } // expected-error {{unexpected non-void return value in void function}} } class ClassWithPropContainingSetter { var propWithSetter: Int { get { return 0 } set { return 1 } // expected-error {{unexpected non-void return value in void function}} } } // https://bugs.swift.org/browse/SR-11964 struct Rect { let width: Int let height: Int } struct Frame { func rect(width: Int, height: Int) -> Rect { Rect(width: width, height: height) } let rect: Rect } func foo(frame: Frame) { frame.rect.width + 10.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} } // Make sure we prefer the conformance failure. func f11(_ n: Int) {} func f11<T : P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}} f11(3, f4) // expected-error {{global function 'f11' requires that 'Int' conform to 'P2'}} let f12: (Int) -> Void = { _ in } // expected-note {{candidate '(Int) -> Void' requires 1 argument, but 2 were provided}} func f12<T : P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{candidate requires that 'Int' conform to 'P2' (requirement specified as 'T' == 'P2')}} f12(3, f4)// expected-error {{no exact matches in call to global function 'f12'}} // SR-12242 struct SR_12242_R<Value> {} struct SR_12242_T {} protocol SR_12242_P {} func fSR_12242() -> SR_12242_R<[SR_12242_T]> {} func genericFunc<SR_12242_T: SR_12242_P>(_ completion: @escaping (SR_12242_R<[SR_12242_T]>) -> Void) { let t = fSR_12242() completion(t) // expected-error {{cannot convert value of type 'diagnostics.SR_12242_R<[diagnostics.SR_12242_T]>' to expected argument type 'diagnostics.SR_12242_R<[SR_12242_T]>'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('diagnostics.SR_12242_T' and 'SR_12242_T') are expected to be equal}} } func assignGenericMismatch() { var a: [Int]? var b: [String] a = b // expected-error {{cannot assign value of type '[String]' to type '[Int]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} b = a // expected-error {{cannot assign value of type '[Int]' to type '[String]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // expected-error@-2 {{value of optional type '[Int]?' must be unwrapped to a value of type '[Int]'}} // expected-note@-3 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-4 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } // [Int] to [String]? argument to param conversion let value: [Int] = [] func gericArgToParamOptional(_ param: [String]?) {} gericArgToParamOptional(value) // expected-error {{convert value of type '[Int]' to expected argument type '[String]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // Inout Expr conversions func gericArgToParamInout1(_ x: inout [[Int]]) {} func gericArgToParamInout2(_ x: inout [[String]]) { gericArgToParamInout1(&x) // expected-error {{cannot convert value of type '[[String]]' to expected argument type '[[Int]]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} } func gericArgToParamInoutOptional(_ x: inout [[String]]?) { gericArgToParamInout1(&x) // expected-error {{cannot convert value of type '[[String]]?' to expected argument type '[[Int]]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} // expected-error@-2 {{value of optional type '[[String]]?' must be unwrapped to a value of type '[[String]]'}} // expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } func gericArgToParamInout(_ x: inout [[Int]]) { // expected-note {{change variable type to '[[String]]?' if it doesn't need to be declared as '[[Int]]'}} gericArgToParamInoutOptional(&x) // expected-error {{cannot convert value of type '[[Int]]' to expected argument type '[[String]]?'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // expected-error@-2 {{inout argument could be set to a value with a type other than '[[Int]]'; use a value declared as type '[[String]]?' instead}} } // SR-12725 struct SR12725<E> {} // expected-note {{arguments to generic parameter 'E' ('Int' and 'Double') are expected to be equal}} func generic<T>(_ value: inout T, _ closure: (SR12725<T>) -> Void) {} let arg: Int generic(&arg) { (g: SR12725<Double>) -> Void in } // expected-error {{cannot convert value of type '(SR12725<Double>) -> Void' to expected argument type '(SR12725<Int>) -> Void'}} // rdar://problem/62428353 - bad error message for passing `T` where `inout T` was expected func rdar62428353<T>(_ t: inout T) { let v = t // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} rdar62428353(v) // expected-error {{cannot pass immutable value as inout argument: 'v' is a 'let' constant}} } func rdar62989214() { struct Flag { var isTrue: Bool } @propertyWrapper @dynamicMemberLookup struct Wrapper<Value> { var wrappedValue: Value subscript<Subject>( dynamicMember keyPath: WritableKeyPath<Value, Subject> ) -> Wrapper<Subject> { get { fatalError() } } } func test(arr: Wrapper<[Flag]>, flag: Flag) { arr[flag].isTrue // expected-error {{cannot convert value of type 'Flag' to expected argument type 'Int'}} } } // SR-5688 func SR5688_1() -> String? { "" } SR5688_1!.count // expected-error {{function 'SR5688_1' was used as a property; add () to call it}} {{9-9=()}} func SR5688_2() -> Int? { 0 } let _: Int = SR5688_2! // expected-error {{function 'SR5688_2' was used as a property; add () to call it}} {{22-22=()}}
6c3779d9551cc4a87e019c10508d31eb
45.500369
228
0.671867
false
false
false
false
tsigo/BombcastNavigator
refs/heads/master
BombcastData/JSONHelper.swift
mit
1
// // JSONHelper.swift // // Version 1.4.0 // // Created by Baris Sencan on 28/08/2014. // Copyright 2014 Baris Sencan // // Distributed under the permissive zlib license // Get the latest version from here: // // https://github.com/isair/JSONHelper // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // import Foundation // Internally used functions, but defined as public as they might serve some // purpose outside this library. public func JSONString(object: AnyObject?) -> String? { return object as? String } public func JSONStrings(object: AnyObject?) -> [String]? { return object as? [String] } public func JSONInt(object: AnyObject?) -> Int? { return object as? Int } public func JSONInts(object: AnyObject?) -> [Int]? { return object as? [Int] } public func JSONBool(object: AnyObject?) -> Bool? { return object as? Bool } public func JSONBools(object: AnyObject?) -> [Bool]? { return object as? [Bool] } public func JSONArray(object: AnyObject?) -> [AnyObject]? { return object as? [AnyObject] } public func JSONObject(object: AnyObject?) -> [String: AnyObject]? { return object as? [String: AnyObject] } public func JSONObjects(object: AnyObject?) -> [[String: AnyObject]]? { return object as? [[String: AnyObject]] } // Operator for use in "if let" conversions. infix operator >>> { associativity left precedence 150 } public func >>><A, B>(a: A?, f: A -> B?) -> B? { if let x = a { return f(x) } else { return nil } } // MARK: - Operator for quick primitive type deserialization. infix operator <<< { associativity right precedence 150 } // For optionals. public func <<<<T>(inout property: T?, value: AnyObject?) -> T? { var newValue: T? if let unwrappedValue: AnyObject = value { if let convertedValue = unwrappedValue as? T { // Direct conversion. newValue = convertedValue } else if property is Int? && unwrappedValue is String { // String -> Int if let intValue = "\(unwrappedValue)".toInt() { newValue = intValue as T } } else if property is NSURL? { // String -> NSURL if let stringValue = unwrappedValue as? String { newValue = NSURL(string: stringValue) as T? } } else if property is NSDate? { // Int || Double || NSNumber -> NSDate if let timestamp = value as? Int { newValue = NSDate(timeIntervalSince1970: Double(timestamp)) as T } else if let timestamp = value as? Double { newValue = NSDate(timeIntervalSince1970: timestamp) as T } else if let timestamp = value as? NSNumber { newValue = NSDate(timeIntervalSince1970: timestamp.doubleValue) as T } } } property = newValue return property } // For non-optionals. public func <<<<T>(inout property: T, value: AnyObject?) -> T { var newValue: T? newValue <<< value if let newValue = newValue { property = newValue } return property } // Special handling for value and format pair to NSDate conversion. public func <<<(inout property: NSDate?, valueAndFormat: (value: AnyObject?, format: AnyObject?)) -> NSDate? { var newValue: NSDate? if let dateString = valueAndFormat.value >>> JSONString { if let formatString = valueAndFormat.format >>> JSONString { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = formatString if let newDate = dateFormatter.dateFromString(dateString) { newValue = newDate } } } property = newValue return property } public func <<<(inout property: NSDate, valueAndFormat: (value: AnyObject?, format: AnyObject?)) -> NSDate { var date: NSDate? date <<< valueAndFormat if let date = date { property = date } return property } // MARK: - Operator for quick primitive array deserialization. infix operator <<<* { associativity right precedence 150 } public func <<<*(inout array: [String]?, value: AnyObject?) -> [String]? { if let stringArray = value >>> JSONStrings { array = stringArray } else { array = nil } return array } public func <<<*(inout array: [String], value: AnyObject?) -> [String] { var newValue: [String]? newValue <<<* value if let newValue = newValue { array = newValue } return array } public func <<<*(inout array: [Int]?, value: AnyObject?) -> [Int]? { if let intArray = value >>> JSONInts { array = intArray } else { array = nil } return array } public func <<<*(inout array: [Int], value: AnyObject?) -> [Int] { var newValue: [Int]? newValue <<<* value if let newValue = newValue { array = newValue } return array } public func <<<*(inout array: [Float]?, value: AnyObject?) -> [Float]? { if let floatArray = value as? [Float] { array = floatArray } else { array = nil } return array } public func <<<*(inout array: [Float], value: AnyObject?) -> [Float] { var newValue: [Float]? newValue <<<* value if let newValue = newValue { array = newValue } return array } public func <<<*(inout array: [Double]?, value: AnyObject?) -> [Double]? { if let doubleArrayDoubleExcitement = value as? [Double] { array = doubleArrayDoubleExcitement } else { array = nil } return array } public func <<<*(inout array: [Double], value: AnyObject?) -> [Double] { var newValue: [Double]? newValue <<<* value if let newValue = newValue { array = newValue } return array } public func <<<*(inout array: [Bool]?, value: AnyObject?) -> [Bool]? { if let boolArray = value >>> JSONBools { array = boolArray } else { array = nil } return array } public func <<<*(inout array: [Bool], value: AnyObject?) -> [Bool] { var newValue: [Bool]? newValue <<<* value if let newValue = newValue { array = newValue } return array } public func <<<*(inout array: [NSURL]?, value: AnyObject?) -> [NSURL]? { if let stringURLArray = value >>> JSONStrings { array = [NSURL]() for stringURL in stringURLArray { if let url = NSURL(string: stringURL) { array!.append(url) } } } else { array = nil } return array } public func <<<*(inout array: [NSURL], value: AnyObject?) -> [NSURL] { var newValue: [NSURL]? newValue <<<* value if let newValue = newValue { array = newValue } return array } public func <<<*(inout array: [NSDate]?, valueAndFormat: (value: AnyObject?, format: AnyObject?)) -> [NSDate]? { var newValue: [NSDate]? if let dateStringArray = valueAndFormat.value >>> JSONStrings { if let formatString = valueAndFormat.format >>> JSONString { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = formatString newValue = [NSDate]() for dateString in dateStringArray { if let date = dateFormatter.dateFromString(dateString) { newValue!.append(date) } } } } array = newValue return array } public func <<<*(inout array: [NSDate], valueAndFormat: (value: AnyObject?, format: AnyObject?)) -> [NSDate] { var newValue: [NSDate]? newValue <<<* valueAndFormat if let newValue = newValue { array = newValue } return array } public func <<<*(inout array: [NSDate]?, value: AnyObject?) -> [NSDate]? { if let timestamps = value as? [AnyObject] { array = [NSDate]() for timestamp in timestamps { var date: NSDate? date <<< timestamp if date != nil { array!.append(date!) } } } else { array = nil } return array } public func <<<*(inout array: [NSDate], value: AnyObject?) -> [NSDate] { var newValue: [NSDate]? newValue <<<* value if let newValue = newValue { array = newValue } return array } // MARK: - Operator for quick class deserialization. infix operator <<<< { associativity right precedence 150 } public protocol Deserializable { init(data: [String: AnyObject]) } public func <<<<<T: Deserializable>(inout instance: T?, dataObject: AnyObject?) -> T? { if let data = dataObject >>> JSONObject { instance = T(data: data) } else { instance = nil } return instance } public func <<<<<T: Deserializable>(inout instance: T, dataObject: AnyObject?) -> T { var newInstance: T? newInstance <<<< dataObject if let newInstance = newInstance { instance = newInstance } return instance } // MARK: - Operator for quick deserialization into an array of instances of a deserializable class. infix operator <<<<* { associativity right precedence 150 } public func <<<<*<T: Deserializable>(inout array: [T]?, dataObject: AnyObject?) -> [T]? { if let dataArray = dataObject >>> JSONObjects { array = [T]() for data in dataArray { array!.append(T(data: data)) } } else { array = nil } return array } public func <<<<*<T: Deserializable>(inout array: [T], dataObject: AnyObject?) -> [T] { var newArray: [T]? newArray <<<<* dataObject if let newArray = newArray { array = newArray } return array } // MARK: - Overloading of own operators for deserialization of JSON strings. private func dataStringToObject(dataString: String) -> AnyObject? { var data: NSData = dataString.dataUsingEncoding(NSUTF8StringEncoding)! var error: NSError? return NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &error) } public func <<<<<T: Deserializable>(inout instance: T?, dataString: String) -> T? { return instance <<<< dataStringToObject(dataString) } public func <<<<<T: Deserializable>(inout instance: T, dataString: String) -> T { return instance <<<< dataStringToObject(dataString) } public func <<<<*<T: Deserializable>(inout array: [T]?, dataString: String) -> [T]? { return array <<<<* dataStringToObject(dataString) } public func <<<<*<T: Deserializable>(inout array: [T], dataString: String) -> [T] { return array <<<<* dataStringToObject(dataString) }
7f315a22f0592a3aa1c9ea8d30762e7d
27.447837
112
0.624687
false
false
false
false
conmeno/20480
refs/heads/master
swift-2048/Models/GameModel.swift
mit
1
// // GameModel.swift // swift-2048 // // Created by Austin Zheng on 6/3/14. // Copyright (c) 2014 Austin Zheng. All rights reserved. // import UIKit /// A protocol that establishes a way for the game model to communicate with its parent view controller. protocol GameModelProtocol : class { func scoreChanged(score: Int) func moveOneTile(from: (Int, Int), to: (Int, Int), value: Int) func moveTwoTiles(from: ((Int, Int), (Int, Int)), to: (Int, Int), value: Int) func insertTile(location: (Int, Int), value: Int) } /// A class representing the game state and game logic for swift-2048. It is owned by a NumberTileGame view controller. class GameModel: NSObject { let dimension: Int let threshold: Int var score: Int = 0 { didSet { delegate.scoreChanged(score) } } var gameboard: SquareGameboard<TileObject> // This really should be unowned/weak. But there is currently a bug that causes the app to crash whenever the delegate // is accessed unless the delegate type is a specific class (rather than a protocol). let delegate: GameModelProtocol var queue: [MoveCommand] var timer: NSTimer let maxCommands = 100 let queueDelay = 0.3 init(dimension d: Int, threshold t: Int, delegate: GameModelProtocol) { dimension = d threshold = t self.delegate = delegate queue = [MoveCommand]() timer = NSTimer() gameboard = SquareGameboard(dimension: d, initialValue: .Empty) super.init() } /// Reset the game state. func reset() { score = 0 gameboard.setAll(.Empty) queue.removeAll(keepCapacity: true) timer.invalidate() } /// Order the game model to perform a move (because the user swiped their finger). The queue enforces a delay of a few /// milliseconds between each move. func queueMove(direction: MoveDirection, completion: (Bool) -> ()) { if queue.count > maxCommands { // Queue is wedged. This should actually never happen in practice. return } let command = MoveCommand(d: direction, c: completion) queue.append(command) if (!timer.valid) { // Timer isn't running, so fire the event immediately timerFired(timer) } } //------------------------------------------------------------------------------------------------------------------// /// Inform the game model that the move delay timer fired. Once the timer fires, the game model tries to execute a /// single move that changes the game state. func timerFired(timer: NSTimer) { if queue.count == 0 { return } // Go through the queue until a valid command is run or the queue is empty var changed = false while queue.count > 0 { let command = queue[0] queue.removeAtIndex(0) changed = performMove(command.direction) command.completion(changed) if changed { // If the command doesn't change anything, we immediately run the next one break } } if changed { self.timer = NSTimer.scheduledTimerWithTimeInterval(queueDelay, target: self, selector: Selector("timerFired:"), userInfo: nil, repeats: false) } } //------------------------------------------------------------------------------------------------------------------// /// Insert a tile with a given value at a position upon the gameboard. func insertTile(pos: (Int, Int), value: Int) { let (x, y) = pos switch gameboard[x, y] { case .Empty: gameboard[x, y] = TileObject.Tile(value) delegate.insertTile(pos, value: value) case .Tile: break } } /// Insert a tile with a given value at a random open position upon the gameboard. func insertTileAtRandomLocation(value: Int) { let openSpots = gameboardEmptySpots() if openSpots.count == 0 { // No more open spots; don't even bother return } // Randomly select an open spot, and put a new tile there let idx = Int(arc4random_uniform(UInt32(openSpots.count-1))) let (x, y) = openSpots[idx] insertTile((x, y), value: value) } /// Return a list of tuples describing the coordinates of empty spots remaining on the gameboard. func gameboardEmptySpots() -> [(Int, Int)] { var buffer = Array<(Int, Int)>() for i in 0..<dimension { for j in 0..<dimension { switch gameboard[i, j] { case .Empty: buffer += [(i, j)] case .Tile: break } } } return buffer } func gameboardFull() -> Bool { return gameboardEmptySpots().count == 0 } //------------------------------------------------------------------------------------------------------------------// func tileBelowHasSameValue(loc: (Int, Int), _ value: Int) -> Bool { let (x, y) = loc if y == dimension-1 { return false } switch gameboard[x, y+1] { case let .Tile(v): return v == value default: return false } } func tileToRightHasSameValue(loc: (Int, Int), _ value: Int) -> Bool { let (x, y) = loc if x == dimension-1 { return false } switch gameboard[x+1, y] { case let .Tile(v): return v == value default: return false } } func userHasLost() -> Bool { if !gameboardFull() { // Player can't lose before filling up the board return false } // Run through all the tiles and check for possible moves for i in 0..<dimension { for j in 0..<dimension { switch gameboard[i, j] { case .Empty: assert(false, "Gameboard reported itself as full, but we still found an empty tile. This is a logic error.") case let .Tile(v): if self.tileBelowHasSameValue((i, j), v) || self.tileToRightHasSameValue((i, j), v) { return false } } } } return true } func userHasWon() -> (Bool, (Int, Int)?) { for i in 0..<dimension { for j in 0..<dimension { // Look for a tile with the winning score or greater switch gameboard[i, j] { case let .Tile(v) where v >= threshold: return (true, (i, j)) default: continue } } } return (false, nil) } //------------------------------------------------------------------------------------------------------------------// // Perform all calculations and update state for a single move. func performMove(direction: MoveDirection) -> Bool { // Prepare the generator closure. This closure differs in behavior depending on the direction of the move. It is // used by the method to generate a list of tiles which should be modified. Depending on the direction this list // may represent a single row or a single column, in either direction. let coordinateGenerator: (Int) -> [(Int, Int)] = { (iteration: Int) -> [(Int, Int)] in var buffer = Array<(Int, Int)>(count:self.dimension, repeatedValue: (0, 0)) for i in 0..<self.dimension { switch direction { case .Up: buffer[i] = (i, iteration) case .Down: buffer[i] = (self.dimension - i - 1, iteration) case .Left: buffer[i] = (iteration, i) case .Right: buffer[i] = (iteration, self.dimension - i - 1) } } return buffer } var atLeastOneMove = false for i in 0..<dimension { // Get the list of coords let coords = coordinateGenerator(i) // Get the corresponding list of tiles let tiles = coords.map() { (c: (Int, Int)) -> TileObject in let (x, y) = c return self.gameboard[x, y] } // Perform the operation let orders = merge(tiles) atLeastOneMove = orders.count > 0 ? true : atLeastOneMove // Write back the results for object in orders { switch object { case let MoveOrder.SingleMoveOrder(s, d, v, wasMerge): // Perform a single-tile move let (sx, sy) = coords[s] let (dx, dy) = coords[d] if wasMerge { score += v } gameboard[sx, sy] = TileObject.Empty gameboard[dx, dy] = TileObject.Tile(v) delegate.moveOneTile(coords[s], to: coords[d], value: v) case let MoveOrder.DoubleMoveOrder(s1, s2, d, v): // Perform a simultaneous two-tile move let (s1x, s1y) = coords[s1] let (s2x, s2y) = coords[s2] let (dx, dy) = coords[d] score += v gameboard[s1x, s1y] = TileObject.Empty gameboard[s2x, s2y] = TileObject.Empty gameboard[dx, dy] = TileObject.Tile(v) delegate.moveTwoTiles((coords[s1], coords[s2]), to: coords[d], value: v) } } } return atLeastOneMove } //------------------------------------------------------------------------------------------------------------------// /// When computing the effects of a move upon a row of tiles, calculate and return a list of ActionTokens /// corresponding to any moves necessary to remove interstital space. For example, |[2][ ][ ][4]| will become /// |[2][4]|. func condense(group: [TileObject]) -> [ActionToken] { var tokenBuffer = [ActionToken]() for (idx, tile) in group.enumerate() { // Go through all the tiles in 'group'. When we see a tile 'out of place', create a corresponding ActionToken. switch tile { case let .Tile(value) where tokenBuffer.count == idx: tokenBuffer.append(ActionToken.NoAction(source: idx, value: value)) case let .Tile(value): tokenBuffer.append(ActionToken.Move(source: idx, value: value)) default: break } } return tokenBuffer; } class func quiescentTileStillQuiescent(inputPosition: Int, outputLength: Int, originalPosition: Int) -> Bool { // Return whether or not a 'NoAction' token still represents an unmoved tile return (inputPosition == outputLength) && (originalPosition == inputPosition) } /// When computing the effects of a move upon a row of tiles, calculate and return an updated list of ActionTokens /// corresponding to any merges that should take place. This method collapses adjacent tiles of equal value, but each /// tile can take part in at most one collapse per move. For example, |[1][1][1][2][2]| will become |[2][1][4]|. func collapse(group: [ActionToken]) -> [ActionToken] { var tokenBuffer = [ActionToken]() var skipNext = false for (idx, token) in group.enumerate() { if skipNext { // Prior iteration handled a merge. So skip this iteration. skipNext = false continue } switch token { case .SingleCombine: assert(false, "Cannot have single combine token in input") case .DoubleCombine: assert(false, "Cannot have double combine token in input") case let .NoAction(s, v) where (idx < group.count-1 && v == group[idx+1].getValue() && GameModel.quiescentTileStillQuiescent(idx, outputLength: tokenBuffer.count, originalPosition: s)): // This tile hasn't moved yet, but matches the next tile. This is a single merge // The last tile is *not* eligible for a merge let next = group[idx+1] let nv = v + group[idx+1].getValue() skipNext = true tokenBuffer.append(ActionToken.SingleCombine(source: next.getSource(), value: nv)) case let t where (idx < group.count-1 && t.getValue() == group[idx+1].getValue()): // This tile has moved, and matches the next tile. This is a double merge // (The tile may either have moved prevously, or the tile might have moved as a result of a previous merge) // The last tile is *not* eligible for a merge let next = group[idx+1] let nv = t.getValue() + group[idx+1].getValue() skipNext = true tokenBuffer.append(ActionToken.DoubleCombine(source: t.getSource(), second: next.getSource(), value: nv)) case let .NoAction(s, v) where !GameModel.quiescentTileStillQuiescent(idx, outputLength: tokenBuffer.count, originalPosition: s): // A tile that didn't move before has moved (first cond.), or there was a previous merge (second cond.) tokenBuffer.append(ActionToken.Move(source: s, value: v)) case let .NoAction(s, v): // A tile that didn't move before still hasn't moved tokenBuffer.append(ActionToken.NoAction(source: s, value: v)) case let .Move(s, v): // Propagate a move tokenBuffer.append(ActionToken.Move(source: s, value: v)) default: // Don't do anything break } } return tokenBuffer } /// When computing the effects of a move upon a row of tiles, take a list of ActionTokens prepared by the condense() /// and convert() methods and convert them into MoveOrders that can be fed back to the delegate. func convert(group: [ActionToken]) -> [MoveOrder] { var moveBuffer = [MoveOrder]() for (idx, t) in group.enumerate() { switch t { case let .Move(s, v): moveBuffer.append(MoveOrder.SingleMoveOrder(source: s, destination: idx, value: v, wasMerge: false)) case let .SingleCombine(s, v): moveBuffer.append(MoveOrder.SingleMoveOrder(source: s, destination: idx, value: v, wasMerge: true)) case let .DoubleCombine(s1, s2, v): moveBuffer.append(MoveOrder.DoubleMoveOrder(firstSource: s1, secondSource: s2, destination: idx, value: v)) default: // Don't do anything break } } return moveBuffer } /// Given an array of TileObjects, perform a collapse and create an array of move orders. func merge(group: [TileObject]) -> [MoveOrder] { // Calculation takes place in three steps: // 1. Calculate the moves necessary to produce the same tiles, but without any interstital space. // 2. Take the above, and calculate the moves necessary to collapse adjacent tiles of equal value. // 3. Take the above, and convert into MoveOrders that provide all necessary information to the delegate. return convert(collapse(condense(group))) } }
dfed97a994c8b95df0d897ed3afc4df7
35.35567
135
0.603786
false
false
false
false
cosmycx/TapLinksLabel
refs/heads/master
Example/TapLinksLabel/TapLinksLabel.swift
mit
2
// // LinksLabel.swift // 91-vcLinks // // Created by Cosmin Potocean on 11/13/16. // Copyright © 2016 Cosmin Potocean. All rights reserved. // import UIKit protocol TapLinksLabelDelegate: class { // when a link is tapped in the LinksLabel func linkWasTapped(url:URL) } class TapLinksLabel: UILabel { weak var delegate :TapLinksLabelDelegate? @IBInspectable var linksColor :UIColor = UIColor.blue { didSet { self.commonInit() } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.commonInit() } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } func commonInit(){ if self.text != nil { self.attributedText = textToAttributtedTextWithLinks(newTextContent: self.text!) } self.isUserInteractionEnabled = true // adding tap to label let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap)) // ############ self.addGestureRecognizer(tap) } // converts text to attributed text with colored links and metadata func textToAttributtedTextWithLinks(newTextContent :String)->NSAttributedString { let attributedTextWithLinks = NSMutableAttributedString(string: newTextContent) // looking for url's let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) let matches = detector.matches(in: newTextContent, options: [], range: NSRange(location: 0, length: newTextContent.utf16.count)) // same font size needed for layoutmanager and range in handle tap func attributedTextWithLinks.addAttribute(NSFontAttributeName, value: self.font, range: NSRange(location: 0,length: newTextContent.utf16.count)) for link in matches { if let url = link.url { attributedTextWithLinks.addAttribute(NSForegroundColorAttributeName, value: linksColor, range: link.range) // adding url value as metadata on the link range attributedTextWithLinks.addAttribute("URL", value: url, range: link.range) } } return attributedTextWithLinks } // handles the tap on a link in the attributed text of the label func handleTap(sender: UITapGestureRecognizer) { if sender.state == .ended { // current size of label let thisLabelSize = self.bounds.size // text container let textContainer = NSTextContainer(size: thisLabelSize) textContainer.lineFragmentPadding = 0.0 textContainer.lineBreakMode = self.lineBreakMode textContainer.maximumNumberOfLines = self.numberOfLines // layout manager let layoutManager = NSLayoutManager() layoutManager.addTextContainer(textContainer) // text storage let textStorage = NSTextStorage(attributedString: self.attributedText!) textStorage.addLayoutManager(layoutManager) // calculate location of touch on text let touchLocation = sender.location(in: self) let textBoundingRect = layoutManager.usedRect(for: textContainer) let textContainerOffset = CGPoint(x: (thisLabelSize.width - textBoundingRect.size.width) * 0.5 - textBoundingRect.origin.x, y: (thisLabelSize.height - textBoundingRect.size.height) * 0.5 - textBoundingRect.origin.y) let touchLocationInTextContainer = CGPoint(x: touchLocation.x - textContainerOffset.x, y: touchLocation.y - textContainerOffset.y) // find charater index at the touch location let characterIndex = layoutManager.characterIndex(for: touchLocationInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) if let tappedUrl = self.attributedText?.attributes(at: characterIndex, effectiveRange: nil)["URL"] as? URL { // a link was tapped delegate?.linkWasTapped(url: tappedUrl) } } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
bc0657ecb1312a5ad385982be899b6d2
39.468468
162
0.64114
false
false
false
false
airbnb/lottie-ios
refs/heads/master
Sources/Private/Model/ShapeItems/GradientFill.swift
apache-2.0
3
// // GradientFill.swift // lottie-swift // // Created by Brandon Withrow on 1/8/19. // import Foundation // MARK: - GradientType enum GradientType: Int, Codable { case none case linear case radial } // MARK: - GradientFill final class GradientFill: ShapeItem { // MARK: Lifecycle required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: GradientFill.CodingKeys.self) opacity = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .opacity) startPoint = try container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .startPoint) endPoint = try container.decode(KeyframeGroup<LottieVector3D>.self, forKey: .endPoint) gradientType = try container.decode(GradientType.self, forKey: .gradientType) highlightLength = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .highlightLength) highlightAngle = try container.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .highlightAngle) fillRule = try container.decodeIfPresent(FillRule.self, forKey: .fillRule) ?? .nonZeroWinding let colorsContainer = try container.nestedContainer(keyedBy: GradientDataKeys.self, forKey: .colors) colors = try colorsContainer.decode(KeyframeGroup<[Double]>.self, forKey: .colors) numberOfColors = try colorsContainer.decode(Int.self, forKey: .numberOfColors) try super.init(from: decoder) } required init(dictionary: [String: Any]) throws { let opacityDictionary: [String: Any] = try dictionary.value(for: CodingKeys.opacity) opacity = try KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary) let startPointDictionary: [String: Any] = try dictionary.value(for: CodingKeys.startPoint) startPoint = try KeyframeGroup<LottieVector3D>(dictionary: startPointDictionary) let endPointDictionary: [String: Any] = try dictionary.value(for: CodingKeys.endPoint) endPoint = try KeyframeGroup<LottieVector3D>(dictionary: endPointDictionary) let gradientRawType: Int = try dictionary.value(for: CodingKeys.gradientType) guard let gradient = GradientType(rawValue: gradientRawType) else { throw InitializableError.invalidInput } gradientType = gradient if let highlightLengthDictionary = dictionary[CodingKeys.highlightLength.rawValue] as? [String: Any] { highlightLength = try? KeyframeGroup<LottieVector1D>(dictionary: highlightLengthDictionary) } else { highlightLength = nil } if let highlightAngleDictionary = dictionary[CodingKeys.highlightAngle.rawValue] as? [String: Any] { highlightAngle = try? KeyframeGroup<LottieVector1D>(dictionary: highlightAngleDictionary) } else { highlightAngle = nil } let colorsDictionary: [String: Any] = try dictionary.value(for: CodingKeys.colors) let nestedColorsDictionary: [String: Any] = try colorsDictionary.value(for: GradientDataKeys.colors) colors = try KeyframeGroup<[Double]>(dictionary: nestedColorsDictionary) numberOfColors = try colorsDictionary.value(for: GradientDataKeys.numberOfColors) if let fillRuleRawValue = dictionary[CodingKeys.fillRule.rawValue] as? Int, let fillRule = FillRule(rawValue: fillRuleRawValue) { self.fillRule = fillRule } else { fillRule = .nonZeroWinding } try super.init(dictionary: dictionary) } // MARK: Internal /// The opacity of the fill let opacity: KeyframeGroup<LottieVector1D> /// The start of the gradient let startPoint: KeyframeGroup<LottieVector3D> /// The end of the gradient let endPoint: KeyframeGroup<LottieVector3D> /// The type of gradient let gradientType: GradientType /// Gradient Highlight Length. Only if type is Radial let highlightLength: KeyframeGroup<LottieVector1D>? /// Highlight Angle. Only if type is Radial let highlightAngle: KeyframeGroup<LottieVector1D>? /// The number of color points in the gradient let numberOfColors: Int /// The Colors of the gradient. let colors: KeyframeGroup<[Double]> /// The fill rule to use when filling a path let fillRule: FillRule override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(opacity, forKey: .opacity) try container.encode(startPoint, forKey: .startPoint) try container.encode(endPoint, forKey: .endPoint) try container.encode(gradientType, forKey: .gradientType) try container.encodeIfPresent(highlightLength, forKey: .highlightLength) try container.encodeIfPresent(highlightAngle, forKey: .highlightAngle) try container.encodeIfPresent(fillRule, forKey: .fillRule) var colorsContainer = container.nestedContainer(keyedBy: GradientDataKeys.self, forKey: .colors) try colorsContainer.encode(numberOfColors, forKey: .numberOfColors) try colorsContainer.encode(colors, forKey: .colors) } // MARK: Private private enum CodingKeys: String, CodingKey { case opacity = "o" case startPoint = "s" case endPoint = "e" case gradientType = "t" case highlightLength = "h" case highlightAngle = "a" case colors = "g" case fillRule = "r" } private enum GradientDataKeys: String, CodingKey { case numberOfColors = "p" case colors = "k" } }
e10bfae8aa90d133311ed0792d0333b3
37.890511
113
0.741742
false
false
false
false
squall09s/VegOresto
refs/heads/master
VegoResto/MainViewController.swift
gpl-3.0
1
// // MainViewController.swift // SkylieRecettes // // Created by Laurent Nicolas (141 - LILLE TOURCOING) on 31/05/2016. // Copyright © 2016 LaurentNicolas. All rights reserved. // import UIKit class MainViewController: LGSideMenuController { static var sharedInstance: MainViewController? var isAlreadySet = false var controllerMenuLateral: MenuLateral = StoryboardScene.Main.menuLateral.instantiate() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { self.setup() } func setup() { if isAlreadySet { return } Debug.log(object: "[ Setup MainViewController ]") MainViewController.sharedInstance = self let navigationController: UITabBarController = StoryboardScene.Main.navigationController.instantiate() self.rootViewController = navigationController navigationController.tabBar.isHidden = true self.setLeftViewEnabledWithWidth(250.0, presentationStyle: .slideAbove, alwaysVisibleOptions: [] ) self.leftViewStatusBarStyle = .default self.leftViewStatusBarVisibleOptions = .onAll self.leftView().addSubview( self.controllerMenuLateral.view ) isAlreadySet = true } override func leftViewWillLayoutSubviews(with size: CGSize) { super.leftViewWillLayoutSubviews(with: size) self.controllerMenuLateral.varIB_tableView.frame = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height) } }
cf4d5962d4d7e81181bf71bafe38fa78
24.185714
121
0.692002
false
false
false
false
mercadopago/sdk-ios
refs/heads/master
MercadoPagoSDK/MercadoPagoSDK/VaultViewController.swift
mit
1
// // VaultViewController.swift // MercadoPagoSDK // // Created by Matias Gualino on 7/1/15. // Copyright (c) 2015 com.mercadopago. All rights reserved. // import Foundation import UIKit public class VaultViewController : UIViewController, UITableViewDataSource, UITableViewDelegate { // ViewController parameters var publicKey: String? var merchantBaseUrl: String? var getCustomerUri: String? var merchantAccessToken: String? var amount : Double = 0 var bundle : NSBundle? = MercadoPago.getBundle() public var callback : ((paymentMethod: PaymentMethod, tokenId: String?, issuerId: NSNumber?, installments: Int) -> Void)? // Input controls @IBOutlet weak private var tableview : UITableView! @IBOutlet weak private var emptyPaymentMethodCell : MPPaymentMethodEmptyTableViewCell! @IBOutlet weak private var paymentMethodCell : MPPaymentMethodTableViewCell! @IBOutlet weak private var installmentsCell : MPInstallmentsTableViewCell! @IBOutlet weak private var securityCodeCell : MPSecurityCodeTableViewCell! public var loadingView : UILoadingView! // Current values public var selectedCard : Card? = nil public var selectedPayerCost : PayerCost? = nil public var selectedCardToken : CardToken? = nil public var selectedPaymentMethod : PaymentMethod? = nil public var selectedIssuer : Issuer? = nil public var cards : [Card]? public var payerCosts : [PayerCost]? public var securityCodeRequired : Bool = true public var securityCodeLength : Int = 0 public var bin : String? public var supportedPaymentTypes : [String]? init(merchantPublicKey: String, merchantBaseUrl: String?, merchantGetCustomerUri: String?, merchantAccessToken: String?, amount: Double, supportedPaymentTypes: [String], callback: (paymentMethod: PaymentMethod, tokenId: String?, issuerId: NSNumber?, installments: Int) -> Void) { super.init(nibName: "VaultViewController", bundle: bundle) self.merchantBaseUrl = merchantBaseUrl self.getCustomerUri = merchantGetCustomerUri self.merchantAccessToken = merchantAccessToken self.publicKey = merchantPublicKey self.amount = amount self.callback = callback self.supportedPaymentTypes = supportedPaymentTypes } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let tableSelection : NSIndexPath? = self.tableview.indexPathForSelectedRow if tableSelection != nil { self.tableview.deselectRowAtIndexPath(tableSelection!, animated: false) } } override public func viewDidLoad() { super.viewDidLoad() self.title = "Pagar".localized self.loadingView = UILoadingView(frame: MercadoPago.screenBoundsFixedToPortraitOrientation(), text: "Cargando...".localized) declareAndInitCells() self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Continuar".localized, style: UIBarButtonItemStyle.Plain, target: self, action: "submitForm") self.navigationItem.rightBarButtonItem?.enabled = false self.tableview.delegate = self self.tableview.dataSource = self if self.merchantBaseUrl != nil && self.getCustomerUri != nil { self.view.addSubview(self.loadingView) MerchantServer.getCustomer(self.merchantBaseUrl!, merchantGetCustomerUri: self.getCustomerUri!, merchantAccessToken: self.merchantAccessToken!, success: { (customer: Customer) -> Void in self.cards = customer.cards self.loadingView.removeFromSuperview() self.tableview.reloadData() }, failure: { (error: NSError?) -> Void in MercadoPago.showAlertViewWithError(error, nav: self.navigationController) }) } else { self.tableview.reloadData() } } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "willShowKeyboard:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "willHideKeyboard:", name: UIKeyboardWillHideNotification, object: nil) } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func willHideKeyboard(notification: NSNotification) { // resize content insets. let contentInsets = UIEdgeInsetsMake(64, 0.0, 0.0, 0) self.tableview.contentInset = contentInsets self.tableview.scrollIndicatorInsets = contentInsets self.scrollToRow(NSIndexPath(forRow: 0, inSection: 0)) } func willShowKeyboard(notification: NSNotification) { let s:NSValue? = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue) let keyboardBounds :CGRect = s!.CGRectValue() // resize content insets. let contentInsets = UIEdgeInsetsMake(64, 0.0, keyboardBounds.size.height, 0) self.tableview.contentInset = contentInsets self.tableview.scrollIndicatorInsets = contentInsets let securityIndexPath = self.tableview.indexPathForCell(self.securityCodeCell) if securityIndexPath != nil { self.scrollToRow(securityIndexPath!) } } public func scrollToRow(indexPath: NSIndexPath) { self.tableview.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true) } public func declareAndInitCells() { let paymentMethodNib = UINib(nibName: "MPPaymentMethodTableViewCell", bundle: self.bundle) self.tableview.registerNib(paymentMethodNib, forCellReuseIdentifier: "paymentMethodCell") self.paymentMethodCell = self.tableview.dequeueReusableCellWithIdentifier("paymentMethodCell") as! MPPaymentMethodTableViewCell let emptyPaymentMethodNib = UINib(nibName: "MPPaymentMethodEmptyTableViewCell", bundle: self.bundle) self.tableview.registerNib(emptyPaymentMethodNib, forCellReuseIdentifier: "emptyPaymentMethodCell") self.emptyPaymentMethodCell = self.tableview.dequeueReusableCellWithIdentifier("emptyPaymentMethodCell") as! MPPaymentMethodEmptyTableViewCell let securityCodeNib = UINib(nibName: "MPSecurityCodeTableViewCell", bundle: self.bundle) self.tableview.registerNib(securityCodeNib, forCellReuseIdentifier: "securityCodeCell") self.securityCodeCell = self.tableview.dequeueReusableCellWithIdentifier("securityCodeCell")as! MPSecurityCodeTableViewCell let installmentsNib = UINib(nibName: "MPInstallmentsTableViewCell", bundle: self.bundle) self.tableview.registerNib(installmentsNib, forCellReuseIdentifier: "installmentsCell") self.installmentsCell = self.tableview.dequeueReusableCellWithIdentifier("installmentsCell") as! MPInstallmentsTableViewCell } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.selectedCard == nil && self.selectedCardToken == nil { if (self.selectedPaymentMethod != nil && !MercadoPago.isCardPaymentType(self.selectedPaymentMethod!.paymentTypeId)) { self.navigationItem.rightBarButtonItem?.enabled = true } return 1 } else if self.selectedPayerCost == nil { return 2 } else if !securityCodeRequired { self.navigationItem.rightBarButtonItem?.enabled = true return 2 } self.navigationItem.rightBarButtonItem?.enabled = true return 3 } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { if self.selectedCard == nil && self.selectedPaymentMethod == nil { self.emptyPaymentMethodCell = self.tableview.dequeueReusableCellWithIdentifier("emptyPaymentMethodCell") as! MPPaymentMethodEmptyTableViewCell return self.emptyPaymentMethodCell } else { self.paymentMethodCell = self.tableview.dequeueReusableCellWithIdentifier("paymentMethodCell") as! MPPaymentMethodTableViewCell if !MercadoPago.isCardPaymentType(self.selectedPaymentMethod!.paymentTypeId) { self.paymentMethodCell.fillWithPaymentMethod(self.selectedPaymentMethod!) } else if self.selectedCardToken != nil { self.paymentMethodCell.fillWithCardTokenAndPaymentMethod(self.selectedCardToken, paymentMethod: self.selectedPaymentMethod!) } else { self.paymentMethodCell.fillWithCard(self.selectedCard) } return self.paymentMethodCell } } else if indexPath.row == 1 { self.installmentsCell = self.tableview.dequeueReusableCellWithIdentifier("installmentsCell") as! MPInstallmentsTableViewCell self.installmentsCell.fillWithPayerCost(self.selectedPayerCost, amount: self.amount) return self.installmentsCell } else if indexPath.row == 2 { self.securityCodeCell = self.tableview.dequeueReusableCellWithIdentifier("securityCodeCell") as! MPSecurityCodeTableViewCell self.securityCodeCell.height = 143 self.securityCodeCell.fillWithPaymentMethod(self.selectedPaymentMethod!) return self.securityCodeCell } return UITableViewCell() } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if (indexPath.row == 2) { return self.securityCodeCell != nil ? self.securityCodeCell.getHeight() : 143 } return 65 } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == 0 { let paymentMethodsViewController = getPaymentMethodsViewController() if self.cards != nil && self.cards!.count > 0 { let customerPaymentMethodsViewController = MercadoPago.startCustomerCardsViewController(self.cards!, callback: {(selectedCard: Card?) -> Void in if selectedCard != nil { self.selectedCard = selectedCard self.selectedPaymentMethod = self.selectedCard?.paymentMethod self.selectedIssuer = self.selectedCard?.issuer self.bin = self.selectedCard?.firstSixDigits self.securityCodeLength = self.selectedCard!.securityCode!.length self.securityCodeRequired = self.securityCodeLength > 0 self.loadPayerCosts() self.navigationController!.popViewControllerAnimated(true) } else { self.showViewController(paymentMethodsViewController) } }) self.showViewController(customerPaymentMethodsViewController) } else { self.showViewController(paymentMethodsViewController) } } else if indexPath.row == 1 { self.showViewController(MercadoPago.startInstallmentsViewController(payerCosts!, amount: amount, callback: { (payerCost: PayerCost?) -> Void in self.selectedPayerCost = payerCost self.tableview.reloadData() self.navigationController!.popToViewController(self, animated: true) })) } } public func showViewController(vc: UIViewController) { if #available(iOS 8.0, *) { self.showViewController(vc, sender: self) } else { self.navigationController?.pushViewController(vc, animated: true) } } public func loadPayerCosts() { self.view.addSubview(self.loadingView) let mercadoPago : MercadoPago = MercadoPago(publicKey: self.publicKey!) mercadoPago.getInstallments(self.bin!, amount: self.amount, issuerId: self.selectedIssuer?._id, paymentTypeId: self.selectedPaymentMethod!.paymentTypeId!, success: {(installments: [Installment]?) -> Void in if installments != nil { self.payerCosts = installments![0].payerCosts self.tableview.reloadData() self.loadingView.removeFromSuperview() } }, failure: { (error: NSError?) -> Void in MercadoPago.showAlertViewWithError(error, nav: self.navigationController) self.navigationController?.popToRootViewControllerAnimated(true) }) } public func submitForm() { self.securityCodeCell.securityCodeTextField.resignFirstResponder() let mercadoPago : MercadoPago = MercadoPago(publicKey: self.publicKey!) var canContinue = true if self.securityCodeRequired { let securityCode = self.securityCodeCell.getSecurityCode() if String.isNullOrEmpty(securityCode) { self.securityCodeCell.setError("invalid_field".localized) canContinue = false } else if securityCode.characters.count != securityCodeLength { self.securityCodeCell.setError(("invalid_cvv_length".localized as NSString).stringByReplacingOccurrencesOfString("%1$s", withString: "\(securityCodeLength)")) canContinue = false } } if !canContinue { self.tableview.reloadData() } else { // Create token if selectedCard != nil { let securityCode = self.securityCodeRequired ? securityCodeCell.securityCodeTextField.text : nil let savedCardToken : SavedCardToken = SavedCardToken(cardId: selectedCard!._id.stringValue, securityCode: securityCode, securityCodeRequired: self.securityCodeRequired) if savedCardToken.validate() { // Send card id to get token id self.view.addSubview(self.loadingView) mercadoPago.createToken(savedCardToken, success: {(token: Token?) -> Void in var tokenId : String? = nil if token != nil { tokenId = token!._id } let installments = self.selectedPayerCost == nil ? 0 : self.selectedPayerCost!.installments self.callback!(paymentMethod: self.selectedPaymentMethod!, tokenId: tokenId, issuerId: self.selectedIssuer?._id, installments: installments) }, failure: { (error: NSError?) -> Void in MercadoPago.showAlertViewWithError(error, nav: self.navigationController) }) } else { print("Invalid data") return } } else { self.selectedCardToken!.securityCode = self.securityCodeCell.securityCodeTextField.text self.view.addSubview(self.loadingView) mercadoPago.createNewCardToken(self.selectedCardToken!, success: {(token: Token?) -> Void in var tokenId : String? = nil if token != nil { tokenId = token!._id } let installments = self.selectedPayerCost == nil ? 0 : self.selectedPayerCost!.installments self.callback!(paymentMethod: self.selectedPaymentMethod!, tokenId: tokenId, issuerId: self.selectedIssuer?._id, installments: installments) }, failure: { (error: NSError?) -> Void in MercadoPago.showAlertViewWithError(error, nav: self.navigationController) }) } } } func getPaymentMethodsViewController() -> PaymentMethodsViewController { return MercadoPago.startPaymentMethodsViewController(self.publicKey!, supportedPaymentTypes: self.supportedPaymentTypes!, callback: { (paymentMethod : PaymentMethod) -> Void in self.selectedPaymentMethod = paymentMethod if MercadoPago.isCardPaymentType(paymentMethod.paymentTypeId) { self.selectedCard = nil if paymentMethod.settings != nil && paymentMethod.settings.count > 0 { self.securityCodeLength = paymentMethod.settings![0].securityCode!.length self.securityCodeRequired = self.securityCodeLength != 0 } let newCardViewController = MercadoPago.startNewCardViewController(MercadoPago.PUBLIC_KEY, key: self.publicKey!, paymentMethod: self.selectedPaymentMethod!, requireSecurityCode: self.securityCodeRequired, callback: { (cardToken: CardToken) -> Void in self.selectedCardToken = cardToken self.bin = self.selectedCardToken?.getBin() self.loadPayerCosts() self.navigationController!.popToViewController(self, animated: true) }) if self.selectedPaymentMethod!.isIssuerRequired() { let issuerViewController = MercadoPago.startIssuersViewController(self.publicKey!, paymentMethod: self.selectedPaymentMethod!, callback: { (issuer: Issuer) -> Void in self.selectedIssuer = issuer self.showViewController(newCardViewController) }) self.showViewController(issuerViewController) } else { self.showViewController(newCardViewController) } } else { self.tableview.reloadData() self.navigationController!.popToViewController(self, animated: true) } }) } }
15b1133ec2fd42eb8fb471d48382c8cf
48.234332
283
0.661501
false
false
false
false
yuwang17/JokeBox
refs/heads/master
JokeBox/MainViewController.swift
apache-2.0
1
// // ViewController.swift // JokeBox // // Created by Wang Yu on 5/24/15. // Copyright (c) 2015 Yu Wang. All rights reserved. // import UIKit import Spring import Social import MessageUI class MainViewController: UIViewController, JokeManagerDelegate, ImageGetterDelegate, MFMailComposeViewControllerDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var backgroundMaskView: UIView! @IBOutlet weak var dialogView: UIView! @IBOutlet weak var shareView: UIView! @IBOutlet weak var headerView: UIView! @IBOutlet weak var jokeLabel: SpringLabel! @IBOutlet weak var maskButton: UIButton! @IBOutlet weak var emailButton: UIButton! @IBOutlet weak var twitterButton: UIButton! @IBOutlet weak var facebookButton: UIButton! @IBOutlet weak var shareLabelsView: UIView! @IBOutlet weak var shareButton: DesignableButton! @IBOutlet weak var favoriteButton: DesignableButton! @IBOutlet weak var jokeLabelActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var shareButtonWidthConstraint: NSLayoutConstraint! var placeHolderImageIndex: Int { get { let random: Int = Int(rand() % 11) return random } } var imageGetter: ImageGetter = ImageGetter() var jokeMgr: JokeManager = JokeManager() var imageUrls = [String]() { didSet { dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { for var index = 0; index < self.imageUrls.count-1; index++ { let imageData = NSData(contentsOfURL: NSURL(string: self.imageUrls[index])!) dispatch_async(dispatch_get_main_queue()) { if imageData != nil { let curImage: UIImage = UIImage(data: imageData!)! self.images.append(curImage) } } } } } } var images = [UIImage]() var jokes = [Joke]() var currentNumber: Int = 0 { didSet { if currentNumber >= 25 { jokeMgr.getManyRandomJoke() imageGetter.getFlickrInterestingnessPhotos() currentNumber = 0 images.removeAll(keepCapacity: true) jokeLabelActivityIndicator.startAnimating() } } } var favoriteButtonIsClicked: Bool = false { didSet { if favoriteButtonIsClicked == true { favoriteButton.setImage(UIImage(named: "leftButton-selected"), forState: UIControlState.Normal) } else { favoriteButton.setImage(UIImage(named: "leftButton"), forState: UIControlState.Normal) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. jokeMgr.delegate = self imageGetter.delegate = self imageGetter.getFlickrInterestingnessPhotos() animator = UIDynamicAnimator(referenceView: view) shareButtonWidthConstraint.constant = self.view.frame.width / 3 dialogView.alpha = 0 imageView.contentMode = UIViewContentMode.ScaleAspectFill jokeLabel.numberOfLines = 0 jokeLabel.text = "" jokeLabel.adjustsFontSizeToFitWidth = true jokeLabelActivityIndicator.hidesWhenStopped = true jokeLabelActivityIndicator.startAnimating() jokeMgr.getManyRandomJoke() facebookButton.addTarget(self, action: "faceBookButtonDidPressed:", forControlEvents: UIControlEvents.TouchUpInside) twitterButton.addTarget(self, action: "twitterButtonDidPressed:", forControlEvents: UIControlEvents.TouchUpInside) emailButton.addTarget(self, action: "emailButtonDidPressed:", forControlEvents: UIControlEvents.TouchUpInside) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(Bool()) insertBlurView(backgroundMaskView, UIBlurEffectStyle.Dark) insertBlurView(headerView, UIBlurEffectStyle.Dark) jokeLabel.text = "" if !jokes.isEmpty { jokeLabel.text = jokes[currentNumber].content } if jokeLabel.text == "" { jokeMgr.getOneRandomJoke() } favoriteButtonIsClicked = false let scale = CGAffineTransformMakeScale(0.5, 0.5) let translate = CGAffineTransformMakeTranslation(0, -200) dialogView.transform = CGAffineTransformConcat(scale, translate) spring(0.5) { let scale = CGAffineTransformMakeScale(1, 1) let translate = CGAffineTransformMakeTranslation(0, 0) self.dialogView.transform = CGAffineTransformConcat(scale, translate) } dialogView.alpha = 1 if !images.isEmpty { var oldImageSize = CGSize() let currentImage = images.removeAtIndex(0) fadeChangeBackgroundImage(currentImage) imageView.image = currentImage } else { setCurrentImageAsRandomImageInPlaceHolder() } favoriteButton.animation = "pop" shareButton.animation = "pop" shareButton.delay = 0.1 favoriteButton.animate() shareButton.animate() } func setCurrentImageAsRandomImageInPlaceHolder() { let currentImage: UIImage? = UIImage(named: "placeHoldImage\(placeHolderImageIndex)") fadeChangeBackgroundImage(currentImage!) imageView.image = currentImage } func gotOneRandomJoke(joke: Joke) { if jokeLabel.text == "" { self.jokeLabel.text = joke.content jokeLabel.animation = "fadeIn" jokeLabel.animate() jokeLabelActivityIndicator.stopAnimating() } } func gotManyRandomJokes(jokes: [Joke]) { self.jokes = jokes jokeLabelActivityIndicator.stopAnimating() } func gotFlickrInterestingnessPhotoUrls(urlList: [String]) { imageUrls = urlList } @IBAction func maskButtonDidPress(sender: AnyObject) { spring(0.5) { self.maskButton.alpha = 0 } hideShareView() } func showMask() { self.maskButton.hidden = false self.maskButton.alpha = 0 spring(0.5) { self.maskButton.alpha = 1 } } @IBAction func favoriteButtonDidPress(sender: UIButton) { favoriteButtonIsClicked = !favoriteButtonIsClicked } @IBAction func shareButtonDidPress(sender: AnyObject) { shareView.hidden = false showMask() shareView.transform = CGAffineTransformMakeTranslation(0, 200) emailButton.transform = CGAffineTransformMakeTranslation(0, 200) twitterButton.transform = CGAffineTransformMakeTranslation(0, 200) facebookButton.transform = CGAffineTransformMakeTranslation(0, 200) shareLabelsView.alpha = 0 spring(0.5) { self.shareView.transform = CGAffineTransformMakeTranslation(0, 0) self.dialogView.transform = CGAffineTransformMakeScale(0.8, 0.8) } springWithDelay(0.5, 0.05, { self.emailButton.transform = CGAffineTransformMakeTranslation(0, 0) }) springWithDelay(0.5, 0.10, { self.twitterButton.transform = CGAffineTransformMakeTranslation(0, 0) }) springWithDelay(0.5, 0.15, { self.facebookButton.transform = CGAffineTransformMakeTranslation(0, 0) }) springWithDelay(0.5, 0.2, { self.shareLabelsView.alpha = 1 }) } func hideShareView() { spring(0.5) { self.shareView.transform = CGAffineTransformMakeTranslation(0, 0) self.dialogView.transform = CGAffineTransformMakeScale(1, 1) self.shareView.hidden = true } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } var animator : UIDynamicAnimator! var attachmentBehavior : UIAttachmentBehavior! var gravityBehaviour : UIGravityBehavior! var snapBehavior : UISnapBehavior! @IBOutlet var panRecognizer: UIPanGestureRecognizer! @IBAction func handleGesture(sender: AnyObject) { let myView = dialogView let location = sender.locationInView(view) let boxLocation = sender.locationInView(dialogView) if sender.state == UIGestureRecognizerState.Began { animator.removeBehavior(snapBehavior) let centerOffset = UIOffsetMake(boxLocation.x - CGRectGetMidX(myView.bounds), boxLocation.y - CGRectGetMidY(myView.bounds)); attachmentBehavior = UIAttachmentBehavior(item: myView, offsetFromCenter: centerOffset, attachedToAnchor: location) attachmentBehavior.frequency = 0 animator.addBehavior(attachmentBehavior) } else if sender.state == UIGestureRecognizerState.Changed { attachmentBehavior.anchorPoint = location } else if sender.state == UIGestureRecognizerState.Ended { animator.removeBehavior(attachmentBehavior) snapBehavior = UISnapBehavior(item: myView, snapToPoint: CGPoint(x: view.center.x, y: view.center.y - 45)) animator.addBehavior(snapBehavior) let translation = sender.translationInView(view) if translation.y > 100 { animator.removeAllBehaviors() var gravity = UIGravityBehavior(items: [dialogView]) gravity.gravityDirection = CGVectorMake(0, 10) animator.addBehavior(gravity) delay(0.3) { self.refreshView() } } } } func refreshView() { currentNumber++ animator.removeAllBehaviors() snapBehavior = UISnapBehavior(item: dialogView, snapToPoint: CGPoint(x: view.center.x, y: view.center.y - 45)) attachmentBehavior.anchorPoint = CGPoint(x: view.center.x, y: view.center.y - 45) dialogView.center = CGPoint(x: view.center.x, y: view.center.y - 45) viewDidAppear(true) } func fadeChangeBackgroundImage(toImage: UIImage) { UIView.transitionWithView(self.backgroundImageView, duration: 1.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { () -> Void in self.backgroundImageView.image = toImage }, completion: nil) } func faceBookButtonDidPressed(sender: UIButton) { if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) { var fbShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook) fbShare.setInitialText("\(jokeLabel.text!)") self.presentViewController(fbShare, animated: true, completion: nil) } else { var alert = UIAlertController(title: "Accounts", message: "Please login to a Facebook account to share.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } func twitterButtonDidPressed(sender: UIButton) { if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter){ var twitterSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter) twitterSheet.setInitialText("\(jokeLabel.text!)") self.presentViewController(twitterSheet, animated: true, completion: nil) } else { var alert = UIAlertController(title: "Accounts", message: "Please login to a Twitter account to share.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } func emailButtonDidPressed(sender: UIButton) { let mailComposeViewController = configuredMailComposeViewController() if MFMailComposeViewController.canSendMail() { self.presentViewController(mailComposeViewController, animated: true, completion: nil) } else { self.showSendMailErrorAlert() } } func configuredMailComposeViewController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property mailComposerVC.setSubject("Check this out. Such funny joke!") mailComposerVC.setMessageBody("\(jokeLabel.text!)", isHTML: false) return mailComposerVC } func showSendMailErrorAlert() { let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK") sendMailErrorAlert.show() } // MARK: MFMailComposeViewControllerDelegate Method func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) { controller.dismissViewControllerAnimated(true, completion: nil) } }
09bb46f046070ddb3dd4aef50c9dd9c4
39.215116
213
0.645077
false
false
false
false
swiftsanyue/TestKitchen
refs/heads/master
TestKitchen/TestKitchen/classes/ingredient(食材)/service(处理公共点击事件)/VideoService.swift
mit
1
// // VideoService.swift // TestKitchen // // Created by ZL on 16/11/3. // Copyright © 2016年 zl. All rights reserved. // import UIKit import AVKit import AVFoundation class VideoService: NSObject { class func playVideo(urlString: String?,onViewController vc: UIViewController){ if urlString != nil { let url = NSURL(string: urlString!) let player = AVPlayer(URL: url!) let videoCtrl = AVPlayerViewController() videoCtrl.player = player //播放 player.play() //显示界面 vc.presentViewController(videoCtrl, animated: true, completion: nil) } } }
f0ddddf2e69af14c0416760daf25716a
21
83
0.553719
false
false
false
false
egouletlang/BaseUtils
refs/heads/master
BaseUtils/Extension/CGColor_EXT.swift
mit
1
// // CGColor_EXT.swift // Bankroll // // Created by Etienne Goulet-Lang on 5/25/16. // Copyright © 2016 Etienne Goulet-Lang. All rights reserved. // import Foundation import CoreGraphics public extension CGColor { public func toRGB() -> UIColorRGB { let components = self.components let red = Int((components?[0])! * 255) let green = Int((components?[1])! * 255) let blue = Int((components?[2])! * 255) return Int64((red<<16) | (green<<8) | (blue)) } public func toColorComponents() -> [CGFloat] { let components = self.components return [ CGFloat(components![0]), CGFloat(components![1]), CGFloat(components![2]), CGFloat(components![3]) ] } public func toRGBString(_ prefixWithHash: Bool = true) -> String { guard let components = self.components, components.count >= 3 else { return "" } var r = NSString(format: "%X", UInt((components[0]) * 255)) var g = NSString(format: "%X", UInt((components[1]) * 255)) var b = NSString(format: "%X", UInt((components[2]) * 255)) if r.length == 1 {r = NSString(string: "0" + (r as String)) } if g.length == 1 {g = NSString(string: "0" + (g as String)) } if b.length == 1 {b = NSString(string: "0" + (b as String)) } return (prefixWithHash ? "#" : "") + (r as String) + (g as String) + (b as String) } }
f04f11b5602199209c26fff36e340bd7
30.265306
90
0.533943
false
false
false
false
ChromieIsDangerous/HamsterUIKit
refs/heads/master
HamsterUIKit/HamsBarChart.swift
apache-2.0
1
// // GradientedBarChat.swift // Hamster // // Created by Howard on 2/12/17. // Copyright © 2017 Howard Wang. All rights reserved. // import UIKit /// the protocol represnts the data model object public protocol HamsBarChartDataSource { /// implement this method to customize rectangular bars func barChart(_ barChart: HamsBarChart, barForChart indexPath: HamsIndexPath) -> HamsBarChartRect /// set number of charts func numberOfCharts(in barChart: HamsBarChart) -> Int /// set number of values in one chart func barChart(_ barChart: HamsBarChart, numberOfValuesInChart chart: Int) -> Int } /// this protocol represents the display and behaviour of the charts @objc public protocol HamsBarChartDelegate { /// should use this method to configue each chart @objc optional func barChart(_ barChart: HamsBarChart, configureForCharts chart: Int) } open class HamsBarChart: HamsChartBase { open weak var delegate: HamsBarChartDelegate? open var dataSource: HamsBarChartDataSource? open override var numberOfCharts: Int { return dataSource!.numberOfCharts(in: self) } open override func numberOfValues(in chart: Int) -> Int { guard let count = dataSource?.barChart(self, numberOfValuesInChart: chart) else { return 0 } return count } /// this will reload data and display open override func reloadData() { if dataSource != nil { self.configure() self.update() self.setNeedsDisplay() } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } convenience init() { self.init(frame: CGRect.zero) setup() } override public init(frame: CGRect) { super.init(frame: frame) setup() } override func update() { delegate?.barChart!(self, configureForCharts: currentChart) super.update() if numberOfValues > 0 { for i in 0..<numberOfValues(in: currentChart) { let rect = dataSource?.barChart(self, barForChart: HamsIndexPath(column: i, view: currentChart)) chartValues.append((rect?.value.sum)!) } } else { isDataEmpty = true } } override open func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() drawBackground(ctx: context!) drawBarchart(ctx: context!) } fileprivate func drawPlainBar(x: CGFloat, rect: HamsBarChartRect, height: CGFloat) { let path = UIBezierPath(roundedRect: CGRect(x: x, y: base-height, width: offsets.column, height: height), byRoundingCorners: [.topRight, .topLeft], cornerRadii: CGSize(width: 5, height: 5)) rect.color.colored().setFill() path.fill() } fileprivate func deawStackedBar(x: CGFloat, rect: HamsBarChartRect, height: CGFloat, vals: [CGFloat], scale: CGFloat) { var currSum: CGFloat = 0 for i in (0..<vals.count).reversed() { if i < vals.count - 1 { let path = UIBezierPath(rect: CGRect(x: x, y: base-height+currSum, width: offsets.column, height: vals[i]*scale)) currSum += vals[i]*scale rect.color.colored(rectIndex: i).setFill() path.fill() } else { let path = UIBezierPath(roundedRect: CGRect(x: x, y: base-height+currSum, width: offsets.column, height: vals[i]*scale), byRoundingCorners: [.topRight, .topLeft], cornerRadii: CGSize(width: 5, height: 5)) currSum += vals[i]*scale rect.color.colored(rectIndex: i).setFill() path.fill() } } } fileprivate func drawGroupedBar(x: CGFloat, rect: HamsBarChartRect, height: CGFloat, vals: [CGFloat]) { let groupedBars = ChartsCore(with: vals, frameSize: CGSize(width: offsets.column, height: height)) groupedBars.columnWidth = offsets.column / CGFloat(vals.count) groupedBars.topBorder = 0 groupedBars.bottomBorder = 0 groupedBars.alignment = .center groupedBars.gapWidth = 0 var groupedscale: CGFloat = 1 if let max = vals.max(), max > 0 { groupedscale = height / max } for j in 0..<vals.count { let groupedHeight = vals[j] * groupedscale let groupedPosX = groupedBars.getX(by: j) let path = UIBezierPath(rect: CGRect(x: groupedPosX + x, y: base-groupedHeight, width: groupedBars.columnWidth, height: groupedHeight)) rect.color.colored(rectIndex: j).setFill() path.fill() } } fileprivate func drawBarchart(ctx: CGContext) { let bars = ChartsCore(with: chartValues, frameSize: frame.size, offsets: offsets) var scale: CGFloat = 1 if let max = chartValues.max(), max > 0 { scale = (base - chartHeaderHeight) / max } for i in 0..<numberOfValues { let rect = (dataSource?.barChart(self, barForChart: HamsIndexPath(column: i, view: currentChart)))! let posX = bars.getX(by: i) let height = chartValues[i] * scale switch rect.value { case .plain: drawPlainBar(x: posX, rect: rect, height: height) case .stacked(let vals): deawStackedBar(x: posX, rect: rect, height: height, vals: vals, scale: scale) case .grouped(let vals): drawGroupedBar(x: posX, rect: rect, height: height, vals: vals) } drawLabels(column: i, posX: posX) } drawBaseline() } fileprivate func drawBaseline() { let path = UIBezierPath() path.move(to: CGPoint(x: offsets.horizon-5, y: base)) path.addLine(to: CGPoint(x: frame.width - offsets.horizon + 5, y: base)) UIColor.white.set() path.stroke() } fileprivate func drawLabels(column i: Int, posX: CGFloat) { let label = UILabel(frame: CGRect( x: posX-5, y: base+10, width: offsets.column + 10, height: 10)) label.text = "\(labels[i])" label.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.regular) label.textColor = labelsColor label.adjustsFontSizeToFitWidth = true label.textAlignment = .center label.tag = i+2000 self.addSubview(label) } fileprivate func drawBackground(ctx: CGContext) { let path = UIBezierPath(rect: bounds) switch filledStyle! { case .gradient(let top, let bottom): defaultColor = top ctx.saveGState() let colors = [top.cgColor, bottom.cgColor] let colorSpace = CGColorSpaceCreateDeviceRGB() let colorLocations: [CGFloat] = [0.0, 1.0] let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: colorLocations) ctx.addPath(path.cgPath) ctx.clip() let endPoint = CGPoint(x: offsets.horizon, y: frame.height) let startPoint = CGPoint(x: offsets.horizon, y: 0) ctx.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: .drawsBeforeStartLocation) ctx.restoreGState() case .plain(let color): defaultColor = color color.setFill() path.fill() } } }
216a802cd2cb94fc737c5c25c392fc72
29.174888
138
0.674989
false
false
false
false
CoderLala/DouYZBTest
refs/heads/master
DouYZB/DouYZB/Classes/Home/View/RecommendCycleView.swift
mit
1
// // RecommendCycleView.swift // DouYZB // // Created by 黄金英 on 17/2/8. // Copyright © 2017年 黄金英. All rights reserved. // import UIKit private let kCycleCellID = "kCycleCellID" class RecommendCycleView: UIView { //定义属性 var cycleTiemr : Timer? var cycleModels : [CycleModel]? { didSet { //1. 刷新collectionView collectionView.reloadData() //2. 设置pageControl的个数 pageControl.numberOfPages = cycleModels?.count ?? 0 //3. 默认滚动到中间某一个位置 let indexPath = IndexPath(item: (cycleModels?.count ?? 0) * 1000, section: 0) collectionView.scrollToItem(at: indexPath, at: .left, animated: false) //4.添加定时器 removeCycleTimer() addCycleTiemr() } } @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() //设置该控件 不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() //注册 cell collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false } } //MARK:- 提供一个快速创建View的方法 extension RecommendCycleView { class func recommendCycleView() -> RecommendCycleView { return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView } } //MARK:- collectionView datasource extension RecommendCycleView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (cycleModels?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell cell.cycleModel = cycleModels![(indexPath as NSIndexPath).item % cycleModels!.count] return cell } } //MARK:- collectionView delegate extension RecommendCycleView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { //1. 获取滚动的偏移量 let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 //2. 计算pageControl的currentIndex pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { //当用户将要拖拽时 移除监听 removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { //当用户停止拖拽时 添加监听 addCycleTiemr() } } //MARK:- 对定时器的操作方法 extension RecommendCycleView { fileprivate func addCycleTiemr() { cycleTiemr = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true) RunLoop.main.add(cycleTiemr!, forMode: .commonModes) } fileprivate func removeCycleTimer() { //从运行循环中移除 cycleTiemr?.invalidate() cycleTiemr = nil } @objc func scrollToNext() { //1. 获取当前偏移量、 获取下一个滚动的偏移量 let currentOffsetX = collectionView.contentOffset.x let nextOffsetX = currentOffsetX + collectionView.bounds.width //2. 滚动该位置 collectionView.setContentOffset(CGPoint(x: nextOffsetX, y: 0), animated: true) } }
f1bf6c66236518bcf19f92980672ca69
27.52381
129
0.636776
false
false
false
false
gowansg/firefox-ios
refs/heads/master
Sync/EncryptedJSON.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 import FxA import Account /** * Turns JSON of the form * * { ciphertext: ..., hmac: ..., iv: ...} * * into a new JSON object resulting from decrypting and parsing the ciphertext. */ public class EncryptedJSON : JSON { var _cleartext: JSON? // Cache decrypted cleartext. var _ciphertextBytes: NSData? // Cache decoded ciphertext. var _hmacBytes: NSData? // Cache decoded HMAC. var _ivBytes: NSData? // Cache decoded IV. var valid: Bool = false var validated: Bool = false let keyBundle: KeyBundle public init(json: String, keyBundle: KeyBundle) { self.keyBundle = keyBundle super.init(JSON.parse(json)) } public init(json: JSON, keyBundle: KeyBundle) { self.keyBundle = keyBundle super.init(json) } private func validate() -> Bool { if validated { return valid } valid = self["ciphertext"].isString && self["hmac"].isString && self["IV"].isString if (!valid) { validated = true return false } validated = true if let ciphertextForHMAC = self.ciphertextB64 { return keyBundle.verify(hmac: self.hmac, ciphertextB64: ciphertextForHMAC) } else { return false } } public func isValid() -> Bool { return !isError && self.validate() } func fromBase64(str: String) -> NSData { let b = Bytes.decodeBase64(str) return b } var ciphertextB64: NSData? { if let ct = self["ciphertext"].asString { return Bytes.dataFromBase64(ct) } else { return nil } } var ciphertext: NSData { if (_ciphertextBytes != nil) { return _ciphertextBytes! } _ciphertextBytes = fromBase64(self["ciphertext"].asString!) return _ciphertextBytes! } var hmac: NSData { if (_hmacBytes != nil) { return _hmacBytes! } _hmacBytes = NSData(base16EncodedString: self["hmac"].asString!, options: NSDataBase16DecodingOptions.Default) return _hmacBytes! } var iv: NSData { if (_ivBytes != nil) { return _ivBytes! } _ivBytes = fromBase64(self["IV"].asString!) return _ivBytes! } // Returns nil on error. public var cleartext: JSON? { if (_cleartext != nil) { return _cleartext } if (!validate()) { println("Failed to validate.") return nil } let decrypted: String? = keyBundle.decrypt(self.ciphertext, iv: self.iv) if (decrypted == nil) { println("Failed to decrypt.") valid = false return nil } _cleartext = JSON.parse(decrypted!) return _cleartext! } }
67a52efca8d398b9a4553d775d97e7c4
24.4
118
0.55482
false
false
false
false
BlessNeo/ios-charts
refs/heads/master
Charts/Classes/Renderers/ChartYAxisRendererHorizontalBarChart.swift
apache-2.0
37
// // ChartYAxisRendererHorizontalBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartYAxisRendererHorizontalBarChart: ChartYAxisRenderer { public override init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: transformer) } /// Computes the axis values. public override func computeAxis(var #yMin: Double, var yMax: Double) { // calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds) if (viewPortHandler.contentHeight > 10.0 && !viewPortHandler.isFullyZoomedOutX) { var p1 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) var p2 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) if (!_yAxis.isInverted) { yMin = Double(p1.x) yMax = Double(p2.x) } else { yMin = Double(p2.x) yMax = Double(p1.x) } } computeAxisValues(min: yMin, max: yMax) } /// draws the y-axis labels to the screen public override func renderAxisLabels(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.isDrawLabelsEnabled) { return } var positions = [CGPoint]() positions.reserveCapacity(_yAxis.entries.count) for (var i = 0; i < _yAxis.entries.count; i++) { positions.append(CGPoint(x: CGFloat(_yAxis.entries[i]), y: 0.0)) } transformer.pointValuesToPixel(&positions) var lineHeight = _yAxis.labelFont.lineHeight var baseYOffset: CGFloat = 2.5 var dependency = _yAxis.axisDependency var labelPosition = _yAxis.labelPosition var yPos: CGFloat = 0.0 if (dependency == .Left) { if (labelPosition == .OutsideChart) { yPos = viewPortHandler.contentTop - baseYOffset } else { yPos = viewPortHandler.contentTop - baseYOffset } } else { if (labelPosition == .OutsideChart) { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } else { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } } // For compatibility with Android code, we keep above calculation the same, // And here we pull the line back up yPos -= lineHeight drawYLabels(context: context, fixedPosition: yPos, positions: positions, offset: _yAxis.yOffset) } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderAxisLine(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.drawAxisLineEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _yAxis.axisLineColor.CGColor) CGContextSetLineWidth(context, _yAxis.axisLineWidth) if (_yAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _yAxis.axisLineDashPhase, _yAxis.axisLineDashLengths, _yAxis.axisLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } if (_yAxis.axisDependency == .Left) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } else { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } CGContextRestoreGState(context) } /// draws the y-labels on the specified x-position internal func drawYLabels(#context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat) { var labelFont = _yAxis.labelFont var labelTextColor = _yAxis.labelTextColor for (var i = 0; i < _yAxis.entryCount; i++) { var text = _yAxis.getFormattedLabel(i) if (!_yAxis.isDrawTopYLabelEntryEnabled && i >= _yAxis.entryCount - 1) { return } ChartUtils.drawText(context: context, text: text, point: CGPoint(x: positions[i].x, y: fixedPosition - offset), align: .Center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) } } public override func renderGridLines(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.isDrawGridLinesEnabled) { return } CGContextSaveGState(context) // pre alloc var position = CGPoint() CGContextSetStrokeColorWithColor(context, _yAxis.gridColor.CGColor) CGContextSetLineWidth(context, _yAxis.gridLineWidth) if (_yAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _yAxis.gridLineDashPhase, _yAxis.gridLineDashLengths, _yAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } // draw the horizontal grid for (var i = 0; i < _yAxis.entryCount; i++) { position.x = CGFloat(_yAxis.entries[i]) position.y = 0.0 transformer.pointValueToPixel(&position) CGContextBeginPath(context) CGContextMoveToPoint(context, position.x, viewPortHandler.contentTop) CGContextAddLineToPoint(context, position.x, viewPortHandler.contentBottom) CGContextStrokePath(context) } CGContextRestoreGState(context) } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderLimitLines(#context: CGContext) { var limitLines = _yAxis.limitLines if (limitLines.count <= 0) { return } CGContextSaveGState(context) var trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i] position.x = CGFloat(l.limit) position.y = 0.0 position = CGPointApplyAffineTransform(position, trans) _limitLineSegmentsBuffer[0].x = position.x _limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop _limitLineSegmentsBuffer[1].x = position.x _limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor) CGContextSetLineWidth(context, l.lineWidth) if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2) var label = l.label // if drawing the limit-value label is enabled if (count(label) > 0) { var labelLineHeight = l.valueFont.lineHeight let add = CGFloat(4.0) var xOffset: CGFloat = l.lineWidth var yOffset: CGFloat = add / 2.0 if (l.labelPosition == .Right) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } } CGContextRestoreGState(context) } }
04fd5d1ca1b2223bc01304f8d240472c
33.799296
233
0.56861
false
false
false
false
wenghengcong/Coderpursue
refs/heads/master
BeeFun/Pods/SwiftMessages/SwiftMessages/SwiftMessages.swift
mit
1
// // SwiftMessages.swift // SwiftMessages // // Created by Timothy Moose on 8/1/16. // Copyright © 2016 SwiftKick Mobile LLC. All rights reserved. // import UIKit private let globalInstance = SwiftMessages() /** The `SwiftMessages` class provides the interface for showing and hiding messages. It behaves like a queue, only showing one message at a time. Message views that adopt the `Identifiable` protocol (as `MessageView` does) will have duplicates removed. */ open class SwiftMessages { /** Specifies whether the message view is displayed at the top or bottom of the selected presentation container. */ public enum PresentationStyle { /** Message view slides down from the top. */ case top /** Message view slides up from the bottom. */ case bottom /** Message view fades into the center. */ case center /** User-defined animation */ case custom(animator: Animator) } /** Specifies how the container for presenting the message view is selected. */ public enum PresentationContext { /** Displays the message view under navigation bars and tab bars if an appropriate one is found. Otherwise, it is displayed in a new window at level `UIWindow.Level.normal`. Use this option to automatically display under bars, where applicable. Because this option involves a top-down search, an approrpiate context might not be found when the view controller heirarchy incorporates custom containers. If this is the case, the .ViewController option can provide a more targeted context. */ case automatic /** Displays the message in a new window at the specified window level. Use `UIWindow.Level.normal` to display under the status bar and `UIWindow.Level.statusBar` to display over. When displaying under the status bar, SwiftMessages automatically increases the top margins of any message view that adopts the `MarginInsetting` protocol (as `MessageView` does) to account for the status bar. */ case window(windowLevel: UIWindow.Level) /** Displays the message view under navigation bars and tab bars if an appropriate one is found using the given view controller as a starting point and searching up the parent view controller chain. Otherwise, it is displayed in the given view controller's view. This option can be used for targeted placement in a view controller heirarchy. */ case viewController(_: UIViewController) /** Displays the message view in the given container view. */ case view(_: UIView) } /** Specifies the duration of the message view's time on screen before it is automatically hidden. */ public enum Duration { /** Hide the message view after the default duration. */ case automatic /** Disables automatic hiding of the message view. */ case forever /** Hide the message view after the speficied number of seconds. - Parameter seconds: The number of seconds. */ case seconds(seconds: TimeInterval) /** The `indefinite` option is similar to `forever` in the sense that the message view will not be automatically hidden. However, it provides two options that can be useful in some scenarios: - `delay`: wait the specified time interval before displaying the message. If you hide the message during the delay interval by calling either `hideAll()` or `hide(id:)`, the message will not be displayed. This is not the case for `hide()` because it only acts on a visible message. Messages shown during another message's delay window are displayed first. - `minimum`: if the message is displayed, ensure that it is displayed for a minimum time interval. If you explicitly hide the during this interval, the message will be hidden at the end of the interval. This option is useful for displaying a message when a process is taking too long but you don't want to display the message if the process completes in a reasonable amount of time. The value `indefinite(delay: 0, minimum: 0)` is equivalent to `forever`. For example, if a URL load is expected to complete in 2 seconds, you may use the value `indefinite(delay: 2, minimum 1)` to ensure that the message will not be displayed in most cases, but will be displayed for at least 1 second if the operation takes longer than 2 seconds. By specifying a minimum duration, you can avoid hiding the message too fast if the operation finishes right after the delay interval. */ case indefinite(delay: TimeInterval, minimum: TimeInterval) } /** Specifies options for dimming the background behind the message view similar to a popover view controller. */ public enum DimMode { /** Don't dim the background behind the message view. */ case none /** Dim the background behind the message view a gray color. - `interactive`: Specifies whether or not tapping the dimmed area dismisses the message view. */ case gray(interactive: Bool) /** Dim the background behind the message view using the given color. SwiftMessages does not apply alpha transparency to the color, so any alpha must be baked into the `UIColor` instance. - `color`: The color of the dim view. - `interactive`: Specifies whether or not tapping the dimmed area dismisses the message view. */ case color(color: UIColor, interactive: Bool) /** Dim the background behind the message view using a blur effect with the given style - `style`: The blur effect style to use - `alpha`: The alpha level of the blur - `interactive`: Specifies whether or not tapping the dimmed area dismisses the message view. */ case blur(style: UIBlurEffect.Style, alpha: CGFloat, interactive: Bool) public var interactive: Bool { switch self { case .gray(let interactive): return interactive case .color(_, let interactive): return interactive case .blur (_, _, let interactive): return interactive case .none: return false } } public var modal: Bool { switch self { case .gray, .color, .blur: return true case .none: return false } } } /** Specifies events in the message lifecycle. */ public enum Event { case willShow case didShow case willHide case didHide } /** A closure that takes an `Event` as an argument. */ public typealias EventListener = (Event) -> Void /** The `Config` struct specifies options for displaying a single message view. It is provided as an optional argument to one of the `MessageView.show()` methods. */ public struct Config { public init() {} /** Specifies whether the message view is displayed at the top or bottom of the selected presentation container. The default is `.Top`. */ public var presentationStyle = PresentationStyle.top /** Specifies how the container for presenting the message view is selected. The default is `.Automatic`. */ public var presentationContext = PresentationContext.automatic /** Specifies the duration of the message view's time on screen before it is automatically hidden. The default is `.Automatic`. */ public var duration = Duration.automatic /** Specifies options for dimming the background behind the message view similar to a popover view controller. The default is `.None`. */ public var dimMode = DimMode.none /** Specifies whether or not the interactive pan-to-hide gesture is enabled on the message view. For views that implement the `BackgroundViewable` protocol (as `MessageView` does), the pan gesture recognizer is installed in the `backgroundView`, which allows for card-style views with transparent margins that shouldn't be interactive. Otherwise, it is installed in the message view itself. The default is `true`. */ public var interactiveHide = true /** Specifies the preferred status bar style when the view is displayed directly behind the status bar, such as when using `.Window` presentation context with a `UIWindow.Level.normal` window level and `.Top` presentation style. This option is useful if the message view has a background color that needs a different status bar style than the current one. The default is `.Default`. */ public var preferredStatusBarStyle: UIStatusBarStyle? /** If a view controller is created to host the message view, should the view controller auto rotate? The default is 'true', meaning it should auto rotate. */ public var shouldAutorotate = true /** Specified whether or not duplicate `Identifiable` messages are ignored. The default is `true`. */ public var ignoreDuplicates = true /** Specifies an optional array of event listeners. */ public var eventListeners: [EventListener] = [] /** Specifies that in cases where the message is displayed in its own window, such as with `.window` presentation context, the window should become the key window. This option should only be used if the message view needs to receive non-touch events, such as keyboard input. From Apple's documentation https://developer.apple.com/reference/uikit/uiwindow: > Whereas touch events are delivered to the window where they occurred, > events that do not have a relevant coordinate value are delivered to > the key window. Only one window at a time can be the key window, and > you can use a window’s keyWindow property to determine its status. > Most of the time, your app’s main window is the key window, but UIKit > may designate a different window as needed. */ public var becomeKeyWindow: Bool? /** The `dimMode` background will use this accessibility label, e.g. "dismiss" when the `interactive` option is used. */ public var dimModeAccessibilityLabel: String = "dismiss" /** If specified, SwiftMessages calls this closure when an instance of `WindowViewController` is needed. Use this if you need to supply a custom subclass of `WindowViewController`. */ public var windowViewController: ((_ windowLevel: UIWindow.Level?, _ config: SwiftMessages.Config) -> WindowViewController)? /** Supply an instance of `KeyboardTrackingView` to have the message view avoid the keyboard. */ public var keyboardTrackingView: KeyboardTrackingView? } /** Not much to say here. */ public init() {} /** Adds the given configuration and view to the message queue to be displayed. - Parameter config: The configuration options. - Parameter view: The view to be displayed. */ open func show(config: Config, view: UIView) { let presenter = Presenter(config: config, view: view, delegate: self) messageQueue.sync { enqueue(presenter: presenter) } } /** Adds the given view to the message queue to be displayed with default configuration options. - Parameter config: The configuration options. - Parameter view: The view to be displayed. */ public func show(view: UIView) { show(config: defaultConfig, view: view) } /// A block that returns an arbitrary view. public typealias ViewProvider = () -> UIView /** Adds the given configuration and view provider to the message queue to be displayed. The `viewProvider` block is guaranteed to be called on the main queue where it is safe to interact with `UIKit` components. This variant of `show()` is recommended when the message might be added from a background queue. - Parameter config: The configuration options. - Parameter viewProvider: A block that returns the view to be displayed. */ open func show(config: Config, viewProvider: @escaping ViewProvider) { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } let view = viewProvider() strongSelf.show(config: config, view: view) } } /** Adds the given view provider to the message queue to be displayed with default configuration options. The `viewProvider` block is guaranteed to be called on the main queue where it is safe to interact with `UIKit` components. This variant of `show()` is recommended when the message might be added from a background queue. - Parameter viewProvider: A block that returns the view to be displayed. */ public func show(viewProvider: @escaping ViewProvider) { show(config: defaultConfig, viewProvider: viewProvider) } /** Hide the current message being displayed by animating it away. */ open func hide(animated: Bool = true) { messageQueue.sync { hideCurrent(animated: animated) } } /** Hide the current message, if there is one, by animating it away and clear the message queue. */ open func hideAll() { messageQueue.sync { queue.removeAll() delays.ids.removeAll() counts.removeAll() hideCurrent() } } /** Hide a message with the given `id`. If the specified message is currently being displayed, it will be animated away. Works with message views, such as `MessageView`, that adopt the `Identifiable` protocol. - Parameter id: The identifier of the message to remove. */ open func hide(id: String) { messageQueue.sync { if id == _current?.id { hideCurrent() } queue = queue.filter { $0.id != id } delays.ids.remove(id) counts[id] = nil } } /** Hide the message when the number of calls to show() and hideCounted(id:) for a given message ID are equal. This can be useful for messages that may be shown from multiple code paths to ensure that all paths are ready to hide. */ open func hideCounted(id: String) { messageQueue.sync { if let count = counts[id] { if count < 2 { counts[id] = nil } else { counts[id] = count - 1 return } } if id == _current?.id { hideCurrent() } queue = queue.filter { $0.id != id } delays.ids.remove(id) } } /** Get the count of a message with the given ID (see `hideCounted(id:)`) */ public func count(id: String) -> Int { return counts[id] ?? 0 } /** Explicitly set the count of a message with the given ID (see `hideCounted(id:)`). Not sure if there's a use case for this, but why not?! */ public func set(count: Int, for id: String) { guard counts[id] != nil else { return } return counts[id] = count } /** Specifies the default configuration to use when calling the variants of `show()` that don't take a `config` argument or as a base for custom configs. */ public var defaultConfig = Config() /** Specifies the amount of time to pause between removing a message and showing the next. Default is 0.5 seconds. */ open var pauseBetweenMessages: TimeInterval = 0.5 /// Type for keeping track of delayed presentations fileprivate class Delays { fileprivate var ids = Set<String>() fileprivate func add(presenter: Presenter) { ids.insert(presenter.id) } @discardableResult fileprivate func remove(presenter: Presenter) -> Bool { guard ids.contains(presenter.id) else { return false } ids.remove(presenter.id) return true } } func show(presenter: Presenter) { messageQueue.sync { enqueue(presenter: presenter) } } fileprivate let messageQueue = DispatchQueue(label: "it.swiftkick.SwiftMessages", attributes: []) fileprivate var queue: [Presenter] = [] fileprivate var delays = Delays() fileprivate var counts: [String : Int] = [:] fileprivate var _current: Presenter? = nil { didSet { if oldValue != nil { let delayTime = DispatchTime.now() + pauseBetweenMessages messageQueue.asyncAfter(deadline: delayTime) { [weak self] in self?.dequeueNext() } } } } fileprivate func enqueue(presenter: Presenter) { if presenter.config.ignoreDuplicates { counts[presenter.id] = (counts[presenter.id] ?? 0) + 1 if _current?.id == presenter.id && _current?.isHiding == false { return } if queue.filter({ $0.id == presenter.id }).count > 0 { return } } func doEnqueue() { queue.append(presenter) dequeueNext() } if let delay = presenter.delayShow { delays.add(presenter: presenter) messageQueue.asyncAfter(deadline: .now() + delay) { [weak self] in // Don't enqueue if the view has been hidden during the delay window. guard let strongSelf = self, strongSelf.delays.remove(presenter: presenter) else { return } doEnqueue() } } else { doEnqueue() } } fileprivate func dequeueNext() { guard self._current == nil, queue.count > 0 else { return } let current = queue.removeFirst() self._current = current // Set `autohideToken` before the animation starts in case // the dismiss gesture begins before we've queued the autohide // block on animation completion. self.autohideToken = current current.showDate = CACurrentMediaTime() DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } do { try current.show { completed in guard let strongSelf = self else { return } guard completed else { strongSelf.messageQueue.sync { strongSelf.internalHide(id: current.id) } return } if current === strongSelf.autohideToken { strongSelf.queueAutoHide() } } } catch { strongSelf.messageQueue.sync { strongSelf._current = nil } } } } fileprivate func internalHide(id: String) { if id == _current?.id { hideCurrent() } queue = queue.filter { $0.id != id } delays.ids.remove(id) } fileprivate func hideCurrent(animated: Bool = true) { guard let current = _current, !current.isHiding else { return } let action = { [weak self] in current.hide(animated: animated) { (completed) in guard completed, let strongSelf = self else { return } strongSelf.messageQueue.sync { guard strongSelf._current === current else { return } strongSelf.counts[current.id] = nil strongSelf._current = nil } } } let delay = current.delayHide ?? 0 DispatchQueue.main.asyncAfter(deadline: .now() + delay) { action() } } fileprivate weak var autohideToken: AnyObject? fileprivate func queueAutoHide() { guard let current = _current else { return } autohideToken = current if let pauseDuration = current.pauseDuration { let delayTime = DispatchTime.now() + pauseDuration messageQueue.asyncAfter(deadline: delayTime, execute: { // Make sure we've still got a green light to auto-hide. if self.autohideToken !== current { return } self.internalHide(id: current.id) }) } } deinit { // Prevent orphaned messages hideCurrent() } } /* MARK: - Accessing messages */ extension SwiftMessages { /** Returns the message view of type `T` if it is currently being shown or hidden. - Returns: The view of type `T` if it is currently being shown or hidden. */ public func current<T: UIView>() -> T? { var view: T? messageQueue.sync { view = _current?.view as? T } return view } /** Returns a message view with the given `id` if it is currently being shown or hidden. - Parameter id: The id of a message that adopts `Identifiable`. - Returns: The view with matching id if currently being shown or hidden. */ public func current<T: UIView>(id: String) -> T? { var view: T? messageQueue.sync { if let current = _current, current.id == id { view = current.view as? T } } return view } /** Returns a message view with the given `id` if it is currently in the queue to be shown. - Parameter id: The id of a message that adopts `Identifiable`. - Returns: The view with matching id if currently queued to be shown. */ public func queued<T: UIView>(id: String) -> T? { var view: T? messageQueue.sync { if let queued = queue.first(where: { $0.id == id }) { view = queued.view as? T } } return view } /** Returns a message view with the given `id` if it is currently being shown, hidden or in the queue to be shown. - Parameter id: The id of a message that adopts `Identifiable`. - Returns: The view with matching id if currently queued to be shown. */ public func currentOrQueued<T: UIView>(id: String) -> T? { return current(id: id) ?? queued(id: id) } } /* MARK: - PresenterDelegate */ extension SwiftMessages: PresenterDelegate { func hide(presenter: Presenter) { messageQueue.sync { self.internalHide(id: presenter.id) } } public func hide(animator: Animator) { messageQueue.sync { guard let presenter = self.presenter(forAnimator: animator) else { return } self.internalHide(id: presenter.id) } } public func panStarted(animator: Animator) { autohideToken = nil } public func panEnded(animator: Animator) { queueAutoHide() } private func presenter(forAnimator animator: Animator) -> Presenter? { if let current = _current, animator === current.animator { return current } let queued = queue.filter { $0.animator === animator } return queued.first } } /** MARK: - Creating views from nibs This extension provides several convenience functions for instantiating views from nib files. SwiftMessages provides several default nib files in the Resources folder that can be drag-and-dropped into a project as a starting point and modified. */ extension SwiftMessages { /** Loads a nib file with the same name as the generic view type `T` and returns the first view found in the nib file with matching type `T`. For example, if the generic type is `MyView`, a nib file named `MyView.nib` is loaded and the first top-level view of type `MyView` is returned. The main bundle is searched first followed by the SwiftMessages bundle. - Parameter filesOwner: An optional files owner. - Throws: `Error.CannotLoadViewFromNib` if a view matching the generic type `T` is not found in the nib. - Returns: An instance of generic view type `T`. */ public class func viewFromNib<T: UIView>(_ filesOwner: AnyObject = NSNull.init()) throws -> T { let name = T.description().components(separatedBy: ".").last assert(name != nil) let view: T = try internalViewFromNib(named: name!, bundle: nil, filesOwner: filesOwner) return view } /** Loads a nib file with specified name and returns the first view found in the nib file with matching type `T`. The main bundle is searched first followed by the SwiftMessages bundle. - Parameter name: The name of the nib file (excluding the .xib extension). - Parameter filesOwner: An optional files owner. - Throws: `Error.CannotLoadViewFromNib` if a view matching the generic type `T` is not found in the nib. - Returns: An instance of generic view type `T`. */ public class func viewFromNib<T: UIView>(named name: String, filesOwner: AnyObject = NSNull.init()) throws -> T { let view: T = try internalViewFromNib(named: name, bundle: nil, filesOwner: filesOwner) return view } /** Loads a nib file with specified name in the specified bundle and returns the first view found in the nib file with matching type `T`. - Parameter name: The name of the nib file (excluding the .xib extension). - Parameter bundle: The name of the bundle containing the nib file. - Parameter filesOwner: An optional files owner. - Throws: `Error.CannotLoadViewFromNib` if a view matching the generic type `T` is not found in the nib. - Returns: An instance of generic view type `T`. */ public class func viewFromNib<T: UIView>(named name: String, bundle: Bundle, filesOwner: AnyObject = NSNull.init()) throws -> T { let view: T = try internalViewFromNib(named: name, bundle: bundle, filesOwner: filesOwner) return view } fileprivate class func internalViewFromNib<T: UIView>(named name: String, bundle: Bundle? = nil, filesOwner: AnyObject = NSNull.init()) throws -> T { let resolvedBundle: Bundle if let bundle = bundle { resolvedBundle = bundle } else { if Bundle.main.path(forResource: name, ofType: "nib") != nil { resolvedBundle = Bundle.main } else { resolvedBundle = Bundle.sm_frameworkBundle() } } let arrayOfViews = resolvedBundle.loadNibNamed(name, owner: filesOwner, options: nil) ?? [] #if swift(>=4.1) guard let view = arrayOfViews.compactMap( { $0 as? T} ).first else { throw SwiftMessagesError.cannotLoadViewFromNib(nibName: name) } #else guard let view = arrayOfViews.flatMap( { $0 as? T} ).first else { throw SwiftMessagesError.cannotLoadViewFromNib(nibName: name) } #endif return view } } /* MARK: - Static APIs This extension provides a shared instance of `SwiftMessages` and a static API wrapper around this instance for simplified syntax. For example, `SwiftMessages.show()` is equivalent to `SwiftMessages.sharedInstance.show()`. */ extension SwiftMessages { /** A default shared instance of `SwiftMessages`. The `SwiftMessages` class provides a set of static APIs that wrap calls to this instance. For example, `SwiftMessages.show()` is equivalent to `SwiftMessages.sharedInstance.show()`. */ public static var sharedInstance: SwiftMessages { return globalInstance } public static func show(viewProvider: @escaping ViewProvider) { globalInstance.show(viewProvider: viewProvider) } public static func show(config: Config, viewProvider: @escaping ViewProvider) { globalInstance.show(config: config, viewProvider: viewProvider) } public static func show(view: UIView) { globalInstance.show(view: view) } public static func show(config: Config, view: UIView) { globalInstance.show(config: config, view: view) } public static func hide(animated: Bool = true) { globalInstance.hide(animated: animated) } public static func hideAll() { globalInstance.hideAll() } public static func hide(id: String) { globalInstance.hide(id: id) } public static func hideCounted(id: String) { globalInstance.hideCounted(id: id) } public static var defaultConfig: Config { get { return globalInstance.defaultConfig } set { globalInstance.defaultConfig = newValue } } public static var pauseBetweenMessages: TimeInterval { get { return globalInstance.pauseBetweenMessages } set { globalInstance.pauseBetweenMessages = newValue } } public static func current<T: UIView>(id: String) -> T? { return globalInstance.current(id: id) } public static func queued<T: UIView>(id: String) -> T? { return globalInstance.queued(id: id) } public static func currentOrQueued<T: UIView>(id: String) -> T? { return globalInstance.currentOrQueued(id: id) } public static func count(id: String) -> Int { return globalInstance.count(id: id) } public static func set(count: Int, for id: String) { globalInstance.set(count: count, for: id) } }
b95c699ae42ab5bd9e16393b22b0e429
33.920493
153
0.603098
false
false
false
false
cheyongzi/MGTV-Swift
refs/heads/master
MGTV-Swift/Share/Extension/CommonExtension.swift
mit
1
// // CommonExtension.swift // MGTV-Swift // // Created by Che Yongzi on 16/6/24. // Copyright © 2016年 Che Yongzi. All rights reserved. // import UIKit let HNTVDeviceHeight = UIScreen.main.bounds.size.height let HNTVDeviceWidth = UIScreen.main.bounds.size.width let HNTVNavigationBarHeight = 64 let HNTVTabBarHeight = 49 func +(leftSize: CGSize, rightSize: CGSize) -> CGSize { return CGSize(width: leftSize.width + rightSize.width, height: rightSize.height) } func isEmpty(data: Any?) -> Bool { if let stringValue = data as? String { if !stringValue.isEmpty { return false } } return true } extension String { func pathExtension() -> String { return (self as NSString).pathExtension } } extension UIColor { public convenience init(hexString: String) { let hexString = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let scanner = Scanner(string: hexString) if (hexString.hasPrefix("#")) { scanner.scanLocation = 1 } var color: UInt32 = 0 if scanner.scanHexInt32(&color) { self.init(hex: color) } else { self.init(hex: 0x000000) } } public convenience init(hex: UInt32) { let mask = 0x000000FF let r = Int(hex >> 16) & mask let g = Int(hex >> 8) & mask let b = Int(hex) & mask let red = CGFloat(r) / 255 let green = CGFloat(g) / 255 let blue = CGFloat(b) / 255 self.init(red:red, green:green, blue:blue, alpha:1) } }
50cf2fbda19075f7b0012bcbf37d8255
23.426471
93
0.586996
false
false
false
false
CherishSmile/ZYBase
refs/heads/master
ZYBase/Tools/ZYCustomeAlert/ExampleAlert/ZYCustomSelectAlert.swift
mit
1
// // ZYCustomSelectAlert.swift // ZYBase // // Created by Mzywx on 2017/3/1. // Copyright © 2017年 Mzywx. All rights reserved. // import UIKit public typealias ZYSelectAlertCompletionClosure = (Int) -> Void open class ZYCustomSelectAlert: UIView,UITableViewDelegate,UITableViewDataSource { public var titleArr : Array<String>! public var completion : ZYSelectAlertCompletionClosure? lazy var selectTab: UITableView = { let tab = UITableView(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH-100, height: CGFloat(self.titleArr.count)*getPtH(80)), style: .plain) tab.backgroundColor = .white tab.layer.masksToBounds = true tab.layer.cornerRadius = 4.0 tab.delegate = self tab.dataSource = self tab.bounces = false return tab }() public init(_ title:String,_ selectTitles:Array<String>,_ completion:@escaping ZYSelectAlertCompletionClosure) { super.init(frame: .zero) self.completion = completion titleArr = selectTitles titleArr.insert(title, at: 0) self.frame = CGRect(x: 50, y: (SCREEN_HEIGHT-CGFloat(self.titleArr.count)*getPtH(80))/2, width: SCREEN_WIDTH-100, height: CGFloat(self.titleArr.count)*getPtH(80)) self.addSubview(selectTab) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func numberOfSections(in tableView: UITableView) -> Int { return 1 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titleArr.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cellID") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cellID") } if indexPath.row>0 { cell?.textLabel?.textColor = .blue; } cell?.textLabel?.text = titleArr[indexPath.row] cell?.textLabel?.font = getFont(getPtW(30)) return cell! } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.row>0 { if completion != nil { completion!(indexPath.row) } dismissZYAlert() } } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return getPtH(80) } }
076ae5ebf1334fd97876430b44d2be51
33.710526
170
0.643669
false
false
false
false
sidewinder-team/sidewinder-ios
refs/heads/master
SidewinderTests/AppDelegateTest.swift
mit
1
import Quick import Nimble import Sidewinder class AppDelegateTest: QuickSpec { override func spec() { describe("When the application registers a device token") { it("will create a Job Subscription Service with that token") { let app = UIApplication.sharedApplication() expectExists(app.delegate) { delegate in let data = "DeviceToken#1".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) delegate.application?(app, didRegisterForRemoteNotificationsWithDeviceToken: data!) expect(JobSubscriptionServiceInstance?.DeviceToken).to(equal(data)) } } } } } public func expectExists<T>(potentialValue: T?, file: String = __FILE__, line: UInt = __LINE__, then: (value: T) -> Void) { if let value = potentialValue { then(value: value) } else { XCTFail("Value did not exist.", file: file, line: line) } }
2917da1414b769ff378ecac340a4df55
36.185185
124
0.616534
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/Card/CardDetails/CardDetailsScreenViewController.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import BlockchainNamespace import Combine import DIKit import Errors import ErrorsUI import Localization import RxSwift import SwiftUI import ToolKit import UIComponentsKit final class CardDetailsScreenViewController: BaseTableViewController { // MARK: - Injected private let keyboardObserver = KeyboardObserver() private let presenter: CardDetailsScreenPresenter private let alertPresenter: AlertViewPresenterAPI private let app: AppProtocol private var keyboardInteractionController: KeyboardInteractionController! private var clearSubscription: AnyCancellable? private let disposeBag = DisposeBag() // MARK: - Setup init( presenter: CardDetailsScreenPresenter, alertPresenter: AlertViewPresenterAPI = resolve(), app: AppProtocol = resolve() ) { self.presenter = presenter self.alertPresenter = alertPresenter self.app = app super.init() } @available(*, unavailable) required init?(coder: NSCoder) { nil } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() presenter.viewDidLoad() setupNavigationBar() keyboardInteractionController = KeyboardInteractionController( in: scrollView, disablesToolBar: false ) setupTableView() setupKeyboardObserver() presenter.error .emit(weak: self) { (self, error) in switch error { case .cardAlreadySaved: typealias LocalizedString = LocalizationConstants.CardDetailsScreen.Alert self.alertPresenter.notify( content: .init( title: LocalizedString.title, message: LocalizedString.message ), in: self ) case .generic: self.alertPresenter.error(in: self, action: nil) } } .disposed(by: disposeBag) presenter.ux .emit(weak: self) { (self, ux) in self.presentUXErrorViewModel(ux) } .disposed(by: disposeBag) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) presenter.viewWillAppear() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) keyboardObserver.setup() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) keyboardObserver.remove() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) presenter.viewDidDisappear() } private func setupNavigationBar() { titleViewStyle = .text(value: presenter.title) setStandardDarkContentStyle() } private func setupKeyboardObserver() { keyboardObserver.state .bindAndCatch(weak: self) { (self, state) in switch state.visibility { case .visible: self.contentBottomConstraint.constant = -(state.payload.height - self.view.safeAreaInsets.bottom) case .hidden: self.contentBottomConstraint.constant = 0 } self.view.layoutIfNeeded() } .disposed(by: disposeBag) } private func setupTableView() { tableView.selfSizingBehaviour = .fill tableView.tableFooterView = UIView() tableView.estimatedRowHeight = 80 tableView.rowHeight = UITableView.automaticDimension tableView.register(TextFieldTableViewCell.self) tableView.register(DoubleTextFieldTableViewCell.self) tableView.register(NoticeTableViewCell.self) tableView.register(HostingTableViewCell<CreditCardLearnMoreView>.self) tableView.registerNibCell(ButtonsTableViewCell.self, in: .module) tableView.separatorColor = .clear tableView.delegate = self tableView.dataSource = self } private func presentUXErrorViewModel(_ ux: UX.Error) { let errorViewController = UINavigationController( rootViewController: UIHostingController( rootView: ErrorView( ux: ux, dismiss: { [weak self] in self?.dismiss(animated: true) } ) .app(app) ) ) if #available(iOS 15.0, *) { if let sheet = errorViewController.sheetPresentationController { sheet.prefersGrabberVisible = true sheet.detents = [.medium()] } } clearSubscription = app.on(blockchain.ux.transaction.action.add.card) { [weak self] _ in self?.presenter.clear() self?.tableView.reloadData() self?.dismiss(animated: true) } .subscribe() present(errorViewController, animated: true) } // MARK: - Navigation override func navigationBarTrailingButtonPressed() { presenter.previous() } } // MARK: - UITableViewDelegate, UITableViewDataSource extension CardDetailsScreenViewController: UITableViewDelegate, UITableViewDataSource { private func textFieldCell(for row: Int, type: TextFieldType) -> UITableViewCell { let cell = tableView.dequeue( TextFieldTableViewCell.self, for: IndexPath(row: row, section: 0) ) cell.setup( viewModel: presenter.textFieldViewModelByType[type]!, keyboardInteractionController: keyboardInteractionController, scrollView: tableView ) return cell } private func doubleTextFieldCell( for row: Int, leadingType: TextFieldType, trailingType: TextFieldType ) -> UITableViewCell { let cell = tableView.dequeue( DoubleTextFieldTableViewCell.self, for: IndexPath(row: row, section: 0) ) cell.setup( viewModel: .init( leading: presenter.textFieldViewModelByType[leadingType]!, trailing: presenter.textFieldViewModelByType[trailingType]! ), keyboardInteractionController: keyboardInteractionController, scrollView: tableView ) return cell } private func buttonTableViewCell( for row: Int, viewModel: ButtonViewModel ) -> UITableViewCell { let cell = tableView.dequeue( ButtonsTableViewCell.self, for: IndexPath(row: row, section: 0) ) cell.models = [viewModel] return cell } private func privacyNoticeCell(for type: CardDetailsScreenPresenter.CellType) -> UITableViewCell { let cell = tableView.dequeue( NoticeTableViewCell.self, for: IndexPath(row: type.row, section: 0) ) cell.viewModel = presenter.noticeViewModel return cell } private func creditCardLearnMoreCell(for type: CardDetailsScreenPresenter.CellType) -> UITableViewCell { let cell = tableView.dequeue( HostingTableViewCell<CreditCardLearnMoreView>.self, for: IndexPath(row: type.row, section: 0) ) cell.host(CreditCardLearnMoreView(app: app), parent: self) return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { presenter.rowCount } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellType = CardDetailsScreenPresenter.CellType(indexPath.row) switch cellType { case .button: return buttonTableViewCell( for: cellType.row, viewModel: presenter.buttonViewModel ) case .textField(let type): return textFieldCell(for: cellType.row, type: type) case .doubleTextField(let leadingType, let trailingType): return doubleTextFieldCell( for: cellType.row, leadingType: leadingType, trailingType: trailingType ) case .creditCardLearnMore: return creditCardLearnMoreCell(for: cellType) case .privacyNotice: return privacyNoticeCell(for: cellType) } } }
9f45fa1d16191a3f237d8d599caf7fee
31.643939
117
0.612787
false
false
false
false
ektodorov/XmlParserP
refs/heads/master
XmlParserPiOS/XmlParserPiOS/XmlElementTreeP.swift
apache-2.0
1
// // XmlElementTreeP.swift // XmlParserPiOS // import UIKit open class XmlElementTreeP: NSObject { fileprivate var mElementParent: XmlElementTreeP?; fileprivate var mElementCurrent: XmlElementP; fileprivate var mArrayElements: Array<XmlElementTreeP>; fileprivate var mMapChildElements: MultiHashMapP<String, Int>; public override init() { mElementParent = nil; mElementCurrent = XmlElementP(); mArrayElements = Array<XmlElementTreeP>(); mMapChildElements = MultiHashMapP<String, Int>(); super.init(); } //mElementParent; /** Gets the parent tag element of this one. */ open func getElementParent()->XmlElementTreeP? {return mElementParent;} /** Sets the parent tag element of this one. */ open func setElementParent(_ aElementParent: XmlElementTreeP) {mElementParent = aElementParent;} //mElementCurrent /** Gets this XML tag element. */ open func getElement()->XmlElementP {return mElementCurrent;} /** Sets this XML tag elements. */ open func setElement(_ aElement: XmlElementP) {mElementCurrent = aElement;} //mArrayElements /** Gets the array holding all tag elements for this XML document. */ open func getArrayElements()->Array<XmlElementTreeP> {return mArrayElements;} //mMapChildElements open func getMapChildElements()->MultiHashMapP<String, Int> {return mMapChildElements;} open func setMapChildElements(_ aMapChildElements: MultiHashMapP<String, Int>) {mMapChildElements = aMapChildElements;} /** Sets the array holding all tag elements for this XML document. */ open func setArrayElements(_ aArrayElements: Array<XmlElementTreeP>) {mArrayElements = aArrayElements;} /** Adds a child element to this one. */ open func addChildElement(_ aElementTree: XmlElementTreeP) { mMapChildElements.put(aElementTree.getElementName(), aValue:mArrayElements.count); mArrayElements.append(aElementTree); } /** Removes a child element from this one. */ open func removeChildElement(_ aElementTree: XmlElementTreeP) { var idx: Int = 0; let count: Int = mArrayElements.count; for x in 0..<count { let element: XmlElementTreeP = mArrayElements[x]; if(aElementTree == element) { idx = x; break; } } mMapChildElements.remove(aElementTree.getElementName(), aValue:idx); } /** Adds a child element to this one at the specified index. */ open func addChildElementAt(_ aIndex: Int, aElementTree: XmlElementTreeP) { mMapChildElements.put(aElementTree.getElementName(), aValue:aIndex); } /** Removes a child element from this one at the specified index. */ open func removeChildElementAt(_ aIndex: Int) { let element: XmlElementTreeP = mArrayElements.remove(at: aIndex); mMapChildElements.remove(element.getElementName(), aValue:aIndex); } /** Gets the Namespace of the current XmlElementP. */ open func getElementNamespace()->String? {return mElementCurrent.getElementNamespace();} /** sets the Namespace of the current XmlElementP. */ open func setElementNamespace(_ aElementNamespace: String) {mElementCurrent.setElementNamespace(aElementNamespace);} /** Gets the name of the current XmlElementP. */ open func getElementName()->String {return mElementCurrent.getElementName();} /** Sets the name of the current XmlElementP. */ open func setElementName(_ aName: String) {mElementCurrent.setElementName(aName);} /** Gets the HashMap<String, String> of attributes of the current XmlElementP. */ open func getElementAttributes()->Array<Dictionary<String, String>> { return mElementCurrent.getElementAttributes(); } /** Sets the HashMap<String, String> of attributes of the current XmlElementP. */ open func setElementAttributes(_ aArrayAttributes: Array<Dictionary<String, String>>) { mElementCurrent.setElementAttributes(aArrayAttributes); } /** Gets the content of the current XmlElementP. */ open func getElementContent()->String {return mElementCurrent.getElementContent();} /** Sets the content of the current XmlElementP. */ open func setElementContent(_ aContent: String) {mElementCurrent.setElementContent(aContent);} /** * Gets Array of all XmlElementTreeP with the specified name. * @param String aName - name of a tag. * @return ArrayList<XmlElementTreeP> - array of all XmlElementTreeP with the specified name. */ open func getElements(_ aName: String)->Array<XmlElementTreeP>? { var retVal: Array<XmlElementTreeP>? = nil; var array: Array<Int>? = mMapChildElements.get(aName); if(array == nil) {return retVal;} retVal = Array<XmlElementTreeP>(); let count: Int = array!.count; for x in 0..<count { let element: XmlElementTreeP = mArrayElements[array![x]]; retVal?.append(element); } return retVal; } /** * Gets the first element in the array of child elements that has the passed in name. * We would normally use this when we know that there is only one child with that name, as a convenience to calling:<br/> * <code>someElement.getElements("tag_name").get(0).getElementContent();</code> * @param String aTagName * @return String - contents of the tag with the passed in name */ open func get(_ aTagName: String)->String { var content: String = ConstantsP.STR_EMPTY; var arrayIdxs: Array<Int>? = mMapChildElements.get(aTagName); if(arrayIdxs != nil && arrayIdxs!.count > 0) { let idx: Int = arrayIdxs![0]; let child: XmlElementTreeP = mArrayElements[idx]; content = child.getElementContent(); } return content; } } public func ==(lhs: XmlElementTreeP, rhs: XmlElementTreeP)->Bool { if(lhs === rhs) {return true;} if(lhs.mElementParent == rhs.mElementParent && lhs.mElementCurrent == rhs.mElementCurrent && lhs.mArrayElements == rhs.mArrayElements) { return true; } return false; }
347c6a181030df5ddb2ca7b4fbfa7c20
37.658385
123
0.676253
false
false
false
false
i-schuetz/scene_kit_pick
refs/heads/master
SceneKitPick/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // SceneKitPick // // Created by ischuetz on 24/07/2014. // Copyright (c) 2014 ivanschuetz. All rights reserved. // import Cocoa class AppDelegate: NSObject, NSApplicationDelegate, ItemSelectionDelegate { @IBOutlet var window: NSWindow! @IBOutlet var sceneView: SceneView! @IBOutlet var selectionLabel: NSTextField! //Map the object names from .dae to strings we want to show to the user let partNames = ["head" : "Head", "eye_l" : "Left eye", "eye_r" : "Right eye", "neck" : "Neck", "torso" : "Torso", "arm_l" : "Left arm", "arm_r" : "Right arm", "hand_l" : "Left hand", "hand_r" : "Right hand", "leg_l" : "Left leg", "leg_r" : "Right leg", "foot_l" : "Left foot", "foot_r" : "Right foot"] override func awakeFromNib() { self.sceneView.allowsCameraControl = true self.sceneView.jitteringEnabled = true self.sceneView.backgroundColor = NSColor.blackColor() let url:NSURL = NSBundle.mainBundle().URLForResource("body", withExtension: "dae") self.sceneView.loadSceneAtURL(url) self.sceneView.selectionDelegate = self } func onItemSelected(name: String) { println("name: " + name) let partName = partNames[name] self.selectionLabel.stringValue = "You selected: " + partName! } }
d4b9fd6a2c9ad4f64054d27da3dc085c
28.979592
90
0.584752
false
false
false
false
aichamorro/fitness-tracker
refs/heads/master
Clients/Apple/FitnessTracker/FitnessTracker/Foundation/MVPView.swift
gpl-3.0
1
// // MVPView.swift // FitnessTracker // // Created by Alberto Chamorro - Personal on 07/07/2017. // Copyright © 2017 OnsetBits. All rights reserved. // import UIKit protocol MVPView: class { func dismiss() func push(_ wireframe: UIWireframe, animated: Bool) func presentModally(_ wireframe: UIWireframe, animated: Bool) func presentAsChild(_ wireframe: UIWireframe) } extension MVPView where Self: UIViewController { func push(_ wireframe: UIWireframe, animated: Bool = true) { guard let navigationController = self.navigationController else { fatalError("This controller is not part of a navigation stack") } wireframe.push(in: navigationController, animated: animated) } func presentModally(_ wireframe: UIWireframe, animated: Bool = true) { wireframe.presentModally(in: self, animated: animated) } func presentAsChild(_ wireframe: UIWireframe) { wireframe.presentAsChildController(in: self) } func dismiss() { if let navigationController = self.navigationController { navigationController.popViewController(animated: true) } else if self.presentationController != nil { self.dismiss(animated: true, completion: nil) } else { fatalError("We don't know how to dismiss the view") } } }
698e7cd88127c481c1c96b33b89937ed
30.045455
75
0.672767
false
false
false
false
volodg/iAsync.network
refs/heads/master
Sources/Extensions/NSMutableURLRequest+CreateRequestWithURLParams.swift
mit
1
// // NSMutableURLRequest+CreateRequestWithURLParams.swift // iAsync_network // // Created by Vladimir Gorbenko on 24.09.14. // Copyright © 2014 EmbeddedSources. All rights reserved. // import Foundation import let iAsync_utils.iAsync_utils_logger import enum ReactiveKit.Result //todo NS extension NSMutableURLRequest { convenience init(params: URLConnectionParams) { let inputStream: InputStream? if let factory = params.httpBodyStreamBuilder { let streamResult = factory() if let error = streamResult.error { iAsync_utils_logger.logError("create stream error: \(error)", context: #function) } inputStream = streamResult.value } else { inputStream = nil } assert(!((params.httpBody != nil) && (inputStream != nil))) self.init( url : params.url, cachePolicy : .reloadIgnoringLocalCacheData, timeoutInterval: 60.0) self.httpBodyStream = inputStream if params.httpBody != nil { self.httpBody = params.httpBody } self.allHTTPHeaderFields = params.headers self.httpMethod = params.httpMethod.rawValue } }
8f5327df3218dd453a03951d32a7e232
24.755102
97
0.616482
false
false
false
false
mmertsock/TouchGradientPicker
refs/heads/master
TouchGradientPicker/TouchGradientPicker.swift
mit
1
// // TouchGradientPicker.swift // TouchGradientPicker // // Created by Mike Mertsock on 8/19/15. // Copyright (c) 2015 Esker Apps. All rights reserved. // import UIKit public class TouchGradientPicker: UIView { @IBOutlet public var gradientView: GradientView! public var gradientBuilder: GradientBuilder? private var panStartValue: GradientType? public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUpGestureRecognizers() } public override init(frame: CGRect) { super.init(frame: frame) setUpGestureRecognizers() } private func setUpGestureRecognizers() { let recognizer = UIPanGestureRecognizer(target: self, action: "didPan:") addGestureRecognizer(recognizer) } func didPan(sender: UIPanGestureRecognizer!) { switch (sender.state) { case .Began: panStartValue = gradientView.gradient case .Changed: if let pan = panFromGesture(sender), newGradient = gradientBuilder?.gradientFromPan(pan, panStartValue: panStartValue ?? gradientView.gradient) { gradientView.gradient = newGradient } case .Ended: panStartValue = nil default: break } } func panFromGesture(gesture: UIPanGestureRecognizer) -> Pan? { let viewTx = gesture.translationInView(self) // normalize both directions to [-1, 1] let panBounds = bounds if panBounds.width < 1 || panBounds.height < 1 { return nil } let normalized = CGPointMake(viewTx.x / panBounds.width, viewTx.y / panBounds.height) return Pan(horizontal: normalized.x, vertical: normalized.y) } }
69af83402df26bf5c64d245dd8ed2d00
28.370968
124
0.621636
false
false
false
false
infinitetoken/Arcade
refs/heads/main
Sources/Models/Sort.swift
mit
1
// // Sort.swift // Arcade // // Created by A.C. Wright Design on 2/1/18. // Copyright © 2018 A.C. Wright Design. All rights reserved. // import Foundation public struct Sort { public enum Order: Int { case ascending = 1 case descending = -1 } public var key: String public var order: Order public init(key: String, order: Order) { self.key = key self.order = order } } public extension Sort { var dictionary: [String : Int] { return [self.key : self.order.rawValue] } } public extension Sort { func sortDescriptor() -> NSSortDescriptor { switch self.order { case .ascending: return NSSortDescriptor(key: self.key, ascending: true) case .descending: return NSSortDescriptor(key: self.key, ascending: false) } } } public extension Sort { func sort(viewables: [Viewable]) -> [Viewable] { let dicts = viewables.map { (viewable) -> [String : Any] in return viewable.dictionary } let sorted = zip(dicts, viewables).sorted { (a, b) -> Bool in switch self.sortDescriptor().compare(a.0, to: b.0) { case .orderedAscending: return true case .orderedDescending: return false case .orderedSame: return true } } return sorted.map { $0.1 } } }
e7868a4902032120419870e5a79247b3
20.542857
69
0.537135
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-struct-1argument-1distinct_use.swift
apache-2.0
3
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main9NamespaceV5ValueOySS_SiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main9NamespaceV5ValueOySS_SiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 513, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceV5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] struct Namespace<Arg> { enum Value<First> { case first(First) } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}}, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main9NamespaceV5ValueOySS_SiGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) // CHECK-SAME: ) // CHECK: } func doit() { consume( Namespace<String>.Value.first(13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceV5ValueOMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8* // CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]] // CHECK: [[TYPE_COMPARISON_1]]: // CHECK: [[EQUAL_TYPE_1_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSSN" to i8*), [[ERASED_TYPE_1]] // CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]] // CHECK: [[EQUAL_TYPE_1_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]] // CHECK: [[EQUAL_TYPES_1_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_1]], [[EQUAL_TYPE_1_2]] // CHECK: br i1 [[EQUAL_TYPES_1_2]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]] // CHECK: [[EXIT_PRESPECIALIZED_1]]: // CHECK: ret %swift.metadata_response { // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main9NamespaceV5ValueOySS_SiGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: [[INT]] 0 // CHECK-SAME: } // CHECK: [[EXIT_NORMAL]]: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( // CHECK-SAME: [[INT]] %0, // CHECK-SAME: i8* [[ERASED_TYPE_1]], // CHECK-SAME: i8* [[ERASED_TYPE_2]], // CHECK-SAME: i8* undef, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceV5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
b770a6f697bb3d844c6878f7d0ae613f
40.169811
157
0.574473
false
false
false
false
TwoRingSoft/shared-utils
refs/heads/master
Sources/PippinLibrary/UIKit/UIAlertController/UIAlertControllerFactory.swift
mit
1
// // UIAlertControllerFactory.swift // Pippin // // Created by Andrew McKnight on 10/25/16. // Copyright © 2016 andrew mcknight. All rights reserved. // import UIKit @objc public extension UIViewController { func confirmDestructiveAction(actionName: String, message: String, cancelLabel: String, actionBlock: @escaping (() -> ())) { showConfirmationAlert(withTitle: "Confirm \(actionName)", message: message, confirmTitle: "Yes, \(actionName)", cancelTitle: cancelLabel, style: .actionSheet, completion: { confirmed in if confirmed { actionBlock() } }) } func showAlert(withTitle title: String? = nil, message: String? = nil, confirmTitle: String = "OK", completion: (() -> ())? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: confirmTitle, style: .destructive, handler: { action in completion?() })) present(alert, animated: true, completion: nil) } func showConfirmationAlert(withTitle title: String? = nil, message: String? = nil, confirmTitle: String = "OK", cancelTitle: String = "Cancel", style: UIAlertController.Style = .alert, completion: ((Bool) -> Void)? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: style) alert.addAction(UIAlertAction(title: confirmTitle, style: .default, handler: { action in completion?(true) })) alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: { action in completion?(false) })) present(alert, animated: true, completion: nil) } }
2db08a31ee718c026fed88cc002bdf74
42.2
227
0.651042
false
false
false
false
zixun/GodEye
refs/heads/master
GodEye/Classes/Main/Controller/Sub/ConsolePrintViewController.swift
mit
1
// // ConsolePrintViewController.swift // Pods // // Created by zixun on 16/12/28. // // import Foundation import ESPullToRefresh class ConsolePrintViewController: UIViewController { private var type:RecordType! init(type:RecordType) { super.init(nibName: nil, bundle: nil) self.hidesBottomBarWhenPushed = true self.type = type self.dataSource = RecordTableViewDataSource(type: type) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false self.edgesForExtendedLayout = [] self.navigationController?.navigationBar.barStyle = .black self.view.backgroundColor = UIColor.niceBlack() self.navigationItem.rightBarButtonItems = [UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(ConsolePrintViewController.handleDeleteButtonTap)),UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(ConsolePrintViewController.handleSharedButtonTap))] self.view.addSubview(self.recordTableView) self.view.addSubview(self.inputField) self.recordTableView.es.addPullToRefresh { [weak self] in guard let sself = self else { return } let result = sself.dataSource.loadPrePage() if result == true { sself.recordTableView.reloadData() } sself.recordTableView.es.stopPullToRefresh() } NotificationCenter.default.addObserver(self, selector: #selector(ConsolePrintViewController.keyboardWillShow(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ConsolePrintViewController.keyboardWillHide(noti:)), name: UIResponder.keyboardWillHideNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() var rect = self.view.bounds if self.type == .command { let height: CGFloat = 28.0 var rect = self.view.bounds rect.origin.x = 5 rect.origin.y = rect.size.height - height - 5 rect.size.width -= rect.origin.x * 2 rect.size.height = height self.inputField.frame = rect self.recordTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.inputField.frame.minY) }else { self.recordTableView.frame = rect self.inputField.frame = CGRect.zero } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isNavigationBarHidden = false self.recordTableView.smoothReloadData(need: false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.recordTableView.scrollToBottom(animated: false) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.isNavigationBarHidden = true } func addRecord(model:RecordORMProtocol) { self.dataSource.addRecord(model: model) if self.view.superview != nil { self.recordTableView.smoothReloadData(need: false) } } @objc private func handleSharedButtonTap() { let image = self.recordTableView.swContentCapture { [unowned self] (image:UIImage?) in let activity = UIActivityViewController(activityItems: [image], applicationActivities: nil) if let popover = activity.popoverPresentationController { popover.sourceView = self.view popover.permittedArrowDirections = .up } self.present(activity, animated: true, completion: nil) } } @objc private func handleDeleteButtonTap() { self.type.model()?.delete(complete: { [unowned self] (finish:Bool) in self.dataSource.cleanRecord() self.recordTableView.reloadData() }) } private lazy var recordTableView: RecordTableView = { [unowned self] in let new = RecordTableView() new.delegate = self.dataSource new.dataSource = self.dataSource return new }() private lazy var inputField: UITextField = { [unowned self] in let new = UITextField(frame: CGRect.zero) new.borderStyle = .roundedRect new.font = UIFont.courier(with: 12) new.autocapitalizationType = .none new.autocorrectionType = .no new.returnKeyType = .done new.enablesReturnKeyAutomatically = false new.clearButtonMode = .whileEditing new.contentVerticalAlignment = .center new.placeholder = "Enter command..." new.autoresizingMask = [.flexibleTopMargin, .flexibleWidth] new.delegate = self return new }() private var dataSource: RecordTableViewDataSource! fileprivate var originRect: CGRect = CGRect.zero } extension ConsolePrintViewController: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { guard let text = textField.text else { return } guard text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) != "" else { return } GodEyeController.shared .configuration .command .execute(command: text) { [unowned self] (model:CommandRecordModel) in model.insert(complete: { (true:Bool) in self.addRecord(model: model) }) } textField.text = "" } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldShouldClear(_ textField: UITextField) -> Bool { return true } @objc fileprivate func keyboardWillShow(noti:NSNotification) { guard let userInfo = noti.userInfo else { return } guard let frame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } guard let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else { return } guard let curve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UIView.AnimationCurve.RawValue else { return } UIView.beginAnimations(nil, context: nil) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationDuration(duration) UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: curve)!) var bounds = self.view.frame self.originRect = bounds switch UIApplication.shared.statusBarOrientation { case .portraitUpsideDown: bounds.origin.y += frame.size.height bounds.size.height -= frame.size.height case .landscapeLeft: bounds.size.width -= frame.size.width case .landscapeRight: bounds.origin.x += frame.size.width bounds.size.width -= frame.size.width default: bounds.size.height -= frame.size.height } self.view.frame = bounds UIView.commitAnimations() } @objc fileprivate func keyboardWillHide(noti:NSNotification) { guard let userInfo = noti.userInfo else { return } guard let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else { return } guard let curve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UIView.AnimationCurve.RawValue else { return } UIView.beginAnimations(nil, context: nil) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationDuration(duration) UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: curve)!) self.view.frame = self.originRect UIView.commitAnimations() } }
93c624b8e9040d5df91a2fb5ed5386fb
34.847328
181
0.591354
false
false
false
false