repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
macemmi/HBCI4Swift | HBCI4Swift/HBCI4Swift/Source/Syntax/HBCISyntax.swift | 1 | 9803 | //
// HBCISyntax.swift
// HBCIBackend
//
// Created by Frank Emminghaus on 18.12.14.
// Copyright (c) 2014 Frank Emminghaus. All rights reserved.
//
import Foundation
enum HBCIChar: CChar {
case plus = 0x2B
case dpoint = 0x3A
case qmark = 0x3F
case quote = 0x27
case amper = 0x40
}
let HBCIChar_plus:CChar = 0x2B
let HBCIChar_dpoint:CChar = 0x3A
let HBCIChar_qmark:CChar = 0x3F
let HBCIChar_quote:CChar = 0x27
let HBCIChar_amper:CChar = 0x40
var syntaxVersions = Dictionary<String,HBCISyntax>();
extension XMLElement {
func valueForAttribute(_ name: String)->String? {
let attrNode = self.attribute(forName: name)
if attrNode != nil {
return attrNode!.stringValue
}
return nil
}
}
class HBCISyntax {
var document: XMLDocument! // todo: change to let once Xcode bug is fixed
var degs: Dictionary<String, HBCIDataElementGroupDescription> = [:]
var segs: Dictionary<String, HBCISegmentVersions> = [:]
var codes: Dictionary<String, HBCISegmentVersions> = [:]
var msgs: Dictionary<String, HBCISyntaxElementDescription> = [:]
init(path: String) throws {
var xmlDoc: XMLDocument?
let furl = URL(fileURLWithPath: path);
do {
xmlDoc = try XMLDocument(contentsOf: furl, options:XMLNode.Options(rawValue: XMLNode.Options.RawValue(Int(XMLNode.Options.nodePreserveWhitespace.rawValue|XMLNode.Options.nodePreserveCDATA.rawValue))));
if xmlDoc == nil {
xmlDoc = try XMLDocument(contentsOf: furl, options: XMLNode.Options(rawValue: XMLNode.Options.RawValue(Int(XMLDocument.Options.documentTidyXML.rawValue))));
}
}
catch let err as NSError {
logInfo("HBCI Syntax file error: \(err.localizedDescription)");
logInfo("HBCI syntax file issue at path \(path)");
throw HBCIError.syntaxFileError;
}
if xmlDoc == nil {
logInfo("HBCI syntax file not found (xmlDoc=nil) at path \(path)");
throw HBCIError.syntaxFileError;
} else {
document = xmlDoc!;
}
try buildDegs();
try buildSegs();
try buildMsgs();
}
func buildDegs() throws {
if let root = document.rootElement() {
if let degs = root.elements(forName: "DEGs").first {
for deg in degs.elements(forName: "DEGdef") {
if let identifier = deg.valueForAttribute("id") {
let elem = try HBCIDataElementGroupDescription(syntax: self, element: deg);
elem.syntaxElement = deg;
self.degs[identifier] = elem;
} else {
// syntax error
logInfo("Syntax file error: invalid DEGdef element found");
throw HBCIError.syntaxFileError;
}
}
return;
} else {
// error
logInfo("Syntax file error: DEGs element not found");
throw HBCIError.syntaxFileError;
}
} else {
// error
logInfo("Synax file error: root element not found");
throw HBCIError.syntaxFileError;
}
}
func buildSegs() throws {
if let root = document.rootElement() {
if let segs = root.elements(forName: "SEGs").first {
for seg in segs.elements(forName: "SEGdef") {
let segv = try HBCISegmentVersions(syntax: self, element: seg);
self.segs[segv.identifier] = segv;
self.codes[segv.code] = segv;
}
return;
} else {
// error
logInfo("Syntax file error: SEGs element not found");
throw HBCIError.syntaxFileError;
}
} else {
// error
logInfo("Synax file error: root element not found");
throw HBCIError.syntaxFileError;
}
}
func buildMsgs() throws {
if let root = document.rootElement() {
if let msgs = root.elements(forName: "MSGs").first {
for msg in msgs.elements(forName: "MSGdef") {
if let identifier = msg.valueForAttribute("id") {
let elem = try HBCIMessageDescription(syntax: self, element: msg);
elem.syntaxElement = msg;
self.msgs[identifier] = elem;
}
}
return;
} else {
// error
logInfo("Syntax file error: MSGs element not found");
throw HBCIError.syntaxFileError;
}
} else {
// error
logInfo("Synax file error: root element not found");
throw HBCIError.syntaxFileError;
}
}
func parseSegment(_ segData:Data, binaries:Array<Data>) throws ->HBCISegment? {
if let headerDescr = self.degs["SegHead"] {
if let headerData = headerDescr.parse((segData as NSData).bytes.bindMemory(to: CChar.self, capacity: segData.count), length: segData.count, binaries: binaries) {
if let code = headerData.elementValueForPath("code") as? String {
if let version = headerData.elementValueForPath("version") as? Int {
if let segVersion = self.codes[code] {
if let segDescr = segVersion.segmentWithVersion(version) {
if let seg = segDescr.parse(segData, binaries: binaries) {
return seg;
} else {
throw HBCIError.parseError;
}
}
}
//logDebug("Segment code \(code) with version \(version) is not supported");
return nil; // code and/or version are not supported, just continue
}
}
}
logInfo("Parse error: segment code or segment version could not be determined");
throw HBCIError.parseError;
} else {
logInfo("Syntax file error: segment SegHead is missing");
throw HBCIError.syntaxFileError;
}
}
func customMessageForSegment(_ segName:String, user:HBCIUser) ->HBCIMessage? {
if let md = self.msgs["CustomMsg"] {
if let msg = md.compose() as? HBCIMessage {
if let segVersions = self.segs[segName] {
// now find the right segment version
// check which segment versions are supported by the bank
var supportedVersions = Array<Int>();
for seg in user.parameters.bpSegments {
if seg.name == segName {
// check if this version is also supported by us
if segVersions.isVersionSupported(seg.version) {
supportedVersions.append(seg.version);
}
}
}
if supportedVersions.count == 0 {
// this process is not supported by the bank
logInfo("Process \(segName) is not supported for custom message");
// In some cases the bank does not send any Parameter but the process is still supported
// let's just try it out
supportedVersions = segVersions.versionNumbers;
}
// now sort the versions - we take the latest supported version
supportedVersions.sort(by: >);
if let sd = segVersions.segmentWithVersion(supportedVersions.first!) {
if let segment = sd.compose() {
segment.name = segName;
msg.children.insert(segment, at: 2);
return msg;
}
}
} else {
logInfo("Segment \(segName) is not supported by HBCI4Swift");
}
}
}
return nil;
}
func addExtension(_ extSyntax:HBCISyntax) {
for key in extSyntax.degs.keys {
if !degs.keys.contains(key) {
degs[key] = extSyntax.degs[key];
}
}
for key in extSyntax.segs.keys {
if !segs.keys.contains(key) {
if let segv = extSyntax.segs[key] {
segs[key] = segv;
codes[segv.code] = segv;
}
}
}
}
class func syntaxWithVersion(_ version:String) throws ->HBCISyntax {
if !["220", "300"].contains(version) {
throw HBCIError.invalidHBCIVersion(version);
}
if let syntax = syntaxVersions[version] {
return syntax;
} else {
// load syntax
var path = Bundle.main.bundlePath;
path = path + "/Contents/Frameworks/HBCI4Swift.framework/Resources/hbci\(version).xml";
let syntax = try HBCISyntax(path: path);
if let extSyntax = HBCISyntaxExtension.instance.extensions[version] {
syntax.addExtension(extSyntax);
}
syntaxVersions[version] = syntax;
return syntax;
}
}
}
| gpl-2.0 | 38dbd682b20cab3291f84b6dbcd822a4 | 38.212 | 213 | 0.51168 | 5.15134 | false | false | false | false |
DiegoSan1895/Smartisan-Notes | Smartisan-Notes/Constants.swift | 1 | 2360 |
//
// Configs.swift
// Smartisan-Notes
//
// Created by DiegoSan on 3/4/16.
// Copyright © 2016 DiegoSan. All rights reserved.
//
import UIKit
let isNotFirstOpenSmartisanNotes = "isNotFirstOpenSmartisanNotes"
let ueAgreeOrNot = "userAgreeToJoinUEPlan"
let NSBundleURL = NSBundle.mainBundle().bundleURL
struct AppID {
static let notesID = 867934588
static let clockID = 828812911
static let syncID = 880078620
static let calenderID = 944154964
}
struct AppURL {
static let clockURL = NSURL(string: "smartisanclock://")!
static let syncURL = NSURL(string: "smartisansync://")!
static let calenderURL = NSURL(string: "smartisancalendar://")!
static let smartisanWeb = NSURL(string: "https://store.smartisan.com")!
}
struct AppItunsURL {
let baseURLString = "http://itunes.apple.com/us/app/id"
static let calenderURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.calenderID)")!
static let syncURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.syncID)")!
static let clockURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.clockID)")!
static let notesURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.notesID)")!
}
struct AppShareURL {
static let notesURL = NSURL(string: "https://itunes.apple.com/us/app/smartisan-notes/id867934588?ls=1&mt=8")!
}
struct iPhoneInfo{
static let iOS_Version = UIDevice.currentDevice().systemVersion
static let deviceName = NSString.deviceName() as String
}
struct AppInfo{
static let App_Version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
}
struct Configs {
struct Weibo {
static let appID = "1682079354"
static let appKey = "94c42dacce2401ad73e5080ccd743052"
static let redirectURL = "http://www.limon.top"
}
struct Wechat {
static let appID = "wx4868b35061f87885"
static let appKey = "64020361b8ec4c99936c0e3999a9f249"
}
struct QQ {
static let appID = "1104881792"
}
struct Pocket {
static let appID = "48363-344532f670a052acff492a25"
static let redirectURL = "pocketapp48363:authorizationFinished" // pocketapp + $prefix + :authorizationFinished
}
struct Alipay {
static let appID = "2016012101112529"
}
} | mit | 106a1f612919be5defa706c60098cd68 | 29.25641 | 119 | 0.690971 | 3.558069 | false | false | false | false |
iOS-mamu/SS | P/Pods/PSOperations/PSOperations/OperationQueue.swift | 1 | 5612 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file contains an NSOperationQueue subclass.
*/
import Foundation
/**
The delegate of an `OperationQueue` can respond to `Operation` lifecycle
events by implementing these methods.
In general, implementing `OperationQueueDelegate` is not necessary; you would
want to use an `OperationObserver` instead. However, there are a couple of
situations where using `OperationQueueDelegate` can lead to simpler code.
For example, `GroupOperation` is the delegate of its own internal
`OperationQueue` and uses it to manage dependencies.
*/
@objc public protocol OperationQueueDelegate: NSObjectProtocol {
@objc optional func operationQueue(_ operationQueue: OperationQueue, willAddOperation operation: Foundation.Operation)
@objc optional func operationQueue(_ operationQueue: OperationQueue, operationDidFinish operation: Foundation.Operation, withErrors errors: [NSError])
}
/**
`OperationQueue` is an `NSOperationQueue` subclass that implements a large
number of "extra features" related to the `Operation` class:
- Notifying a delegate of all operation completion
- Extracting generated dependencies from operation conditions
- Setting up dependencies to enforce mutual exclusivity
*/
open class OperationQueue: Foundation.OperationQueue {
open weak var delegate: OperationQueueDelegate?
override open func addOperation(_ operation: Foundation.Operation) {
if let op = operation as? Operation {
// Set up a `BlockObserver` to invoke the `OperationQueueDelegate` method.
let delegate = BlockObserver(
startHandler: nil,
produceHandler: { [weak self] in
self?.addOperation($1)
},
finishHandler: { [weak self] finishedOperation, errors in
if let q = self {
q.delegate?.operationQueue?(q, operationDidFinish: finishedOperation, withErrors: errors)
//Remove deps to avoid cascading deallocation error
//http://stackoverflow.com/questions/19693079/nsoperationqueue-bug-with-dependencies
finishedOperation.dependencies.forEach { finishedOperation.removeDependency($0) }
}
}
)
op.addObserver(delegate)
// Extract any dependencies needed by this operation.
let dependencies = op.conditions.flatMap {
$0.dependencyForOperation(op)
}
for dependency in dependencies {
op.addDependency(dependency)
self.addOperation(dependency)
}
/*
With condition dependencies added, we can now see if this needs
dependencies to enforce mutual exclusivity.
*/
let concurrencyCategories: [String] = op.conditions.flatMap { condition in
if !type(of: condition).isMutuallyExclusive { return nil }
return "\(type(of: condition))"
}
if !concurrencyCategories.isEmpty {
// Set up the mutual exclusivity dependencies.
let exclusivityController = ExclusivityController.sharedExclusivityController
exclusivityController.addOperation(op, categories: concurrencyCategories)
op.addObserver(BlockObserver { operation, _ in
exclusivityController.removeOperation(operation, categories: concurrencyCategories)
})
}
}
else {
/*
For regular `NSOperation`s, we'll manually call out to the queue's
delegate we don't want to just capture "operation" because that
would lead to the operation strongly referencing itself and that's
the pure definition of a memory leak.
*/
operation.addCompletionBlock { [weak self, weak operation] in
guard let queue = self, let operation = operation else { return }
queue.delegate?.operationQueue?(queue, operationDidFinish: operation, withErrors: [])
//Remove deps to avoid cascading deallocation error
//http://stackoverflow.com/questions/19693079/nsoperationqueue-bug-with-dependencies
operation.dependencies.forEach { operation.removeDependency($0) }
}
}
delegate?.operationQueue?(self, willAddOperation: operation)
super.addOperation(operation)
/*
Indicate to the operation that we've finished our extra work on it
and it's now it a state where it can proceed with evaluating conditions,
if appropriate.
*/
if let op = operation as? Operation {
op.didEnqueue()
}
}
override open func addOperations(_ ops: [Foundation.Operation], waitUntilFinished wait: Bool) {
/*
The base implementation of this method does not call `addOperation()`,
so we'll call it ourselves.
*/
for operation in ops {
addOperation(operation)
}
if wait {
for operation in ops {
operation.waitUntilFinished()
}
}
}
}
| mit | 682421a42ffd0b5e10edf1e3fab010a0 | 40.865672 | 154 | 0.611765 | 5.886674 | false | false | false | false |
ipmobiletech/firefox-ios | UITests/ClearPrivateDataTests.swift | 1 | 11507 | /* 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 WebKit
import UIKit
// Needs to be in sync with Client Clearables.
private enum Clearable: String {
case History = "Browsing History"
case Logins = "Saved Logins"
case Cache = "Cache"
case OfflineData = "Offline Website Data"
case Cookies = "Cookies"
}
private let AllClearables = Set([Clearable.History, Clearable.Logins, Clearable.Cache, Clearable.OfflineData, Clearable.Cookies])
class ClearPrivateDataTests: KIFTestCase, UITextFieldDelegate {
private var webRoot: String!
override func setUp() {
webRoot = SimplePageServer.start()
}
override func tearDown() {
BrowserUtils.clearHistoryItems(tester())
}
private func clearPrivateData(clearables: Set<Clearable>) {
let webView = tester().waitForViewWithAccessibilityLabel("Web content") as! WKWebView
let lastTabLabel = webView.title!.isEmpty ? "home" : webView.title!
tester().tapViewWithAccessibilityLabel("Show Tabs")
tester().tapViewWithAccessibilityLabel("Settings")
tester().tapViewWithAccessibilityLabel("Clear Private Data")
// Disable all items that we don't want to clear.
for clearable in AllClearables.subtract(clearables) {
// If we don't wait here, setOn:forSwitchWithAccessibilityLabel tries to use the UITableViewCell
// instead of the UISwitch. KIF bug?
tester().waitForViewWithAccessibilityLabel(clearable.rawValue)
tester().setOn(false, forSwitchWithAccessibilityLabel: clearable.rawValue)
}
tester().tapViewWithAccessibilityLabel("Clear Private Data", traits: UIAccessibilityTraitButton)
tester().tapViewWithAccessibilityLabel("Settings")
tester().tapViewWithAccessibilityLabel("Done")
tester().tapViewWithAccessibilityLabel(lastTabLabel)
}
func visitSites(noOfSites noOfSites: Int) -> [(title: String, domain: String, url: String)] {
var urls: [(title: String, domain: String, url: String)] = []
for pageNo in 1...noOfSites {
tester().tapViewWithAccessibilityIdentifier("url")
let url = "\(webRoot)/numberedPage.html?page=\(pageNo)"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page \(pageNo)")
let tuple: (title: String, domain: String, url: String) = ("Page \(pageNo)", NSURL(string: url)!.normalizedHost()!, url)
urls.append(tuple)
}
BrowserUtils.resetToAboutHome(tester())
return urls
}
func anyDomainsExistOnTopSites(domains: Set<String>) {
for domain in domains {
if self.tester().viewExistsWithLabel(domain) {
return
}
}
XCTFail("Couldn't find any domains in top sites.")
}
func testClearsTopSitesPanel() {
let urls = visitSites(noOfSites: 2)
let domains = Set<String>(urls.map { $0.domain })
tester().tapViewWithAccessibilityLabel("Top sites")
// Only one will be found -- we collapse by domain.
anyDomainsExistOnTopSites(domains)
clearPrivateData([Clearable.History])
XCTAssertFalse(tester().viewExistsWithLabel(urls[0].title), "Expected to have removed top site panel \(urls[0])")
XCTAssertFalse(tester().viewExistsWithLabel(urls[1].title), "We shouldn't find the other URL, either.")
}
func testDisabledHistoryDoesNotClearTopSitesPanel() {
let urls = visitSites(noOfSites: 2)
let domains = Set<String>(urls.map { $0.domain })
anyDomainsExistOnTopSites(domains)
clearPrivateData(AllClearables.subtract([Clearable.History]))
anyDomainsExistOnTopSites(domains)
}
func testClearsHistoryPanel() {
let urls = visitSites(noOfSites: 2)
tester().tapViewWithAccessibilityLabel("History")
let url1 = "\(urls[0].title), \(urls[0].url)"
let url2 = "\(urls[1].title), \(urls[1].url)"
XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to have history row \(url1)")
XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to have history row \(url2)")
clearPrivateData([Clearable.History])
tester().tapViewWithAccessibilityLabel("History")
XCTAssertFalse(tester().viewExistsWithLabel(url1), "Expected to have removed history row \(url1)")
XCTAssertFalse(tester().viewExistsWithLabel(url2), "Expected to have removed history row \(url2)")
}
func testDisabledHistoryDoesNotClearHistoryPanel() {
let urls = visitSites(noOfSites: 2)
tester().tapViewWithAccessibilityLabel("History")
let url1 = "\(urls[0].title), \(urls[0].url)"
let url2 = "\(urls[1].title), \(urls[1].url)"
XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to have history row \(url1)")
XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to have history row \(url2)")
clearPrivateData(AllClearables.subtract([Clearable.History]))
XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to not have removed history row \(url1)")
XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to not have removed history row \(url2)")
}
func testClearsCookies() {
tester().tapViewWithAccessibilityIdentifier("url")
let url = "\(webRoot)/numberedPage.html?page=1"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
let webView = tester().waitForViewWithAccessibilityLabel("Web content") as! WKWebView
// Set and verify a dummy cookie value.
setCookies(webView, cookie: "foo=bar")
var cookies = getCookies(webView)
XCTAssertEqual(cookies.cookie, "foo=bar")
XCTAssertEqual(cookies.localStorage, "foo=bar")
XCTAssertEqual(cookies.sessionStorage, "foo=bar")
// Verify that cookies are not cleared when Cookies is deselected.
clearPrivateData(AllClearables.subtract([Clearable.Cookies]))
cookies = getCookies(webView)
XCTAssertEqual(cookies.cookie, "foo=bar")
XCTAssertEqual(cookies.localStorage, "foo=bar")
XCTAssertEqual(cookies.sessionStorage, "foo=bar")
// Verify that cookies are cleared when Cookies is selected.
clearPrivateData([Clearable.Cookies])
cookies = getCookies(webView)
XCTAssertEqual(cookies.cookie, "")
XCTAssertNil(cookies.localStorage)
XCTAssertNil(cookies.sessionStorage)
}
@available(iOS 9.0, *)
func testClearsCache() {
let cachedServer = CachedPageServer()
let cacheRoot = cachedServer.start()
let url = "\(cacheRoot)/cachedPage.html"
tester().tapViewWithAccessibilityIdentifier("url")
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Cache test")
let webView = tester().waitForViewWithAccessibilityLabel("Web content") as! WKWebView
let requests = cachedServer.requests
// Verify that clearing non-cache items will keep the page in the cache.
clearPrivateData(AllClearables.subtract([Clearable.Cache]))
webView.reload()
XCTAssertEqual(cachedServer.requests, requests)
// Verify that clearing the cache will fire a new request.
clearPrivateData([Clearable.Cache])
webView.reload()
XCTAssertEqual(cachedServer.requests, requests + 1)
}
func testClearsLogins() {
tester().tapViewWithAccessibilityIdentifier("url")
let url = "\(webRoot)/loginForm.html"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Submit")
// The form should be empty when we first load it.
XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("foo"))
XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("bar"))
// Fill it in and submit.
tester().enterText("foo", intoWebViewInputWithName: "username")
tester().enterText("bar", intoWebViewInputWithName: "password")
tester().tapWebViewElementWithAccessibilityLabel("Submit")
// Say "Yes" to the remember password prompt.
tester().tapViewWithAccessibilityLabel("Yes")
// Verify that the form is autofilled after reloading.
tester().tapViewWithAccessibilityLabel("Reload")
XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("foo"))
XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("bar"))
// Ensure that clearing other data has no effect on the saved logins.
clearPrivateData(AllClearables.subtract([Clearable.Logins]))
tester().tapViewWithAccessibilityLabel("Reload")
XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("foo"))
XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("bar"))
// Ensure that clearing logins clears the form.
clearPrivateData([Clearable.Logins])
tester().tapViewWithAccessibilityLabel("Reload")
XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("foo"))
XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("bar"))
}
private func setCookies(webView: WKWebView, cookie: String) {
let expectation = expectationWithDescription("Set cookie")
webView.evaluateJavaScript("document.cookie = \"\(cookie)\"; localStorage.cookie = \"\(cookie)\"; sessionStorage.cookie = \"\(cookie)\";") { result, _ in
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
private func getCookies(webView: WKWebView) -> (cookie: String, localStorage: String?, sessionStorage: String?) {
var cookie: (String, String?, String?)!
let expectation = expectationWithDescription("Got cookie")
webView.evaluateJavaScript("JSON.stringify([document.cookie, localStorage.cookie, sessionStorage.cookie])") { result, _ in
let cookies = JSON.parse(result as! String).asArray!
cookie = (cookies[0].asString!, cookies[1].asString, cookies[2].asString)
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
return cookie
}
}
/// Server that keeps track of requests.
private class CachedPageServer {
var requests = 0
func start() -> String {
let webServer = GCDWebServer()
webServer.addHandlerForMethod("GET", path: "/cachedPage.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
self.requests++
return GCDWebServerDataResponse(HTML: "<html><head><title>Cached page</title></head><body>Cache test</body></html>")
}
webServer.startWithPort(0, bonjourName: nil)
// We use 127.0.0.1 explicitly here, rather than localhost, in order to avoid our
// history exclusion code (Bug 1188626).
let webRoot = "http://127.0.0.1:\(webServer.port)"
return webRoot
}
}
| mpl-2.0 | d758a510a5bca9eb6eb4248e4768f947 | 43.088123 | 161 | 0.681151 | 5.394749 | false | true | false | false |
kusl/swift | validation-test/compiler_crashers_fixed/1922-getselftypeforcontainer.swift | 13 | 492 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let x {
var b = 1][Any) -> Self {
f(")) {
let i(x) {
}
let v: A, self.A> Any) -> {
func c] = [unowned self] {
return { self.f == A<B : Any) -> : AnyObject, 3] == {
var d {
}
}
}
}
return z: NSObject {
func x: B, range.<T, U) -> () {
})
}
}
protocol b {
func a
typealias d: a {
| apache-2.0 | 36f9fd69b972d4adcb6ac6952800c088 | 17.222222 | 87 | 0.601626 | 2.779661 | false | true | false | false |
kusl/swift | validation-test/compiler_crashers_fixed/0181-swift-parser-parseexprclosure.swift | 12 | 2657 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func f<T : BooleanType>(b: T) {
}
f(true as BooleanType)
class k {
func l((Any, k))(m }
}
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
class func j()
}
class e: k{ class func j
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
func ^(a: BooleanType, Bool) -> Bool {
return !(a)
}
({})
struct A<T> {
let a: [(T, () -> ())] = []
}
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
d ""
e}
class d {
func b((Any, d)typealias b = b
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(m: (Any, Any) -> Any) -> Any in
return m(x, y)
}
}
func b(z: (((Any, Any) -> Any) -> Any)) -> Any {
return z({
(p: Any, q:Any) -> Any in
return p
})
}
b(a(1, a(2, 3)))
protocol a : a {
}
a
}
struct e : f {
i f = g
}
func i<g : g, e : f where e.f == g> (c: e) {
}
func i<h : f where h.f == c> (c: h) {
}
i(e())
class a<f : g, g : g where f.f == g> {
}
protocol g {
typealias f
typealias e
}
struct c<h : g> : g {
typealias f = h
typealias e = a<c<h>, f>
({})
func prefix(with: String) -> <T>(() -> T) -> String { func b
clanType, Bool) -> Bool {
)
}
strs d
typealias b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
func prefi(with: String-> <T>() -> T)t
protocol l : p {
}
protocol m {
j f = p
}
f m : m {
j f = o
}
func i<o : o, m : m n m.f == o> (l: m) {
}
k: m
}
func p<m>() -> [l<m>] {
return []
}
f
m)
func f<o>() -> (o, o -> o) -> o {
m o m.i = {
}
{
o) {
p }
}
protocol f {
class func i()
}
class m: f{ class func i {}
protocol p {
class func l()
}
class o: p {
class func l() { }
struct A<T> {
let a: [(T, () -> ())] = []
}
f
e)
func f<g>() -> (g, g -> g) -> g {
d j d.i 1, a(2, 3)))
class a {
typealias ((t, t) -> t) -> t)) -> t {
return r({
return k
})
() {
g g h g
}
}
func e(i: d) -> <f>(() -> f)>
func m(c: b) -> <h>(() -> h) -> b {
f) -> j) -> > j {
l i !(k)
}
d
l)
func d<m>-> (m, m -
struct c<d, e: b where d.c ==e>
var x1 =I Bool !(a)
}
func prefix(with: Strin) -> <T>(() -> T) in
// Distributed under the terms oclass a {
typealias b = b
func b((Any, e))(e: (Any) -> <d>(()-> d) -> f
func f() {
({})
}
| apache-2.0 | beeded5d52ff69303dfacba30c0b78fc | 14.815476 | 87 | 0.451637 | 2.437615 | false | false | false | false |
cikelengfeng/Jude | Jude/Antlr4/atn/EmptyPredictionContext.swift | 2 | 932 | /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
public class EmptyPredictionContext: SingletonPredictionContext {
public init() {
super.init(nil, PredictionContext.EMPTY_RETURN_STATE)
}
override
public func isEmpty() -> Bool {
return true
}
override
public func size() -> Int {
return 1
}
override
public func getParent(_ index: Int) -> PredictionContext? {
return nil
}
override
public func getReturnState(_ index: Int) -> Int {
return returnState
}
override
public var description: String {
return "$"
}
}
public func ==(lhs: EmptyPredictionContext, rhs: EmptyPredictionContext) -> Bool {
if lhs === rhs {
return true
}
return false
}
| mit | 713fb34766bf8a7b94b175a410adc791 | 19.711111 | 82 | 0.625536 | 4.636816 | false | false | false | false |
STShenZhaoliang/STWeiBo | STWeiBo/STWeiBo/Classes/Home/Status.swift | 1 | 7014 | //
// Status.swift
// STWeiBo
//
// Created by ST on 15/11/17.
// Copyright © 2015年 ST. All rights reserved.
//
import UIKit
import SDWebImage
class Status: NSObject {
/// 微博创建时间
var created_at: String?
{
didSet{
// 1.将字符串转换为时间
let createdDate = NSDate.dateWithStr(created_at!)
// 2.获取格式化之后的时间字符串
created_at = createdDate.descDate
}
}
/// 微博ID
var id: Int = 0
/// 微博信息内容
var text: String?
/// 微博来源
var source: String?
{
didSet{
// 1.截取字符串
if let str = source
{
if str == ""
{
return
}
// 1.1获取开始截取的位置
let startLocation = (str as NSString).rangeOfString(">").location + 1
// 1.2获取截取的长度
let length = (str as NSString).rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - startLocation
// 1.3截取字符串
source = "来自:" + (str as NSString).substringWithRange(NSMakeRange(startLocation, length))
}
}
}
/// 配图数组
var pic_urls: [[String: AnyObject]]?
{
didSet{
// 1.初始化数组
storedPicURLS = [NSURL]()
// 2遍历取出所有的图片路径字符串
storedLargePicURLS = [NSURL]()
for dict in pic_urls!
{
if let urlStr = dict["thumbnail_pic"] as? String
{
// 1.将字符串转换为URL保存到数组中
storedPicURLS!.append(NSURL(string: urlStr)!)
// 2.处理大图
let largeURLStr = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
storedLargePicURLS!.append(NSURL(string: largeURLStr)!)
}
}
}
}
/// 保存当前微博所有配图的URL
var storedPicURLS: [NSURL]?
/// 保存当前微博所有配图"大图"的URL
var storedLargePicURLS: [NSURL]?
/// 用户信息
var user: User?
/// 转发微博
var retweeted_status: Status?
// 如果有转发, 原创就没有配图
/// 定义一个计算属性, 用于返回原创获取转发配图的URL数组
var pictureURLS:[NSURL]?
{
return retweeted_status != nil ? retweeted_status?.storedPicURLS : storedPicURLS
}
/// 定义一个计算属性, 用于返回原创或者转发配图的大图URL数组
var LargePictureURLS:[NSURL]?
{
return retweeted_status != nil ? retweeted_status?.storedLargePicURLS : storedLargePicURLS
}
/// 加载微博数据
class func loadStatuses(since_id: Int, finished: (models:[Status]?, error:NSError?)->()){
let path = "2/statuses/home_timeline.json"
var params = ["access_token": UserAccount.loadAccount()!.access_token!]
print("\(__FUNCTION__) \(self)")
// 下拉刷新
if since_id > 0
{
params["since_id"] = "\(since_id)"
}
NetworkTools.shareNetworkTools().GET(path, parameters: params, success: { (_, JSON) -> Void in
// 1.取出statuses key对应的数组 (存储的都是字典)
// 2.遍历数组, 将字典转换为模型
let models = dict2Model(JSON["statuses"] as! [[String: AnyObject]])
// 3.缓存微博配图
cacheStatusImages(models, finished: finished)
}) { (_, error) -> Void in
print(error)
finished(models: nil, error: error)
}
}
/// 缓存配图
class func cacheStatusImages(list: [Status], finished: (models:[Status]?, error:NSError?)->()) {
if list.count == 0
{
finished(models: list, error: nil)
return
}
// 1.创建一个组
let group = dispatch_group_create()
// 1.缓存图片
for status in list
{
// 1.1判断当前微博是否有配图, 如果没有就直接跳过
// Swift2.0新语法, 如果条件为nil, 那么就会执行else后面的语句
guard let _ = status.pictureURLS else
{
continue
}
for url in status.pictureURLS!
{
// 将当前的下载操作添加到组中
dispatch_group_enter(group)
// 缓存图片
SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
// 离开当前组
dispatch_group_leave(group)
})
}
}
// 2.当所有图片都下载完毕再通过闭包通知调用者
dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
// 能够来到这个地方, 一定是所有图片都下载完毕
finished(models: list, error: nil)
}
}
/// 将字典数组转换为模型数组
class func dict2Model(list: [[String: AnyObject]]) -> [Status] {
var models = [Status]()
for dict in list
{
models.append(Status(dict: dict))
}
return models
}
// 字典转模型
init(dict: [String: AnyObject])
{
super.init()
setValuesForKeysWithDictionary(dict)
}
// setValuesForKeysWithDictionary内部会调用以下方法
override func setValue(value: AnyObject?, forKey key: String) {
// 1.判断当前是否正在给微博字典中的user字典赋值
if "user" == key
{
// 2.根据user key对应的字典创建一个模型
user = User(dict: value as! [String : AnyObject])
return
}
// 2.判断是否是转发微博, 如果是就自己处理
if "retweeted_status" == key
{
retweeted_status = Status(dict: value as! [String : AnyObject])
return
}
// 3,调用父类方法, 按照系统默认处理
super.setValue(value, forKey: key)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
// 打印当前模型
var properties = ["created_at", "id", "text", "source", "pic_urls"]
override var description: String {
let dict = dictionaryWithValuesForKeys(properties)
return "\(dict)"
}
}
| mit | b837a2787487b911d771b812dd48e8e5 | 27.282407 | 171 | 0.492225 | 4.56577 | false | false | false | false |
CJGitH/QQMusic | QQMusic/Classes/Other/Tool/QQImageTool.swift | 1 | 1274 | //
// QQImageTool.swift
// QQMusic
//
// Created by chen on 16/5/18.
// Copyright © 2016年 chen. All rights reserved.
//
import UIKit
class QQImageTool: NSObject {
class func getNewImage(sourceImage: UIImage, str: String) -> UIImage {
let size = sourceImage.size
// 1. 开启图形上下文
UIGraphicsBeginImageContext(size)
// 2. 绘制大的图片
sourceImage.drawInRect(CGRectMake(0, 0, size.width, size.height))
// 3. 绘制文字
let style: NSMutableParagraphStyle = NSMutableParagraphStyle()
style.alignment = .Center
let dic: [String : AnyObject] = [
NSForegroundColorAttributeName: UIColor.whiteColor(),
NSParagraphStyleAttributeName: style,
NSFontAttributeName: UIFont.systemFontOfSize(20)
]
(str as NSString).drawInRect(CGRectMake(0, 0, size.width, 26), withAttributes: dic)
// 4. 获取结果图片
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
// 5. 关闭上下文
UIGraphicsEndImageContext()
// 6. 返回结果
return resultImage
}
} | mit | 70edb61e14c0401fde77bd3180962056 | 23.653061 | 91 | 0.570837 | 5.15812 | false | false | false | false |
lcddhr/BSImagePicker | Pod/Classes/Model/AssetsModel.swift | 2 | 5403 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import Photos
final class AssetsModel<T: AnyEquatableObject> : Selectable {
var delegate: AssetsDelegate?
subscript (idx: Int) -> PHFetchResult {
return _results[idx]
}
var count: Int {
return _results.count
}
private var _selections = [T]()
private var _results: [PHFetchResult]
required init(fetchResult aFetchResult: [PHFetchResult]) {
_results = aFetchResult
}
// MARK: PHPhotoLibraryChangeObserver
func photoLibraryDidChange(changeInstance: PHChange!) {
for (index, fetchResult) in enumerate(_results) {
// Check if there are changes to our fetch result
if let collectionChanges = changeInstance.changeDetailsForFetchResult(fetchResult) {
// Get the new fetch result
let newResult = collectionChanges.fetchResultAfterChanges as PHFetchResult
// Replace old result
_results[index] = newResult
// Sometimes the properties on PHFetchResultChangeDetail are nil
// Work around it for now
let incrementalChange = collectionChanges.hasIncrementalChanges && collectionChanges.removedIndexes != nil && collectionChanges.insertedIndexes != nil && collectionChanges.changedIndexes != nil
let removedIndexPaths: [NSIndexPath]
let insertedIndexPaths: [NSIndexPath]
let changedIndexPaths: [NSIndexPath]
if incrementalChange {
// Incremental change, tell delegate what has been deleted, inserted and changed
removedIndexPaths = indexPathsFromIndexSet(collectionChanges.removedIndexes, inSection: index)
insertedIndexPaths = indexPathsFromIndexSet(collectionChanges.insertedIndexes, inSection: index)
changedIndexPaths = indexPathsFromIndexSet(collectionChanges.changedIndexes, inSection: index)
} else {
// No incremental change. Set empty arrays
removedIndexPaths = []
insertedIndexPaths = []
changedIndexPaths = []
}
// Notify delegate
delegate?.didUpdateAssets(self, incrementalChange: incrementalChange, insert: insertedIndexPaths, delete: removedIndexPaths, change: changedIndexPaths)
}
}
}
private func indexPathsFromIndexSet(indexSet: NSIndexSet, inSection section: Int) -> [NSIndexPath] {
var indexPaths: [NSIndexPath] = []
indexSet.enumerateIndexesUsingBlock { (index, _) -> Void in
indexPaths.append(NSIndexPath(forItem: index, inSection: section))
}
return indexPaths
}
// MARK: Selectable
func selectObjectAtIndexPath(indexPath: NSIndexPath) {
if let object = _results[indexPath.section][indexPath.row] as? T where contains(_selections, object) == false {
_selections.append(object)
}
}
func deselectObjectAtIndexPath(indexPath: NSIndexPath) {
if let object = _results[indexPath.section][indexPath.row] as? T, let index = find(_selections, object) {
_selections.removeAtIndex(index)
}
}
func selectionCount() -> Int {
return _selections.count
}
func selectedIndexPaths() -> [NSIndexPath] {
var indexPaths: [NSIndexPath] = []
for object in _selections {
for (resultIndex, fetchResult) in enumerate(_results) {
let index = fetchResult.indexOfObject(object)
if index != NSNotFound {
let indexPath = NSIndexPath(forItem: index, inSection: resultIndex)
indexPaths.append(indexPath)
}
}
}
return indexPaths
}
func selections() -> [T] {
return _selections
}
func setSelections(newSelections: [T]) {
_selections = newSelections
}
func removeSelections() {
_selections.removeAll(keepCapacity: true)
}
}
| mit | 8fc6ea2a9b031101ab916031b2e5cef1 | 39.616541 | 209 | 0.631618 | 5.615385 | false | false | false | false |
MobileFirstInc/MFCard | MFCard/Card /Toast/Toast.swift | 1 | 31043 | //
// Toast.swift
// Toast-Swift
//
// Copyright (c) 2015 Charles Scalesse.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
import ObjectiveC
public enum ToastPosition {
case top
case center
case bottom
}
/**
Toast is a Swift extension that adds toast notifications to the `UIView` object class.
It is intended to be simple, lightweight, and easy to use. Most toast notifications
can be triggered with a single line of code.
The `makeToast` methods create a new view and then display it as toast.
The `showToast` methods display any view as toast.
*/
public extension UIView {
/**
Keys used for associated objects.
*/
private struct ToastKeys {
static var Timer = "CSToastTimerKey"
static var Duration = "CSToastDurationKey"
static var Position = "CSToastPositionKey"
static var Completion = "CSToastCompletionKey"
static var ActiveToast = "CSToastActiveToastKey"
static var ActivityView = "CSToastActivityViewKey"
static var Queue = "CSToastQueueKey"
}
/**
Swift closures can't be directly associated with objects via the
Objective-C runtime, so the (ugly) solution is to wrap them in a
class that can be used with associated objects.
*/
private class ToastCompletionWrapper {
var completion: ((Bool) -> Void)?
init(_ completion: ((Bool) -> Void)?) {
self.completion = completion
}
}
private enum ToastError: Error {
case insufficientData
}
private var queue: NSMutableArray {
get {
if let queue = objc_getAssociatedObject(self, &ToastKeys.Queue) as? NSMutableArray {
return queue
} else {
let queue = NSMutableArray()
objc_setAssociatedObject(self, &ToastKeys.Queue, queue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return queue
}
}
}
// MARK: - Make Toast Methods
/**
Creates and presents a new toast view with a message and displays it with the
default duration and position. Styled using the shared style.
@param message The message to be displayed
*/
func makeToast(_ message: String) {
self.makeToast(message, duration: ToastManager.shared.duration, position: ToastManager.shared.position)
}
/**
Creates and presents a new toast view with a message. Duration and position
can be set explicitly. Styled using the shared style.
@param message The message to be displayed
@param duration The toast duration
@param position The toast's position
*/
func makeToast(_ message: String, duration: TimeInterval, position: ToastPosition) {
self.makeToast(message, duration: duration, position: position, style: nil)
}
/**
Creates and presents a new toast view with a message. Duration and position
can be set explicitly. Styled using the shared style.
@param message The message to be displayed
@param duration The toast duration
@param position The toast's center point
*/
func makeToast(_ message: String, duration: TimeInterval, position: CGPoint) {
self.makeToast(message, duration: duration, position: position, style: nil)
}
/**
Creates and presents a new toast view with a message. Duration, position, and
style can be set explicitly.
@param message The message to be displayed
@param duration The toast duration
@param position The toast's position
@param style The style. The shared style will be used when nil
*/
func makeToast(_ message: String, duration: TimeInterval, position: ToastPosition, style: ToastStyle?) {
self.makeToast(message, duration: duration, position: position, title: nil, image: nil, style: style, completion: nil)
}
/**
Creates and presents a new toast view with a message. Duration, position, and
style can be set explicitly.
@param message The message to be displayed
@param duration The toast duration
@param position The toast's center point
@param style The style. The shared style will be used when nil
*/
func makeToast(_ message: String, duration: TimeInterval, position: CGPoint, style: ToastStyle?) {
self.makeToast(message, duration: duration, position: position, title: nil, image: nil, style: style, completion: nil)
}
/**
Creates and presents a new toast view with a message, title, and image. Duration,
position, and style can be set explicitly. The completion closure executes when the
toast completes presentation. `didTap` will be `true` if the toast view was dismissed
from a tap.
@param message The message to be displayed
@param duration The toast duration
@param position The toast's position
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@param completion The completion closure, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func makeToast(_ message: String?, duration: TimeInterval, position: ToastPosition, title: String?, image: UIImage?, style: ToastStyle?, completion: ((_ didTap: Bool) -> Void)?) {
var toastStyle = ToastManager.shared.style
if let style = style {
toastStyle = style
}
do {
let toast = try self.toastViewForMessage(message, title: title, image: image, style: toastStyle)
self.showToast(toast, duration: duration, position: position, completion: completion)
} catch ToastError.insufficientData {
print("Error: message, title, and image are all nil")
} catch {}
}
/**
Creates and presents a new toast view with a message, title, and image. Duration,
position, and style can be set explicitly. The completion closure executes when the
toast completes presentation. `didTap` will be `true` if the toast view was dismissed
from a tap.
@param message The message to be displayed
@param duration The toast duration
@param position The toast's center point
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@param completion The completion closure, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func makeToast(_ message: String?, duration: TimeInterval, position: CGPoint, title: String?, image: UIImage?, style: ToastStyle?, completion: ((_ didTap: Bool) -> Void)?) {
var toastStyle = ToastManager.shared.style
if let style = style {
toastStyle = style
}
do {
let toast = try self.toastViewForMessage(message, title: title, image: image, style: toastStyle)
self.showToast(toast, duration: duration, position: position, completion: completion)
} catch ToastError.insufficientData {
print("Error: message, title, and image cannot all be nil")
} catch {}
}
// MARK: - Show Toast Methods
/**
Displays any view as toast using the default duration and position.
@param toast The view to be displayed as toast
*/
func showToast(_ toast: UIView) {
self.showToast(toast, duration: ToastManager.shared.duration, position: ToastManager.shared.position, completion: nil)
}
/**
Displays any view as toast at a provided position and duration. The completion closure
executes when the toast view completes. `didTap` will be `true` if the toast view was
dismissed from a tap.
@param toast The view to be displayed as toast
@param duration The notification duration
@param position The toast's position
@param completion The completion block, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func showToast(_ toast: UIView, duration: TimeInterval, position: ToastPosition, completion: ((_ didTap: Bool) -> Void)?) {
let point = self.centerPointForPosition(position, toast: toast)
self.showToast(toast, duration: duration, position: point, completion: completion)
}
/**
Displays any view as toast at a provided position and duration. The completion closure
executes when the toast view completes. `didTap` will be `true` if the toast view was
dismissed from a tap.
@param toast The view to be displayed as toast
@param duration The notification duration
@param position The toast's center point
@param completion The completion block, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func showToast(_ toast: UIView, duration: TimeInterval, position: CGPoint, completion: ((_ didTap: Bool) -> Void)?) {
objc_setAssociatedObject(toast, &ToastKeys.Completion, ToastCompletionWrapper(completion), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if let _ = objc_getAssociatedObject(self, &ToastKeys.ActiveToast) as? UIView, ToastManager.shared.queueEnabled {
objc_setAssociatedObject(toast, &ToastKeys.Duration, NSNumber(value: duration), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(toast, &ToastKeys.Position, NSValue(cgPoint: position), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.queue.add(toast)
} else {
self.showToast(toast, duration: duration, position: position)
}
}
// MARK: - Activity Methods
/**
Creates and displays a new toast activity indicator view at a specified position.
@warning Only one toast activity indicator view can be presented per superview. Subsequent
calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called.
@warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast
activity views can be presented and dismissed while toast views are being displayed.
`makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods.
@param position The toast's position
*/
func makeToastActivity(_ position: ToastPosition) {
// sanity
if let _ = objc_getAssociatedObject(self, &ToastKeys.ActivityView) as? UIView {
return
}
let toast = self.createToastActivityView()
let point = self.centerPointForPosition(position, toast: toast)
self.makeToastActivity(toast, position: point)
}
/**
Creates and displays a new toast activity indicator view at a specified position.
@warning Only one toast activity indicator view can be presented per superview. Subsequent
calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called.
@warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast
activity views can be presented and dismissed while toast views are being displayed.
`makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods.
@param position The toast's center point
*/
func makeToastActivity(_ position: CGPoint) {
// sanity
if let _ = objc_getAssociatedObject(self, &ToastKeys.ActivityView) as? UIView {
return
}
let toast = self.createToastActivityView()
self.makeToastActivity(toast, position: position)
}
/**
Dismisses the active toast activity indicator view.
*/
func hideToastActivity() {
if let toast = objc_getAssociatedObject(self, &ToastKeys.ActivityView) as? UIView {
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { () -> Void in
toast.alpha = 0.0
}, completion: { (finished: Bool) -> Void in
toast.removeFromSuperview()
objc_setAssociatedObject(self, &ToastKeys.ActivityView, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
})
}
}
// MARK: - Private Activity Methods
private func makeToastActivity(_ toast: UIView, position: CGPoint) {
toast.alpha = 0.0
toast.center = position
objc_setAssociatedObject(self, &ToastKeys.ActivityView, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
self.addSubview(toast)
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
toast.alpha = 1.0
}, completion: nil)
}
private func createToastActivityView() -> UIView {
let style = ToastManager.shared.style
let activityView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: style.activitySize.width, height: style.activitySize.height))
activityView.backgroundColor = style.backgroundColor
activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
activityView.layer.cornerRadius = style.cornerRadius
if style.displayShadow {
activityView.layer.shadowColor = style.shadowColor.cgColor
activityView.layer.shadowOpacity = style.shadowOpacity
activityView.layer.shadowRadius = style.shadowRadius
activityView.layer.shadowOffset = style.shadowOffset
}
let activityIndicatorView = UIActivityIndicatorView(style: .whiteLarge)
activityIndicatorView.center = CGPoint(x: activityView.bounds.size.width / 2.0, y: activityView.bounds.size.height / 2.0)
activityView.addSubview(activityIndicatorView)
activityIndicatorView.startAnimating()
return activityView
}
// MARK: - Private Show/Hide Methods
private func showToast(_ toast: UIView, duration: TimeInterval, position: CGPoint) {
toast.center = position
toast.alpha = 0.0
if ToastManager.shared.tapToDismissEnabled {
let recognizer = UITapGestureRecognizer(target: self, action: #selector(UIView.handleToastTapped(_:)))
toast.addGestureRecognizer(recognizer)
toast.isUserInteractionEnabled = true
toast.isExclusiveTouch = true
}
objc_setAssociatedObject(self, &ToastKeys.ActiveToast, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.addSubview(toast)
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { () -> Void in
toast.alpha = 1.0
}) { (finished) -> Void in
let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false)
RunLoop.main.add(timer, forMode: RunLoop.Mode.common)
objc_setAssociatedObject(toast, &ToastKeys.Timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private func hideToast(_ toast: UIView) {
self.hideToast(toast, fromTap: false)
}
private func hideToast(_ toast: UIView, fromTap: Bool) {
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { () -> Void in
toast.alpha = 0.0
}) { (didFinish: Bool) -> Void in
toast.removeFromSuperview()
objc_setAssociatedObject(self, &ToastKeys.ActiveToast, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if let wrapper = objc_getAssociatedObject(toast, &ToastKeys.Completion) as? ToastCompletionWrapper, let completion = wrapper.completion {
completion(fromTap)
}
if let nextToast = self.queue.firstObject as? UIView, let duration = objc_getAssociatedObject(nextToast, &ToastKeys.Duration) as? NSNumber, let position = objc_getAssociatedObject(nextToast, &ToastKeys.Position) as? NSValue {
self.queue.removeObject(at: 0)
self.showToast(nextToast, duration: duration.doubleValue, position: position.cgPointValue)
}
}
}
// MARK: - Events
@objc func handleToastTapped(_ recognizer: UITapGestureRecognizer) {
if let toast = recognizer.view, let timer = objc_getAssociatedObject(toast, &ToastKeys.Timer) as? Timer {
timer.invalidate()
self.hideToast(toast, fromTap: true)
}
}
@objc func toastTimerDidFinish(_ timer: Timer) {
if let toast = timer.userInfo as? UIView {
self.hideToast(toast)
}
}
// MARK: - Toast Construction
/**
Creates a new toast view with any combination of message, title, and image.
The look and feel is configured via the style. Unlike the `makeToast` methods,
this method does not present the toast view automatically. One of the `showToast`
methods must be used to present the resulting view.
@warning if message, title, and image are all nil, this method will throw
`ToastError.InsufficientData`
@param message The message to be displayed
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@throws `ToastError.InsufficientData` when message, title, and image are all nil
@return The newly created toast view
*/
func toastViewForMessage(_ message: String?, title: String?, image: UIImage?, style: ToastStyle) throws -> UIView {
// sanity
if message == nil && title == nil && image == nil {
throw ToastError.insufficientData
}
var messageLabel: UILabel?
var titleLabel: UILabel?
var imageView: UIImageView?
let wrapperView = UIView()
wrapperView.backgroundColor = style.backgroundColor
wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
wrapperView.layer.cornerRadius = style.cornerRadius
if style.displayShadow {
wrapperView.layer.shadowColor = UIColor.black.cgColor
wrapperView.layer.shadowOpacity = style.shadowOpacity
wrapperView.layer.shadowRadius = style.shadowRadius
wrapperView.layer.shadowOffset = style.shadowOffset
}
if let image = image {
imageView = UIImageView(image: image)
imageView?.contentMode = .scaleAspectFit
imageView?.frame = CGRect(x: style.horizontalPadding, y: style.verticalPadding, width: style.imageSize.width, height: style.imageSize.height)
}
var imageRect = CGRect.zero
if let imageView = imageView {
imageRect.origin.x = style.horizontalPadding
imageRect.origin.y = style.verticalPadding
imageRect.size.width = imageView.bounds.size.width
imageRect.size.height = imageView.bounds.size.height
}
if let title = title {
titleLabel = UILabel()
titleLabel?.numberOfLines = style.titleNumberOfLines
titleLabel?.font = style.titleFont
titleLabel?.textAlignment = style.titleAlignment
titleLabel?.lineBreakMode = .byTruncatingTail
titleLabel?.textColor = style.titleColor
titleLabel?.backgroundColor = UIColor.clear
titleLabel?.text = title;
let maxTitleSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage)
let titleSize = titleLabel?.sizeThatFits(maxTitleSize)
if let titleSize = titleSize {
titleLabel?.frame = CGRect(x: 0.0, y: 0.0, width: titleSize.width, height: titleSize.height)
}
}
if let message = message {
messageLabel = UILabel()
messageLabel?.text = message
messageLabel?.numberOfLines = style.messageNumberOfLines
messageLabel?.font = style.messageFont
messageLabel?.textAlignment = style.messageAlignment
messageLabel?.lineBreakMode = .byTruncatingTail;
messageLabel?.textColor = style.messageColor
messageLabel?.backgroundColor = UIColor.clear
let maxMessageSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage)
let messageSize = messageLabel?.sizeThatFits(maxMessageSize)
if let messageSize = messageSize {
let actualWidth = min(messageSize.width, maxMessageSize.width)
let actualHeight = min(messageSize.height, maxMessageSize.height)
messageLabel?.frame = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
}
}
var titleRect = CGRect.zero
if let titleLabel = titleLabel {
titleRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding
titleRect.origin.y = style.verticalPadding
titleRect.size.width = titleLabel.bounds.size.width
titleRect.size.height = titleLabel.bounds.size.height
}
var messageRect = CGRect.zero
if let messageLabel = messageLabel {
messageRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding
messageRect.origin.y = titleRect.origin.y + titleRect.size.height + style.verticalPadding
messageRect.size.width = messageLabel.bounds.size.width
messageRect.size.height = messageLabel.bounds.size.height
}
let longerWidth = max(titleRect.size.width, messageRect.size.width)
let longerX = max(titleRect.origin.x, messageRect.origin.x)
let wrapperWidth = max((imageRect.size.width + (style.horizontalPadding * 2.0)), (longerX + longerWidth + style.horizontalPadding))
let wrapperHeight = max((messageRect.origin.y + messageRect.size.height + style.verticalPadding), (imageRect.size.height + (style.verticalPadding * 2.0)))
wrapperView.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight)
if let titleLabel = titleLabel {
titleLabel.frame = titleRect
wrapperView.addSubview(titleLabel)
}
if let messageLabel = messageLabel {
messageLabel.frame = messageRect
wrapperView.addSubview(messageLabel)
}
if let imageView = imageView {
wrapperView.addSubview(imageView)
}
return wrapperView
}
// MARK: - Helpers
private func centerPointForPosition(_ position: ToastPosition, toast: UIView) -> CGPoint {
let padding: CGFloat = ToastManager.shared.style.verticalPadding
switch(position) {
case .top:
return CGPoint(x: self.bounds.size.width / 2.0, y: (toast.frame.size.height / 2.0) + padding)
case .center:
return CGPoint(x: self.bounds.size.width / 2.0, y: self.bounds.size.height / 2.0)
case .bottom:
return CGPoint(x: self.bounds.size.width / 2.0, y: (self.bounds.size.height - (toast.frame.size.height / 2.0)) - padding)
}
}
}
// MARK: - Toast Style
/**
`ToastStyle` instances define the look and feel for toast views created via the
`makeToast` methods as well for toast views created directly with
`toastViewForMessage(message:title:image:style:)`.
@warning `ToastStyle` offers relatively simple styling options for the default
toast view. If you require a toast view with more complex UI, it probably makes more
sense to create your own custom UIView subclass and present it with the `showToast`
methods.
*/
public struct ToastStyle {
public init() {}
/**
The background color. Default is `UIColor.blackColor()` at 80% opacity.
*/
public var backgroundColor = UIColor.black.withAlphaComponent(0.8)
/**
The title color. Default is `UIColor.whiteColor()`.
*/
public var titleColor = UIColor.white
/**
The message color. Default is `UIColor.whiteColor()`.
*/
public var messageColor = UIColor.white
/**
A percentage value from 0.0 to 1.0, representing the maximum width of the toast
view relative to it's superview. Default is 0.8 (80% of the superview's width).
*/
public var maxWidthPercentage: CGFloat = 0.8 {
didSet {
maxWidthPercentage = max(min(maxWidthPercentage, 1.0), 0.0)
}
}
/**
A percentage value from 0.0 to 1.0, representing the maximum height of the toast
view relative to it's superview. Default is 0.8 (80% of the superview's height).
*/
public var maxHeightPercentage: CGFloat = 0.8 {
didSet {
maxHeightPercentage = max(min(maxHeightPercentage, 1.0), 0.0)
}
}
/**
The spacing from the horizontal edge of the toast view to the content. When an image
is present, this is also used as the padding between the image and the text.
Default is 10.0.
*/
public var horizontalPadding: CGFloat = 10.0
/**
The spacing from the vertical edge of the toast view to the content. When a title
is present, this is also used as the padding between the title and the message.
Default is 10.0.
*/
public var verticalPadding: CGFloat = 10.0
/**
The corner radius. Default is 10.0.
*/
public var cornerRadius: CGFloat = 10.0;
/**
The title font. Default is `UIFont.boldSystemFontOfSize(16.0)`.
*/
public var titleFont = UIFont.boldSystemFont(ofSize: 16.0)
/**
The message font. Default is `UIFont.systemFontOfSize(16.0)`.
*/
public var messageFont = UIFont.systemFont(ofSize: 16.0)
/**
The title text alignment. Default is `NSTextAlignment.Left`.
*/
public var titleAlignment = NSTextAlignment.center
/**
The message text alignment. Default is `NSTextAlignment.Left`.
*/
public var messageAlignment = NSTextAlignment.left
/**
The maximum number of lines for the title. The default is 0 (no limit).
*/
public var titleNumberOfLines = 0
/**
The maximum number of lines for the message. The default is 0 (no limit).
*/
public var messageNumberOfLines = 0
/**
Enable or disable a shadow on the toast view. Default is `false`.
*/
public var displayShadow = false
/**
The shadow color. Default is `UIColor.blackColor()`.
*/
public var shadowColor = UIColor.black
/**
A value from 0.0 to 1.0, representing the opacity of the shadow.
Default is 0.8 (80% opacity).
*/
public var shadowOpacity: Float = 0.8 {
didSet {
shadowOpacity = max(min(shadowOpacity, 1.0), 0.0)
}
}
/**
The shadow radius. Default is 6.0.
*/
public var shadowRadius: CGFloat = 6.0
/**
The shadow offset. The default is 4 x 4.
*/
public var shadowOffset = CGSize(width: 4.0, height: 4.0)
/**
The image size. The default is 80 x 80.
*/
public var imageSize = CGSize(width: 80.0, height: 80.0)
/**
The size of the toast activity view when `makeToastActivity(position:)` is called.
Default is 100 x 100.
*/
public var activitySize = CGSize(width: 100.0, height: 100.0)
/**
The fade in/out animation duration. Default is 0.2.
*/
public var fadeDuration: TimeInterval = 0.2
}
// MARK: - Toast Manager
/**
`ToastManager` provides general configuration options for all toast
notifications. Backed by a singleton instance.
*/
public class ToastManager {
/**
The `ToastManager` singleton instance.
*/
public static let shared = ToastManager()
/**
The shared style. Used whenever toastViewForMessage(message:title:image:style:) is called
with with a nil style.
*/
public var style = ToastStyle()
/**
Enables or disables tap to dismiss on toast views. Default is `true`.
*/
public var tapToDismissEnabled = true
/**
Enables or disables queueing behavior for toast views. When `true`,
toast views will appear one after the other. When `false`, multiple toast
views will appear at the same time (potentially overlapping depending
on their positions). This has no effect on the toast activity view,
which operates independently of normal toast views. Default is `true`.
*/
public var queueEnabled = true
/**
The default duration. Used for the `makeToast` and
`showToast` methods that don't require an explicit duration.
Default is 3.0.
*/
public var duration: TimeInterval = 3.0
/**
Sets the default position. Used for the `makeToast` and
`showToast` methods that don't require an explicit position.
Default is `ToastPosition.Bottom`.
*/
public var position = ToastPosition.bottom
}
| mit | bdd83d22c13c73e34424b707066f4a44 | 39.420573 | 237 | 0.654415 | 4.942366 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | Foundation/Locale.swift | 1 | 17976 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import CoreFoundation
internal func __NSLocaleIsAutoupdating(_ locale: NSLocale) -> Bool {
return false // Auto-updating is only on Darwin
}
internal func __NSLocaleCurrent() -> NSLocale {
return CFLocaleCopyCurrent()._nsObject
}
/**
`Locale` encapsulates information about linguistic, cultural, and technological conventions and standards. Examples of information encapsulated by a locale include the symbol used for the decimal separator in numbers and the way dates are formatted.
Locales are typically used to provide, format, and interpret information about and according to the user’s customs and preferences. They are frequently used in conjunction with formatters. Although you can use many locales, you usually use the one associated with the current user.
*/
public struct Locale : CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable, ReferenceConvertible {
public typealias ReferenceType = NSLocale
public typealias LanguageDirection = NSLocale.LanguageDirection
internal var _wrapped : NSLocale
internal var _autoupdating : Bool
/// Returns the user's current locale.
public static var current : Locale {
return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: false)
}
@available(*, unavailable, message: "Consider using the user's locale or nil instead, depending on use case")
public static var system : Locale { fatalError() }
// MARK: -
//
/// Return a locale with the specified identifier.
public init(identifier: String) {
_wrapped = NSLocale(localeIdentifier: identifier)
_autoupdating = false
}
internal init(reference: NSLocale) {
_wrapped = reference.copy() as! NSLocale
if __NSLocaleIsAutoupdating(reference) {
_autoupdating = true
} else {
_autoupdating = false
}
}
private init(adoptingReference reference: NSLocale, autoupdating: Bool) {
_wrapped = reference
_autoupdating = autoupdating
}
// MARK: -
//
/// Returns a localized string for a specified identifier.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forIdentifier identifier: String) -> String? {
return _wrapped.displayName(forKey: .identifier, value: identifier)
}
/// Returns a localized string for a specified language code.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forLanguageCode languageCode: String) -> String? {
return _wrapped.displayName(forKey: .languageCode, value: languageCode)
}
/// Returns a localized string for a specified region code.
///
/// For example, in the "en" locale, the result for `"fr"` is `"France"`.
public func localizedString(forRegionCode regionCode: String) -> String? {
return _wrapped.displayName(forKey: .countryCode, value: regionCode)
}
/// Returns a localized string for a specified script code.
///
/// For example, in the "en" locale, the result for `"Hans"` is `"Simplified Han"`.
public func localizedString(forScriptCode scriptCode: String) -> String? {
return _wrapped.displayName(forKey: .scriptCode, value: scriptCode)
}
/// Returns a localized string for a specified variant code.
///
/// For example, in the "en" locale, the result for `"POSIX"` is `"Computer"`.
public func localizedString(forVariantCode variantCode: String) -> String? {
return _wrapped.displayName(forKey: .variantCode, value: variantCode)
}
/// Returns a localized string for a specified `Calendar.Identifier`.
///
/// For example, in the "en" locale, the result for `.buddhist` is `"Buddhist Calendar"`.
public func localizedString(for calendarIdentifier: Calendar.Identifier) -> String? {
// NSLocale doesn't export a constant for this
let result = CFLocaleCopyDisplayNameForPropertyValue(unsafeBitCast(_wrapped, to: CFLocale.self), kCFLocaleCalendarIdentifier, Calendar._toNSCalendarIdentifier(calendarIdentifier).rawValue._cfObject)._swiftObject
return result
}
/// Returns a localized string for a specified ISO 4217 currency code.
///
/// For example, in the "en" locale, the result for `"USD"` is `"US Dollar"`.
/// - seealso: `Locale.isoCurrencyCodes`
public func localizedString(forCurrencyCode currencyCode: String) -> String? {
return _wrapped.displayName(forKey: .currencyCode, value: currencyCode)
}
/// Returns a localized string for a specified ICU collation identifier.
///
/// For example, in the "en" locale, the result for `"phonebook"` is `"Phonebook Sort Order"`.
public func localizedString(forCollationIdentifier collationIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collationIdentifier, value: collationIdentifier)
}
/// Returns a localized string for a specified ICU collator identifier.
public func localizedString(forCollatorIdentifier collatorIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collatorIdentifier, value: collatorIdentifier)
}
// MARK: -
//
/// Returns the identifier of the locale.
public var identifier: String {
return _wrapped.localeIdentifier
}
/// Returns the language code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "zh".
public var languageCode: String? {
return _wrapped.object(forKey: .languageCode) as? String
}
/// Returns the region code of the locale, or nil if it has none.
///
/// For example, for the locale "zh-Hant-HK", returns "HK".
public var regionCode: String? {
// n.b. this is called countryCode in ObjC
if let result = _wrapped.object(forKey: .countryCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the script code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "Hant".
public var scriptCode: String? {
return _wrapped.object(forKey: .scriptCode) as? String
}
/// Returns the variant code for the locale, or nil if it has none.
///
/// For example, for the locale "en_POSIX", returns "POSIX".
public var variantCode: String? {
if let result = _wrapped.object(forKey: .variantCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the exemplar character set for the locale, or nil if has none.
public var exemplarCharacterSet: CharacterSet? {
return _wrapped.object(forKey: .exemplarCharacterSet) as? CharacterSet
}
/// Returns the calendar for the locale, or the Gregorian calendar as a fallback.
public var calendar: Calendar {
// NSLocale should not return nil here
if let result = _wrapped.object(forKey: .calendar) as? Calendar {
return result
} else {
return Calendar(identifier: .gregorian)
}
}
/// Returns the collation identifier for the locale, or nil if it has none.
///
/// For example, for the locale "en_US@collation=phonebook", returns "phonebook".
public var collationIdentifier: String? {
return _wrapped.object(forKey: .collationIdentifier) as? String
}
/// Returns true if the locale uses the metric system.
///
/// -seealso: MeasurementFormatter
public var usesMetricSystem: Bool {
// NSLocale should not return nil here, but just in case
if let result = (_wrapped.object(forKey: .usesMetricSystem) as? NSNumber)?.boolValue {
return result
} else {
return false
}
}
/// Returns the decimal separator of the locale.
///
/// For example, for "en_US", returns ".".
public var decimalSeparator: String? {
return _wrapped.object(forKey: .decimalSeparator) as? String
}
/// Returns the grouping separator of the locale.
///
/// For example, for "en_US", returns ",".
public var groupingSeparator: String? {
return _wrapped.object(forKey: .groupingSeparator) as? String
}
/// Returns the currency symbol of the locale.
///
/// For example, for "zh-Hant-HK", returns "HK$".
public var currencySymbol: String? {
return _wrapped.object(forKey: .currencySymbol) as? String
}
/// Returns the currency code of the locale.
///
/// For example, for "zh-Hant-HK", returns "HKD".
public var currencyCode: String? {
return _wrapped.object(forKey: .currencyCode) as? String
}
/// Returns the collator identifier of the locale.
public var collatorIdentifier: String? {
return _wrapped.object(forKey: .collatorIdentifier) as? String
}
/// Returns the quotation begin delimiter of the locale.
///
/// For example, returns `“` for "en_US", and `「` for "zh-Hant-HK".
public var quotationBeginDelimiter: String? {
return _wrapped.object(forKey: .quotationBeginDelimiterKey) as? String
}
/// Returns the quotation end delimiter of the locale.
///
/// For example, returns `”` for "en_US", and `」` for "zh-Hant-HK".
public var quotationEndDelimiter: String? {
return _wrapped.object(forKey: .quotationEndDelimiterKey) as? String
}
/// Returns the alternate quotation begin delimiter of the locale.
///
/// For example, returns `‘` for "en_US", and `『` for "zh-Hant-HK".
public var alternateQuotationBeginDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationBeginDelimiterKey) as? String
}
/// Returns the alternate quotation end delimiter of the locale.
///
/// For example, returns `’` for "en_US", and `』` for "zh-Hant-HK".
public var alternateQuotationEndDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationEndDelimiterKey) as? String
}
// MARK: -
//
/// Returns a list of available `Locale` identifiers.
public static var availableIdentifiers: [String] {
return NSLocale.availableLocaleIdentifiers
}
/// Returns a list of available `Locale` language codes.
public static var isoLanguageCodes: [String] {
return NSLocale.isoLanguageCodes
}
/// Returns a list of available `Locale` region codes.
public static var isoRegionCodes: [String] {
// This was renamed from Obj-C
return NSLocale.isoCountryCodes
}
/// Returns a list of available `Locale` currency codes.
public static var isoCurrencyCodes: [String] {
return NSLocale.isoCurrencyCodes
}
/// Returns a list of common `Locale` currency codes.
public static var commonISOCurrencyCodes: [String] {
return NSLocale.commonISOCurrencyCodes
}
/// Returns a list of the user's preferred languages.
///
/// - note: `Bundle` is responsible for determining the language that your application will run in, based on the result of this API and combined with the languages your application supports.
/// - seealso: `Bundle.preferredLocalizations(from:)`
/// - seealso: `Bundle.preferredLocalizations(from:forPreferences:)`
public static var preferredLanguages: [String] {
return NSLocale.preferredLanguages
}
/// Returns a dictionary that splits an identifier into its component pieces.
public static func components(fromIdentifier string: String) -> [String : String] {
return NSLocale.components(fromLocaleIdentifier: string)
}
/// Constructs an identifier from a dictionary of components.
public static func identifier(fromComponents components: [String : String]) -> String {
return NSLocale.localeIdentifier(fromComponents: components)
}
/// Returns a canonical identifier from the given string.
public static func canonicalIdentifier(from string: String) -> String {
return NSLocale.canonicalLocaleIdentifier(from: string)
}
/// Returns a canonical language identifier from the given string.
public static func canonicalLanguageIdentifier(from string: String) -> String {
return NSLocale.canonicalLanguageIdentifier(from: string)
}
/// Returns the `Locale` identifier from a given Windows locale code, or nil if it could not be converted.
public static func identifier(fromWindowsLocaleCode code: Int) -> String? {
return NSLocale.localeIdentifier(fromWindowsLocaleCode: UInt32(code))
}
/// Returns the Windows locale code from a given identifier, or nil if it could not be converted.
public static func windowsLocaleCode(fromIdentifier identifier: String) -> Int? {
let result = NSLocale.windowsLocaleCode(fromLocaleIdentifier: identifier)
if result == 0 {
return nil
} else {
return Int(result)
}
}
/// Returns the character direction for a specified language code.
public static func characterDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.characterDirection(forLanguage: isoLangCode)
}
/// Returns the line direction for a specified language code.
public static func lineDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.lineDirection(forLanguage: isoLangCode)
}
// MARK: -
@available(*, unavailable, renamed: "init(identifier:)")
public init(localeIdentifier: String) { fatalError() }
@available(*, unavailable, renamed: "identifier")
public var localeIdentifier: String { fatalError() }
@available(*, unavailable, renamed: "localizedString(forIdentifier:)")
public func localizedString(forLocaleIdentifier localeIdentifier: String) -> String { fatalError() }
@available(*, unavailable, renamed: "availableIdentifiers")
public static var availableLocaleIdentifiers: [String] { fatalError() }
@available(*, unavailable, renamed: "components(fromIdentifier:)")
public static func components(fromLocaleIdentifier string: String) -> [String : String] { fatalError() }
@available(*, unavailable, renamed: "identifier(fromComponents:)")
public static func localeIdentifier(fromComponents dict: [String : String]) -> String { fatalError() }
@available(*, unavailable, renamed: "canonicalIdentifier(from:)")
public static func canonicalLocaleIdentifier(from string: String) -> String { fatalError() }
@available(*, unavailable, renamed: "identifier(fromWindowsLocaleCode:)")
public static func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { fatalError() }
@available(*, unavailable, renamed: "windowsLocaleCode(fromIdentifier:)")
public static func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { fatalError() }
@available(*, unavailable, message: "use regionCode instead")
public var countryCode: String { fatalError() }
@available(*, unavailable, message: "use localizedString(forRegionCode:) instead")
public func localizedString(forCountryCode countryCode: String) -> String { fatalError() }
@available(*, unavailable, renamed: "isoRegionCodes")
public static var isoCountryCodes: [String] { fatalError() }
// MARK: -
//
public var description: String {
return _wrapped.description
}
public var debugDescription : String {
return _wrapped.debugDescription
}
public var hashValue : Int {
if _autoupdating {
return 1
} else {
return _wrapped.hash
}
}
}
public func ==(lhs: Locale, rhs: Locale) -> Bool {
if lhs._autoupdating || rhs._autoupdating {
return lhs._autoupdating == rhs._autoupdating
} else {
return lhs._wrapped.isEqual(rhs._wrapped)
}
}
extension Locale : _ObjectTypeBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSLocale {
return _wrapped
}
public static func _forceBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) {
if !_conditionallyBridgeFromObjectiveC(input, result: &result) {
fatalError("Unable to bridge \(NSLocale.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) -> Bool {
result = Locale(reference: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSLocale?) -> Locale {
var result: Locale? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
| apache-2.0 | 6a0475ce7a070d6e9d34bc7b41fcac23 | 38.209607 | 282 | 0.65514 | 5.084371 | false | false | false | false |
gyro-n/PaymentsIos | GyronPayments/Classes/Models/Cancel.swift | 1 | 2381 | //
// Cancel.swift
// GyronPayments
//
// Created by David Ye on 2017/08/31.
// Copyright © 2016 gyron. All rights reserved.
//
import Foundation
/**
The CancelStatus enum is a list of cancel statuses.
*/
public enum CancelStatus: String {
case pending = "pending"
case successful = "successful"
case failed = "failed"
case error = "error"
}
/**
The Cancel class stores the information about cancelations for a charge.
*/
open class Cancel: BaseModel {
/**
The unique identifier for the cancel.
*/
public var id: String
/**
The unique identifier for the charge.
*/
public var chargeId: String
/**
The unique identifier for the store.
*/
public var storeId: String?
/**
The status of the cancel. One of pending, successful, failed, or errored.
*/
public var status: CancelStatus
/**
The error for the cancel (if any)
- code: The error code of why a cancel failed or errored.
- message: A short description of why a cancel failed.
- detail: Additional details of why a cancel failed
*/
public var error: PaymentError?
/**
Any metadata to associate with the cancel.
*/
public var metadata: Metadata?
/**
live or test
*/
public var mode: ProcessingMode
/**
The date the cancel was created.
*/
public var createdOn: String
/**
Initializes the Cancel object
*/
override init() {
id = ""
chargeId = ""
storeId = nil
status = CancelStatus.pending
error = nil
metadata = nil
mode = ProcessingMode.test
createdOn = ""
}
/**
Maps the values from a hash map object into the Cancel.
*/
override open func mapFromObject(map: ResponseData) {
id = map["id"] as? String ?? ""
chargeId = map["charge_id"] as? String ?? ""
storeId = map["store_id"] as? String
status = CancelStatus(rawValue: map["status"] as? String ?? CancelStatus.pending.rawValue)!
createdOn = map["created_on"] as? String ?? ""
error = map["error"] as? PaymentError
metadata = map["metadata"] as? Metadata
mode = ProcessingMode(rawValue: map["mode"] as? String ?? ProcessingMode.test.rawValue)!
createdOn = map["created_on"] as? String ?? ""
}
}
| mit | a48d9bc7205766856a162af08b65e720 | 25.444444 | 99 | 0.60042 | 4.399261 | false | false | false | false |
Allow2CEO/browser-ios | Client/Frontend/Browser/BrowserViewController/BrowserViewController+KeyCommands.swift | 1 | 4548 | /* 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 Shared
extension BrowserViewController {
func reloadTab(){
if homePanelController == nil {
tabManager.selectedTab?.reload()
}
}
func goBack(){
if tabManager.selectedTab?.canGoBack == true && homePanelController == nil {
tabManager.selectedTab?.goBack()
}
}
func goForward(){
if tabManager.selectedTab?.canGoForward == true && homePanelController == nil {
tabManager.selectedTab?.goForward()
}
}
func findOnPage(){
if let tab = tabManager.selectedTab, homePanelController == nil {
browser(tab, didSelectFindInPageForSelection: "")
}
}
func selectLocationBar() {
urlBar.browserLocationViewDidTapLocation(urlBar.locationView)
}
func newTab() {
openBlankNewTabAndFocus(isPrivate: PrivateBrowsing.singleton.isOn)
self.selectLocationBar()
}
func newPrivateTab() {
openBlankNewTabAndFocus(isPrivate: true)
if PinViewController.isBrowserLockEnabled {
self.selectLocationBar()
}
}
func closeTab() {
guard let tab = tabManager.selectedTab else { return }
let priv = tab.isPrivate
nextOrPrevTabShortcut(false)
tabManager.removeTab(tab, createTabIfNoneLeft: !priv)
if priv && tabManager.tabs.privateTabs.count == 0 {
urlBarDidPressTabs(urlBar)
}
}
fileprivate func nextOrPrevTabShortcut(_ isNext: Bool) {
guard let tab = tabManager.selectedTab else { return }
let step = isNext ? 1 : -1
let tabList: [Browser] = tabManager.tabs.displayedTabsForCurrentPrivateMode
func wrappingMod(_ val:Int, mod:Int) -> Int {
return ((val % mod) + mod) % mod
}
assert(wrappingMod(-1, mod: 10) == 9)
let index = wrappingMod((tabList.index(of: tab)! + step), mod: tabList.count)
tabManager.selectTab(tabList[index])
}
func nextTab() {
nextOrPrevTabShortcut(true)
}
func previousTab() {
nextOrPrevTabShortcut(false)
}
override var keyCommands: [UIKeyCommand]? {
let result = [
UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(BrowserViewController.reloadTab), discoverabilityTitle: Strings.ReloadPageTitle),
UIKeyCommand(input: "[", modifierFlags: .command, action: #selector(BrowserViewController.goBack), discoverabilityTitle: Strings.BackTitle),
UIKeyCommand(input: "]", modifierFlags: .command, action: #selector(BrowserViewController.goForward), discoverabilityTitle: Strings.ForwardTitle),
UIKeyCommand(input: "f", modifierFlags: .command, action: #selector(BrowserViewController.findOnPage), discoverabilityTitle: Strings.FindTitle),
UIKeyCommand(input: "l", modifierFlags: .command, action: #selector(BrowserViewController.selectLocationBar), discoverabilityTitle: Strings.SelectLocationBarTitle),
UIKeyCommand(input: "t", modifierFlags: .command, action: #selector(BrowserViewController.newTab), discoverabilityTitle: Strings.NewTabTitle),
//#if DEBUG
UIKeyCommand(input: "t", modifierFlags: .control, action: #selector(BrowserViewController.newTab), discoverabilityTitle: Strings.NewTabTitle),
//#endif
UIKeyCommand(input: "p", modifierFlags: [.command, .shift], action: #selector(BrowserViewController.newPrivateTab), discoverabilityTitle: Strings.NewPrivateTabTitle),
UIKeyCommand(input: "w", modifierFlags: .command, action: #selector(BrowserViewController.closeTab), discoverabilityTitle: Strings.CloseTabTitle),
UIKeyCommand(input: "\t", modifierFlags: .control, action: #selector(BrowserViewController.nextTab), discoverabilityTitle: Strings.ShowNextTabTitle),
UIKeyCommand(input: "\t", modifierFlags: [.control, .shift], action: #selector(BrowserViewController.previousTab), discoverabilityTitle: Strings.ShowPreviousTabTitle),
]
#if DEBUG
// in simulator, CMD+t is slow-mo animation
return result + [
UIKeyCommand(input: "t", modifierFlags: [.command, .shift], action: #selector(BrowserViewController.newTab))]
#else
return result
#endif
}
}
| mpl-2.0 | 3a62f767e60d2065599d8fbed37477e2 | 44.029703 | 198 | 0.664688 | 5.115861 | false | false | false | false |
jarrroo/MarkupKitLint | Tools/Pods/Nimble/Sources/Nimble/Matchers/AsyncMatcherWrapper.swift | 28 | 10966 | import Foundation
/// If you are running on a slower machine, it could be useful to increase the default timeout value
/// or slow down poll interval. Default timeout interval is 1, and poll interval is 0.01.
public struct AsyncDefaults {
public static var Timeout: TimeInterval = 1
public static var PollInterval: TimeInterval = 0.01
}
fileprivate func async<T>(style: ExpectationStyle, predicate: Predicate<T>, timeout: TimeInterval, poll: TimeInterval, fnName: String) -> Predicate<T> {
return Predicate { actualExpression in
let uncachedExpression = actualExpression.withoutCaching()
let fnName = "expect(...).\(fnName)(...)"
var lastPredicateResult: PredicateResult?
let result = pollBlock(
pollInterval: poll,
timeoutInterval: timeout,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: fnName) {
lastPredicateResult = try predicate.satisfies(uncachedExpression)
return lastPredicateResult!.toBoolean(expectation: style)
}
switch result {
case .completed: return lastPredicateResult!
case .timedOut: return PredicateResult(status: .fail, message: lastPredicateResult!.message)
case let .errorThrown(error):
return PredicateResult(status: .fail, message: .fail("unexpected error thrown: <\(error)>"))
case let .raisedException(exception):
return PredicateResult(status: .fail, message: .fail("unexpected exception raised: \(exception)"))
case .blockedRunLoop:
return PredicateResult(status: .fail, message: lastPredicateResult!.message.appended(message: " (timed out, but main thread was unresponsive)."))
case .incomplete:
internalError("Reached .incomplete state for toEventually(...).")
}
}
}
// Deprecated
internal struct AsyncMatcherWrapper<T, U>: Matcher
where U: Matcher, U.ValueType == T {
let fullMatcher: U
let timeoutInterval: TimeInterval
let pollInterval: TimeInterval
init(fullMatcher: U, timeoutInterval: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval) {
self.fullMatcher = fullMatcher
self.timeoutInterval = timeoutInterval
self.pollInterval = pollInterval
}
func matches(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let fnName = "expect(...).toEventually(...)"
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: fnName) {
try self.fullMatcher.matches(uncachedExpression, failureMessage: failureMessage)
}
switch result {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.stringValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.stringValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventually(...).")
}
}
func doesNotMatch(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: "expect(...).toEventuallyNot(...)") {
try self.fullMatcher.doesNotMatch(uncachedExpression, failureMessage: failureMessage)
}
switch result {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.stringValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.stringValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventuallyNot(...).")
}
}
}
private let toEventuallyRequiresClosureError = FailureMessage(stringValue: "expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )\nSwift 1.2 @autoclosure behavior has changed in an incompatible way for Nimble to function")
extension Expectation {
/// Tests the actual value using a matcher to match by checking continuously
/// at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventually(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) {
nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue)
let (pass, msg) = execute(
expression,
.toMatch,
async(style: .toMatch, predicate: predicate, timeout: timeout, poll: pollInterval, fnName: "toEventually"),
to: "to eventually",
description: description,
captureExceptions: false
)
verify(pass, msg)
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventuallyNot(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) {
nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue)
let (pass, msg) = execute(
expression,
.toNotMatch,
async(style: .toNotMatch, predicate: predicate, timeout: timeout, poll: pollInterval, fnName: "toEventuallyNot"),
to: "to eventually not",
description: description,
captureExceptions: false
)
verify(pass, msg)
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// Alias of toEventuallyNot()
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toNotEventually(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) {
return toEventuallyNot(predicate, timeout: timeout, pollInterval: pollInterval, description: description)
}
}
// Deprecated
extension Expectation {
/// Tests the actual value using a matcher to match by checking continuously
/// at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T {
if expression.isClosure {
let (pass, msg) = expressionMatches(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
to: "to eventually",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventuallyNot<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T {
if expression.isClosure {
let (pass, msg) = expressionDoesNotMatch(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
toNot: "to eventually not",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// Alias of toEventuallyNot()
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toNotEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T {
return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description)
}
}
| mit | cd60aefb095c86637d34f8ecccf368ae | 47.522124 | 268 | 0.662867 | 5.597754 | false | false | false | false |
DeveloperPans/PSCarouselView | CarouselDemo/CarouselDemo/CarouselWithSwift/SwiftViewController.swift | 1 | 1323 | //
// SwiftViewController.swift
// CarouselDemo
//
// Created by Pan on 16/4/18.
// Copyright © 2016年 Pan. All rights reserved.
//
import UIKit
import PSCarouselView
let IMAGE_URLSTRING0 = "http://img.hb.aicdn.com/0f14ad30f6c0b4e4cf96afcad7a0f9d6332e5b061b5f3c-uSUEUC_fw658"
let IMAGE_URLSTRING1 = "http://img.hb.aicdn.com/3f9d1434ba618579d50ae8c8476087f1a04d7ee3169f8e-zD2u09_fw658"
let IMAGE_URLSTRING2 = "http://img.hb.aicdn.com/81427fb53bed38bf1b6a0c5da1c5d5a485e00bd1149232-gn4CO1_fw658"
let ScreenWidth = UIScreen.main.bounds.size.width
class SwiftViewController: UIViewController {
var carouselView: PSCarouselView = PSCarouselView()
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
setupCarouselView()
view.addSubview(carouselView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
carouselView.startMoving()
}
func setupCarouselView() {
carouselView.frame = CGRect(x: 0,y: 64,width: ScreenWidth,height: 0.382 * ScreenWidth)
carouselView.imageURLs = [IMAGE_URLSTRING0,IMAGE_URLSTRING1,IMAGE_URLSTRING2]
carouselView.placeholder = UIImage(named: "placeholder")
carouselView.isAutoMoving = true
}
}
| mit | 77d827f84397c281af312f7d4888257a | 32 | 108 | 0.725 | 3.308271 | false | false | false | false |
sbooth/SFBAudioEngine | Player/SFBAudioPlayer.swift | 1 | 2746 | //
// Copyright (c) 2020 - 2022 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
import Foundation
extension AudioPlayer {
/// Playback position information for `AudioPlayer`
public typealias PlaybackPosition = AudioPlayerNode.PlaybackPosition
/// Playback time information for `AudioPlayer`
public typealias PlaybackTime = AudioPlayerNode.PlaybackTime
/// Returns the frame position in the current decoder or `nil` if the current decoder is `nil`
public var framePosition: AVAudioFramePosition? {
let framePosition = __framePosition
return framePosition == unknownFramePosition ? nil : framePosition
}
/// Returns the frame length of the current decoder or `nil` if the current decoder is `nil`
public var frameLength: AVAudioFramePosition? {
let frameLength = __frameLength
return frameLength == unknownFrameLength ? nil : frameLength
}
/// Returns the playback position in the current decoder or `nil` if the current decoder is `nil`
public var position: PlaybackPosition? {
var position = SFBAudioPlayerPlaybackPosition()
guard __getPlaybackPosition(&position, andTime: nil) else {
return nil
}
return PlaybackPosition(position)
}
/// Returns the current time in the current decoder or `nil` if the current decoder is `nil`
public var currentTime: TimeInterval? {
let currentTime = __currentTime
return currentTime == unknownTime ? nil : currentTime
}
/// Returns the total time of the current decoder or `nil` if the current decoder is `nil`
public var totalTime: TimeInterval? {
let totalTime = __totalTime
return totalTime == unknownTime ? nil : totalTime
}
/// Returns the playback time in the current decoder or `nil` if the current decoder is `nil`
public var time: PlaybackTime? {
var time = SFBAudioPlayerPlaybackTime()
guard __getPlaybackPosition(nil, andTime: &time) else {
return nil
}
return PlaybackTime(time)
}
/// Returns the playback position and time in the current decoder or `nil` if the current decoder is `nil`
public var positionAndTime: (position: PlaybackPosition, time: PlaybackTime)? {
var position = SFBAudioPlayerPlaybackPosition()
var time = SFBAudioPlayerPlaybackTime()
guard __getPlaybackPosition(&position, andTime: &time) else {
return nil
}
return (position: PlaybackPosition(position), time: PlaybackTime(time))
}
}
extension AudioPlayer.PlaybackState: CustomDebugStringConvertible {
// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
switch self {
case .playing:
return ".playing"
case .paused:
return ".paused"
case .stopped:
return ".stopped"
@unknown default:
fatalError()
}
}
}
| mit | 8b9f71619bfa55c42cae29727eba2a0c | 32.487805 | 107 | 0.74472 | 4.092399 | false | false | false | false |
jlandon/Alexandria | Sources/Alexandria/ImageEffects/UIImage+Effects.swift | 1 | 14492 | /*
File: UIImage+ImageEffects.m
Abstract: This is a category of UIImage that adds methods to apply blur and tint effects to an image. This is the code you’ll want to look out to find out how to use vImage to efficiently calculate a blur.
Version: 1.0
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2013 Apple Inc. All Rights Reserved.
Copyright © 2013 Apple Inc. All rights reserved.
WWDC 2013 License
NOTE: This Apple Software was supplied by Apple as part of a WWDC 2013
Session. Please refer to the applicable WWDC 2013 Session for further
information.
IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and
your use, installation, modification or redistribution of this Apple
software constitutes acceptance of these terms. If you do not agree with
these terms, please do not use, install, modify or redistribute this
Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple
Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES
NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
EA1002
5/3/2013
*/
//
// UIImage.swift
// Today
//
// Created by Alexey Globchastyy on 15/09/14.
// Copyright (c) 2014 Alexey Globchastyy. All rights reserved.
//
import UIKit
import Accelerate
extension UIImage {
/**
Applies a lightening (blur) effect to the image
- returns: The lightened image, or nil if error.
*/
public func applyLightEffect() -> UIImage? {
return applyBlur(withRadius: 30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.0)
}
/**
Applies an extra lightening (blur) effect to the image
- returns: The extra lightened image, or nil if error.
*/
public func applyExtraLightEffect() -> UIImage? {
return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8)
}
/**
Applies a darkening (blur) effect to the image.
- returns: The darkened image, or nil if error.
*/
public func applyDarkEffect() -> UIImage? {
return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8)
}
/**
Tints the image with the given color.
- parameter tintColor: The tint color
- returns: The tinted image, or nil if error.
*/
public func applyTintEffect(withColor tintColor: UIColor) -> UIImage? {
let effectColorAlpha: CGFloat = 0.6
var effectColor = tintColor
let componentCount = tintColor.cgColor.numberOfComponents
if componentCount == 2 {
var b: CGFloat = 0
if tintColor.getWhite(&b, alpha: nil) {
effectColor = UIColor(white: b, alpha: effectColorAlpha)
}
} else {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) {
effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha)
}
}
return applyBlur(withRadius: 10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil)
}
/**
Core function to create a new image with the given blur.
- parameter blurRadius: The blur radius
- parameter tintColor: The color to tint the image; optional.
- parameter saturationDeltaFactor: The delta by which to change the image saturation
- parameter maskImage: An optional image mask.
- returns: The adjusted image, or nil if error.
*/
public func applyBlur(withRadius blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? {
// Check pre-conditions.
guard size.width >= 1 && size.height >= 1 else {
print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)")
return nil
}
guard let cgImage = self.cgImage else {
print("*** error: image must be backed by a CGImage: \(self)")
return nil
}
if maskImage != nil && maskImage!.cgImage == nil {
print("*** error: maskImage must be backed by a CGImage: \(String(describing: maskImage))")
return nil
}
defer { UIGraphicsEndImageContext() }
let epsilon = CGFloat(Float.ulpOfOne)
let screenScale = UIScreen.main.scale
let imageRect = CGRect(origin: .zero, size: size)
var effectImage: UIImage? = self
let hasBlur = blurRadius > epsilon
let hasSaturationChange = abs(saturationDeltaFactor - 1.0) > epsilon
if hasBlur || hasSaturationChange {
func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
let data = context.data
let width = context.width
let height = context.height
let rowBytes = context.bytesPerRow
return vImage_Buffer(data: data, height: UInt(height), width: UInt(width), rowBytes: rowBytes)
}
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
guard let effectInContext = UIGraphicsGetCurrentContext() else { return self }
effectInContext.scaleBy(x: 1, y: -1)
effectInContext.translateBy(x: 0, y: -size.height)
effectInContext.draw(cgImage, in: imageRect)
var effectInBuffer = createEffectBuffer(effectInContext)
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
guard let effectOutContext = UIGraphicsGetCurrentContext() else { return self }
var effectOutBuffer = createEffectBuffer(effectOutContext)
if hasBlur {
// A description of how to compute the box kernel width from the Gaussian
// radius (aka standard deviation) appears in the SVG spec:
// http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
//
// For larger values of 's' (s >= 2.0), an approximation can be used: Three
// successive box-blurs build a piece-wise quadratic convolution kernel, which
// approximates the Gaussian kernel to within roughly 3%.
//
// let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
//
// ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
//
let inputRadius = blurRadius * screenScale
let input = inputRadius * 3 * sqrt(2 * .pi) / 4 + 0.5
var radius = UInt32(floor(input))
if radius % 2 != 1 {
radius += 1 // force radius to be odd so that the three box-blur methodology works.
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s: CGFloat = saturationDeltaFactor
let floatingPointSaturationMatrix: [CGFloat] = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
]
let divisor: CGFloat = 256
let saturationMatrix = floatingPointSaturationMatrix.map { Int16(round($0) * divisor) }
if hasBlur {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
effectImageBuffersAreSwapped = true
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
}
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
if effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
}
// Set up output context.
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let outputContext = UIGraphicsGetCurrentContext()
outputContext?.scaleBy(x: 1, y: -1)
outputContext?.translateBy(x: 0, y: -size.height)
// Draw base image.
outputContext?.draw(cgImage, in: imageRect)
// Draw effect image.
if let effectImage = effectImage?.cgImage, hasBlur {
outputContext?.saveGState()
if let image = maskImage?.cgImage {
outputContext?.clip(to: imageRect, mask: image)
}
outputContext?.draw(effectImage, in: imageRect)
outputContext?.restoreGState()
}
// Add in color tint.
if let color = tintColor {
outputContext?.saveGState()
outputContext?.setFillColor(color.cgColor)
outputContext?.fill(imageRect)
outputContext?.restoreGState()
}
// Output image is ready.
return UIGraphicsGetImageFromCurrentImageContext()
}
}
| mit | 0c35e38a35dd6e0d5ac3bbed3d3825e5 | 43.444785 | 205 | 0.647733 | 5.078514 | false | false | false | false |
Rag0n/QuNotes | QuNotes/Library/LibraryViewController.swift | 1 | 4906 | //
// LibraryViewController.swift
// QuNotes
//
// Created by Alexander Guschin on 21.09.17.
// Copyright © 2017 Alexander Guschin. All rights reserved.
//
import UIKit
import Prelude
final public class LibraryViewController: UIViewController {
public func perform(effect: Library.ViewEffect) {
switch effect {
case .updateAllNotebooks(let notebooks):
self.notebooks = notebooks
tableView.reloadData()
case .addNotebook(let index, let notebooks):
self.notebooks = notebooks
let indexPath = IndexPath(row: index, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
case .deleteNotebook(let index, let notebooks):
self.notebooks = notebooks
let indexPath = IndexPath(row: index, section: 0)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
public init(withDispatch dispatch: @escaping Library.ViewDispacher) {
self.dispatch = dispatch
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func loadView() {
view = UIView()
view.flex.alignItems(.center).define {
$0.addItem(tableView).grow(1)
$0.addItem(addButton).position(.absolute).bottom(20)
}
navigationItem.title = "library_title".localized
tableView.dataSource = self
tableView.delegate = self
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
view.flex.layout()
}
override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard traitCollection.preferredContentSizeCategory != previousTraitCollection?.preferredContentSizeCategory else { return }
addButton.flex.markDirty()
}
// MARK: - Private
fileprivate enum Constants {
static let estimatedCellHeight: CGFloat = 44
static let libraryCellReuseIdentifier = "libraryCellReuseIdentifier"
}
fileprivate var notebooks: [Library.NotebookViewModel] = []
fileprivate var dispatch: Library.ViewDispacher
private let tableView: UITableView = {
let t = UITableView()
LibraryTableViewCell.registerFor(tableView: t, reuseIdentifier: Constants.libraryCellReuseIdentifier)
let theme = AppEnvironment.current.theme
t.backgroundColor = theme.ligherDarkColor
t.separatorColor = theme.textColor.withAlphaComponent(0.5)
t.estimatedRowHeight = Constants.estimatedCellHeight
return t
}()
private let addButton: UIButton = {
let b = UIButton(type: .system)
b.setTitle("library_add_notebook_button".localized, for: .normal)
b.titleLabel!.font = UIFont.preferredFont(forTextStyle: .headline)
b.titleLabel!.adjustsFontForContentSizeCategory = true
b.addTarget(self, action: #selector(addNotebookButtonDidTap), for: .touchUpInside)
return b
}()
@objc private func addNotebookButtonDidTap() {
dispatch <| .addNotebook
}
}
// MARK: - UITableViewDataSource
extension LibraryViewController: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notebooks.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.libraryCellReuseIdentifier, for: indexPath) as! LibraryTableViewCell
cell.render(viewModel: notebooks[indexPath.row])
return cell
}
}
// MARK: - UITableViewDelegate
extension LibraryViewController: UITableViewDelegate {
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dispatch <| .selectNotebook(index: indexPath.row)
tableView.deselectRow(at: indexPath, animated: true)
}
public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = deleteContextualAction(forIndexPath: indexPath)
let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
return configuration
}
private func deleteContextualAction(forIndexPath indexPath: IndexPath) -> UIContextualAction {
let action = UIContextualAction(style: .destructive, title: "library_delete_notebook_button".localized) { [unowned self] (action, view, success) in
self.dispatch <| .deleteNotebook(index: indexPath.row)
success(true)
}
action.backgroundColor = .red
return action
}
}
| gpl-3.0 | ad2549d893d2c7146791725f67d86c14 | 36.730769 | 155 | 0.691743 | 5.257235 | false | false | false | false |
LouisZhu/Gatling | Gatling/Classes/TimeStrategy.swift | 1 | 2939 | //
// TimeStrategy.swift
//
// Copyright (c) 2016 Louis Zhu (http://github.com/LouisZhu)
//
// 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
private struct TimeBaseInfo {
static let timebase_info: mach_timebase_info_data_t = {
var info = mach_timebase_info_data_t()
mach_timebase_info(&info)
return info
}()
static var denom: UInt32 {
return timebase_info.denom
}
static var numer: UInt32 {
return timebase_info.numer
}
}
private func gatling_time_absolute_to_nanoseconds(absoluteTime: UInt64) -> UInt64 {
return absoluteTime * UInt64(TimeBaseInfo.numer) / UInt64(TimeBaseInfo.denom)
}
private func gatling_time_nanoseconds_to_absolute(nanoseconds: UInt64) -> UInt64 {
return nanoseconds * UInt64(TimeBaseInfo.denom) / UInt64(TimeBaseInfo.numer)
}
internal func gatling_dispatch_when(when: UInt64, _ queue: dispatch_queue_t, _ block: dispatch_block_t) {
let now = mach_absolute_time()
if when < now {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), queue, block)
return
}
let delta = gatling_time_absolute_to_nanoseconds(when - now)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delta)), queue, block)
}
internal class TimeStrategy {
private let startTime: UInt64
private let timeInterval: NSTimeInterval
private(set) var nextFireTime: UInt64
init(timeInterval: NSTimeInterval) {
let now = mach_absolute_time()
self.startTime = now
self.timeInterval = timeInterval
self.nextFireTime = now
self.updateNextFireTime()
}
internal func updateNextFireTime() {
let delta = gatling_time_nanoseconds_to_absolute(UInt64(self.timeInterval * Double(NSEC_PER_SEC)))
self.nextFireTime = self.nextFireTime + delta
}
}
| mit | 64dc5774e393813fe4dec1d7e786d8bf | 31.296703 | 106 | 0.696155 | 4.116246 | false | false | false | false |
jacobwhite/firefox-ios | Client/Frontend/Browser/ButtonToast.swift | 1 | 6969 | /* 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 SnapKit
struct ButtonToastUX {
static let ToastPadding = 15.0
static let TitleSpacing = 2.0
static let ToastButtonPadding: CGFloat = 10.0
static let TitleButtonPadding: CGFloat = 5.0
static let ToastDelay = DispatchTimeInterval.milliseconds(900)
static let ToastButtonBorderRadius: CGFloat = 5
static let ToastButtonBorderWidth: CGFloat = 1
}
private class HighlightableButton: UIButton {
override var isHighlighted: Bool {
didSet {
self.backgroundColor = isHighlighted ? .white : .clear
}
}
}
class ButtonToast: UIView {
fileprivate var dismissed = false
fileprivate var completionHandler: ((Bool) -> Void)?
fileprivate lazy var toast: UIView = {
let toast = UIView()
toast.backgroundColor = SimpleToastUX.ToastDefaultColor
return toast
}()
fileprivate var animationConstraint: Constraint?
fileprivate lazy var gestureRecognizer: UITapGestureRecognizer = {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
gestureRecognizer.cancelsTouchesInView = false
return gestureRecognizer
}()
init(labelText: String, descriptionText: String? = nil, buttonText: String, completion:@escaping (_ buttonPressed: Bool) -> Void) {
super.init(frame: .zero)
completionHandler = completion
self.clipsToBounds = true
self.addSubview(createView(labelText, descriptionText: descriptionText, buttonText: buttonText))
toast.snp.makeConstraints { make in
make.left.right.height.equalTo(self)
animationConstraint = make.top.equalTo(self).offset(SimpleToastUX.ToastHeight).constraint
}
self.snp.makeConstraints { make in
make.height.equalTo(SimpleToastUX.ToastHeight)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func createView(_ labelText: String, descriptionText: String?, buttonText: String) -> UIView {
let label = UILabel()
label.textColor = UIColor.white
label.font = SimpleToastUX.ToastFont
label.text = labelText
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
toast.addSubview(label)
let button = HighlightableButton()
button.layer.cornerRadius = ButtonToastUX.ToastButtonBorderRadius
button.layer.borderWidth = ButtonToastUX.ToastButtonBorderWidth
button.layer.borderColor = UIColor.white.cgColor
button.setTitle(buttonText, for: [])
button.setTitleColor(self.toast.backgroundColor, for: .highlighted)
button.titleLabel?.font = SimpleToastUX.ToastFont
button.titleLabel?.numberOfLines = 1
button.titleLabel?.lineBreakMode = .byClipping
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.minimumScaleFactor = 0.1
let recognizer = UITapGestureRecognizer(target: self, action: #selector(buttonPressed))
button.addGestureRecognizer(recognizer)
toast.addSubview(button)
var descriptionLabel: UILabel?
if let text = descriptionText {
let textLabel = UILabel()
textLabel.textColor = UIColor.white
textLabel.font = SimpleToastUX.ToastFont
textLabel.text = text
textLabel.lineBreakMode = .byTruncatingTail
toast.addSubview(textLabel)
descriptionLabel = textLabel
}
if let description = descriptionLabel {
label.numberOfLines = 1 // if showing a description we cant wrap to the second line
label.lineBreakMode = .byClipping
label.adjustsFontSizeToFitWidth = true
label.snp.makeConstraints { (make) in
make.leading.equalTo(toast).offset(ButtonToastUX.ToastPadding)
make.top.equalTo(toast).offset(ButtonToastUX.TitleButtonPadding)
make.trailing.equalTo(button.snp.leading).offset(-ButtonToastUX.TitleButtonPadding)
}
description.snp.makeConstraints { (make) in
make.leading.equalTo(toast).offset(ButtonToastUX.ToastPadding)
make.top.equalTo(label.snp.bottom).offset(ButtonToastUX.TitleSpacing)
make.trailing.equalTo(button.snp.leading).offset(-ButtonToastUX.TitleButtonPadding)
}
} else {
label.snp.makeConstraints { (make) in
make.leading.equalTo(toast).offset(ButtonToastUX.ToastPadding)
make.centerY.equalTo(toast)
make.trailing.equalTo(button.snp.leading).offset(-ButtonToastUX.TitleButtonPadding)
}
}
button.snp.makeConstraints { (make) in
make.trailing.equalTo(toast).offset(-ButtonToastUX.ToastPadding)
make.centerY.equalTo(toast)
make.width.equalTo(button.titleLabel!.intrinsicContentSize.width + 2*ButtonToastUX.ToastButtonPadding)
}
return toast
}
fileprivate func dismiss(_ buttonPressed: Bool) {
guard dismissed == false else {
return
}
dismissed = true
superview?.removeGestureRecognizer(gestureRecognizer)
UIView.animate(withDuration: SimpleToastUX.ToastAnimationDuration, animations: {
self.animationConstraint?.update(offset: SimpleToastUX.ToastHeight)
self.layoutIfNeeded()
},
completion: { finished in
self.removeFromSuperview()
if !buttonPressed {
self.completionHandler?(false)
}
}
)
}
func showToast(duration: DispatchTimeInterval = SimpleToastUX.ToastDismissAfter) {
layoutIfNeeded()
UIView.animate(withDuration: SimpleToastUX.ToastAnimationDuration, animations: {
self.animationConstraint?.update(offset: 0)
self.layoutIfNeeded()
},
completion: { finished in
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
self.dismiss(false)
}
}
)
}
@objc func buttonPressed(_ gestureRecognizer: UIGestureRecognizer) {
self.completionHandler?(true)
self.dismiss(true)
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
superview?.addGestureRecognizer(gestureRecognizer)
}
@objc func handleTap(_ gestureRecognizer: UIGestureRecognizer) {
dismiss(false)
}
}
| mpl-2.0 | 4dd699ee82640872bf1f619d6228d2b6 | 38.372881 | 135 | 0.644999 | 5.465882 | false | false | false | false |
migue1s/habitica-ios | HabitRPG/TableviewCells/SubscriptionOptionView.swift | 2 | 1115 | //
// SubscriptionOptionView.swift
// Habitica
//
// Created by Phillip Thelen on 07/02/2017.
// Copyright © 2017 Phillip Thelen. All rights reserved.
//
import UIKit
class SubscriptionOptionView: UITableViewCell {
//swiftlint:disable private_outlet
@IBOutlet weak var selectionView: UIImageView!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
//swiftlint:enable private_outlet
override func setSelected(_ selected: Bool, animated: Bool) {
let animDuration = 0.3
if selected {
UIView.animate(withDuration: animDuration, animations: {[weak self] () in
self?.selectionView.backgroundColor = .purple300()
self?.selectionView.image = #imageLiteral(resourceName: "circle_selected")
})
} else {
UIView.animate(withDuration: animDuration, animations: {[weak self] () in
self?.selectionView.backgroundColor = .purple600()
self?.selectionView.image = #imageLiteral(resourceName: "circle_unselected")
})
}
}
}
| gpl-3.0 | bd61c47cabd84fab983e55ab6ad21cf3 | 31.764706 | 92 | 0.645422 | 4.864629 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Nodes/Effects/Reverb/Flat Frequency Response Reverb/AKFlatFrequencyResponseReverb.swift | 1 | 4133 | //
// AKFlatFrequencyResponseReverb.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// This filter reiterates the input with an echo density determined by loop
/// time. The attenuation rate is independent and is determined by the
/// reverberation time (defined as the time in seconds for a signal to decay to
/// 1/1000, or 60dB down from its original amplitude). Output will begin to
/// appear immediately.
///
open class AKFlatFrequencyResponseReverb: AKNode, AKToggleable, AKComponent, AKInput {
public typealias AKAudioUnitType = AKFlatFrequencyResponseReverbAudioUnit
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(effect: "alps")
// MARK: - Properties
private var internalAU: AKAudioUnitType?
private var token: AUParameterObserverToken?
fileprivate var reverbDurationParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
@objc open dynamic var rampTime: Double = AKSettings.rampTime {
willSet {
internalAU?.rampTime = newValue
}
}
/// The duration in seconds for a signal to decay to 1/1000, or 60dB down from its original amplitude.
@objc open dynamic var reverbDuration: Double = 0.5 {
willSet {
if reverbDuration != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
reverbDurationParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.reverbDuration = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return internalAU?.isPlaying() ?? false
}
// MARK: - Initialization
/// Initialize this reverb node
///
/// - Parameters:
/// - input: Input node to process
/// - reverbDuration: The duration in seconds for a signal to decay to 1/1000,
/// or 60dB down from its original amplitude.
/// - loopDuration: The loop duration of the filter, in seconds. This can also be thought of as the
/// delay time or “echo density” of the reverberation.
///
@objc public init(
_ input: AKNode? = nil,
reverbDuration: Double = 0.5,
loopDuration: Double = 0.1) {
self.reverbDuration = reverbDuration
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioNode = avAudioUnit
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
input?.connect(to: self!)
if let au = self?.internalAU {
au.setLoopDuration(Float(loopDuration))
}
}
guard let tree = internalAU?.parameterTree else {
AKLog("Parameter Tree Failed")
return
}
reverbDurationParameter = tree["reverbDuration"]
token = tree.token(byAddingParameterObserver: { [weak self] _, _ in
guard let _ = self else {
AKLog("Unable to create strong reference to self")
return
} // Replace _ with strongSelf if needed
DispatchQueue.main.async {
// This node does not change its own values so we won't add any
// value observing, but if you need to, this is where that goes.
}
})
internalAU?.reverbDuration = Float(reverbDuration)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
| mit | b47bfdf83d229984c2d4d0107c374217 | 33.689076 | 106 | 0.616279 | 5.231939 | false | false | false | false |
SeaHub/ImgTagging | ImgTagger/ImgTagger/AuthenticationViewController.swift | 1 | 10340 | //
// AuthenticationViewController.swift
// ImgTagger
//
// Created by SeaHub on 2017/6/29.
// Copyright © 2017年 SeaCluster. All rights reserved.
//
import UIKit
import NotificationBannerSwift
import NVActivityIndicatorView
enum AMLoginSignupViewMode {
case login
case signup
}
class AuthenticationViewController: UIViewController {
let animationDuration = 0.25
var mode: AMLoginSignupViewMode = .signup
// MARK: - Constraints
@IBOutlet weak var backImageLeftConstraint: NSLayoutConstraint!
@IBOutlet weak var backImageBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var loginView: UIView!
@IBOutlet weak var loginContentView: UIView!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var loginButtonVerticalCenterConstraint: NSLayoutConstraint!
@IBOutlet weak var loginButtonTopConstraint: NSLayoutConstraint!
@IBOutlet weak var loginWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var signupView: UIView!
@IBOutlet weak var signupContentView: UIView!
@IBOutlet weak var signupButton: UIButton!
@IBOutlet weak var signupButtonVerticalCenterConstraint: NSLayoutConstraint!
@IBOutlet weak var signupButtonTopConstraint: NSLayoutConstraint!
@IBOutlet weak var logoView: UIView!
@IBOutlet weak var logoTopConstraint: NSLayoutConstraint!
@IBOutlet weak var logoHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var logoBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var logoButtomInSingupConstraint: NSLayoutConstraint!
@IBOutlet weak var logoCenterConstraint: NSLayoutConstraint!
@IBOutlet weak var forgotPassTopConstraint: NSLayoutConstraint!
@IBOutlet weak var socialsView: UIView!
@IBOutlet weak var loginEmailInputView: AMInputView!
@IBOutlet weak var loginPasswordInputView: AMInputView!
@IBOutlet weak var signupEmailInputView: AMInputView!
@IBOutlet weak var signupPasswordInputView: AMInputView!
@IBOutlet weak var signupPasswordConfirmInputView: AMInputView!
@IBOutlet weak var maskView: UIView!
@IBOutlet weak var sendVcodeButton: UIButton!
private var indicator: NVActivityIndicatorView! = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), type: .ballTrianglePath, color: .white, padding: nil)
// MARK: - controller
override func viewDidLoad() {
super.viewDidLoad()
configureIndicator()
toggleViewMode(animated: false)
NotificationCenter.default.addObserver(self, selector: #selector(keyboarFrameChange(notification:)), name: .UIKeyboardWillChangeFrame, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - button actions
@IBAction func loginButtonTouchUpInside(_ sender: AnyObject) {
if mode == .signup {
toggleViewMode(animated: true)
} else {
self.indicatorStartAnimating()
APIManager.login(username: loginEmailInputView.textFieldView.text!, password: loginPasswordInputView.textFieldView.text!, success: { (user) in
self.indicatorStopAnimating()
let homeViewController = ImgTaggerUtil.mainStoryborad.instantiateViewController(withIdentifier: ConstantStroyboardIdentifier.kHomeViewControllerIdentifier)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = homeViewController
UserDefaults.standard.setValue(user.token, forKey: AppConstant.kUserTokenIdentifier)
}) { (error) in
self.indicatorStopAnimating()
let banner = StatusBarNotificationBanner(title: "An error occurer, please retry later!", style: .danger)
banner.show()
}
}
}
@IBAction func signupButtonTouchUpInside(_ sender: AnyObject) {
if mode == .login {
toggleViewMode(animated: true)
} else {
self.indicatorStartAnimating()
APIManager.register(username: signupEmailInputView.textFieldView.text!, password: signupPasswordInputView.textFieldView.text!, email: nil, vcode: signupPasswordConfirmInputView.textFieldView.text!, success: {
self.indicatorStopAnimating()
self.toggleViewMode(animated: true)
}, failure: { (error) in
self.indicatorStopAnimating()
let banner = StatusBarNotificationBanner(title: "An error occurer, please retry later!", style: .danger)
banner.show()
})
}
}
// MARK: - toggle view
func toggleViewMode(animated:Bool){
mode = mode == .login ? .signup:.login
backImageLeftConstraint.constant = mode == .login ? 0 : -self.view.frame.size.width
loginWidthConstraint.isActive = mode == .signup ? true : false
logoCenterConstraint.constant = (mode == .login ? -1:1) * (loginWidthConstraint.multiplier * self.view.frame.size.width) / 2
loginButtonVerticalCenterConstraint.priority = mode == .login ? 300 : 900
signupButtonVerticalCenterConstraint.priority = mode == .signup ? 300 : 900
// animate
self.view.endEditing(true)
UIView.animate(withDuration:animated ? animationDuration:0) {
// animate constraints
self.view.layoutIfNeeded()
// hide or show views
self.loginContentView.alpha = self.mode == .login ? 1 : 0
self.signupContentView.alpha = self.mode == .signup ? 1 : 0
// rotate and scale login button
let scaleLogin: CGFloat = self.mode == .login ? 1 : 0.4
let rotateAngleLogin: CGFloat = self.mode == .login ? 0 : CGFloat(-CGFloat.pi / 2)
var transformLogin = CGAffineTransform(scaleX: scaleLogin, y: scaleLogin)
transformLogin = transformLogin.rotated(by: rotateAngleLogin)
self.loginButton.transform = transformLogin
// rotate and scale signup button
let scaleSignup:CGFloat = self.mode == .signup ? 1:0.4
let rotateAngleSignup:CGFloat = self.mode == .signup ? 0:CGFloat(-CGFloat.pi / 2)
var transformSignup = CGAffineTransform(scaleX: scaleSignup, y: scaleSignup)
transformSignup = transformSignup.rotated(by: rotateAngleSignup)
self.signupButton.transform = transformSignup
}
}
// MARK: - keyboard
func keyboarFrameChange(notification: NSNotification) {
let userInfo = notification.userInfo as! [String: AnyObject]
// get top of keyboard in view
let topOfKetboard = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue .origin.y
// get animation curve for animate view like keyboard animation
var animationDuration: TimeInterval = 0.25
var animationCurve: UIViewAnimationCurve = .easeOut
if let animDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber {
animationDuration = animDuration.doubleValue
}
if let animCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
animationCurve = UIViewAnimationCurve.init(rawValue: animCurve.intValue)!
}
// check keyboard is showing
let keyboardShow = topOfKetboard != self.view.frame.size.height
//hide logo in little devices
let hideLogo = self.view.frame.size.height < 667
// set constraints
backImageBottomConstraint.constant = self.view.frame.size.height - topOfKetboard
logoTopConstraint.constant = keyboardShow ? (hideLogo ? 0:20):50
logoHeightConstraint.constant = keyboardShow ? (hideLogo ? 0:40):60
logoBottomConstraint.constant = keyboardShow ? 20:32
logoButtomInSingupConstraint.constant = keyboardShow ? 20:32
forgotPassTopConstraint.constant = keyboardShow ? 30:45
loginButtonTopConstraint.constant = keyboardShow ? 25:30
signupButtonTopConstraint.constant = keyboardShow ? 23:35
loginButton.alpha = keyboardShow ? 1:0.7
signupButton.alpha = keyboardShow ? 1:0.7
// animate constraints changes
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(animationDuration)
UIView.setAnimationCurve(animationCurve)
self.view.layoutIfNeeded()
UIView.commitAnimations()
}
// MARK: - hide status bar
override var prefersStatusBarHidden: Bool {
return true
}
// MARK: - Custom
private func indicatorStartAnimating() {
UIView.animate(withDuration: 0.5) {
self.maskView.alpha = 0.5
}
}
private func indicatorStopAnimating() {
UIView.animate(withDuration: 0.5) {
self.maskView.alpha = 0
self.indicator.stopAnimating()
}
}
private func configureIndicator() {
self.indicator.center = CGPoint(x: self.view.bounds.width / 2, y: self.view.bounds.height / 2)
self.maskView.addSubview(self.indicator)
self.indicator.startAnimating()
}
@IBAction func sendVCodeButtonClicked(_ sender: Any) {
if mode == .login {
toggleViewMode(animated: true)
} else {
APIManager.getVCode(phone: signupEmailInputView.textFieldView.text!, success: {
self.indicatorStopAnimating()
self.sendVcodeButton.isHidden = true
}) { (error) in
self.indicatorStopAnimating()
let banner = StatusBarNotificationBanner(title: "An error occurer, please retry later!", style: .danger)
banner.show()
}
}
}
}
| gpl-3.0 | 8c13f6f6c31810446c7cd6b0a683218b | 39.537255 | 221 | 0.63858 | 5.434805 | false | false | false | false |
MegaBits/SelfieBits | SelfieBits/Stickers/StickerCellView.swift | 1 | 3369 | //
// StickerCellView.swift
// SelfieBits
//
// Created by Patrick Perini on 12/21/14.
// Copyright (c) 2014 megabits. All rights reserved.
//
import UIKit
class StickerCellView: UICollectionViewCell {
// MARK: Classes
internal struct Position {
var originalCenter: CGPoint = CGPointZero
var lastCenter: CGPoint = CGPointZero
var originalSuperView: UIView
var photoView: UIView
func overView(view: UIView?) -> Bool {
var viewFrame = self.photoView.convertRect(view?.frame ?? CGRectZero, fromView: view)
return CGRectContainsPoint(viewFrame, self.lastCenter)
}
}
// MARK: Properties
@IBOutlet var imageView: UIImageView?
var photoView: UIImageView?
private lazy var longPressGestureRecognizer: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressGestureRecognized:")
private var position: Position?
override func awakeFromNib() {
// Add long press gesture recognizer
self.longPressGestureRecognizer.allowableMovement = CGFloat.max
self.longPressGestureRecognizer.minimumPressDuration = 0.10
self.addGestureRecognizer(self.longPressGestureRecognizer)
}
func longPressGestureRecognized(gestureRecognizer: UIGestureRecognizer) {
switch (gestureRecognizer.state) {
case UIGestureRecognizerState.Began: // Pick up
var position = Position(originalCenter: self.center,
lastCenter: self.center,
originalSuperView: self.superview!,
photoView: self.photoView!)
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowRadius = 1.0
self.layer.shadowOpacity = 0.50
self.layer.shadowOffset = CGSizeZero
self.photoView?.addSubview(self)
self.transform = CGAffineTransformMakeScale(1.25, 1.25)
position.lastCenter = self.photoView!.convertPoint(self.center, fromView: position.originalSuperView)
self.center = position.lastCenter
self.position = position
case UIGestureRecognizerState.Changed: // Drag
if var position = self.position {
position.lastCenter = gestureRecognizer.locationInView(self.superview)
self.center = position.lastCenter
self.position = position
}
case UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled: // Put down
if var position = self.position {
self.transform = CGAffineTransformIdentity
self.center = position.originalCenter
position.originalSuperView.addSubview(self)
self.layer.shadowOpacity = 0.00
if position.overView(self.photoView) {
var newImageView: StickerView = StickerView(imageView: self.imageView!)
newImageView.center = position.lastCenter
self.photoView?.addSubview(newImageView)
}
self.position = nil
}
default:
break
}
}
} | mit | e680bd105861ddca1b53ab715a7c2806 | 36.032967 | 161 | 0.609676 | 5.962832 | false | false | false | false |
milseman/swift | test/stdlib/Renames.swift | 4 | 46302 | // RUN: %target-typecheck-verify-swift
func _Algorithm<I : IteratorProtocol, S : Sequence>(i: I, s: S) {
func fn1(_: EnumerateGenerator<I>) {} // expected-error {{'EnumerateGenerator' has been renamed to 'EnumeratedIterator'}} {{15-33=EnumeratedIterator}} {{none}}
func fn2(_: EnumerateSequence<S>) {} // expected-error {{'EnumerateSequence' has been renamed to 'EnumeratedSequence'}} {{15-32=EnumeratedSequence}} {{none}}
_ = EnumeratedIterator(i) // expected-error {{use the 'enumerated()' method on the sequence}} {{none}}
_ = EnumeratedSequence(s) // expected-error {{use the 'enumerated()' method on the sequence}} {{none}}
}
func _Arrays<T>(e: T) {
// _ = ContiguousArray(count: 1, repeatedValue: e) // xpected-error {{Please use init(repeating:count:) instead}} {{none}}
// _ = ArraySlice(count: 1, repeatedValue: e) // xpected-error {{Please use init(repeating:count:) instead}} {{none}}
// _ = Array(count: 1, repeatedValue: e) // xpected-error {{Please use init(repeating:count:) instead}} {{none}}
// The actual error is: {{argument 'repeatedValue' must precede argument 'count'}}
var a = ContiguousArray<T>()
_ = a.removeAtIndex(0) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}}
_ = a.replaceRange(0..<1, with: []) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange(_:with:)'}} {{9-21=replaceSubrange}} {{none}}
_ = a.appendContentsOf([]) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{9-25=append}} {{26-26=contentsOf: }} {{none}}
var b = ArraySlice<T>()
_ = b.removeAtIndex(0) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}}
_ = b.replaceRange(0..<1, with: []) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange(_:with:)'}} {{9-21=replaceSubrange}} {{none}}
_ = b.appendContentsOf([]) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{9-25=append}} {{26-26=contentsOf: }} {{none}}
var c = Array<T>()
_ = c.removeAtIndex(0) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}}
_ = c.replaceRange(0..<1, with: []) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange(_:with:)'}} {{9-21=replaceSubrange}} {{none}}
_ = c.appendContentsOf([]) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{9-25=append}} {{26-26=contentsOf: }} {{none}}
}
func _Builtin(o: AnyObject, oo: AnyObject?) {
_ = unsafeAddressOf(o) // expected-error {{Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.}} {{none}}
_ = unsafeAddress(of: o) // expected-error {{Removed in Swift 3. Use Unmanaged.passUnretained(x).toOpaque() instead.}} {{none}}
_ = unsafeUnwrap(oo) // expected-error {{Removed in Swift 3. Please use Optional.unsafelyUnwrapped instead.}} {{none}}
}
func _CString() {
_ = String.fromCString([]) // expected-error {{'fromCString' is unavailable: Please use String.init?(validatingUTF8:) instead. Note that it no longer accepts NULL as a valid input. Also consider using String(cString:), that will attempt to repair ill-formed code units.}} {{none}}
_ = String.fromCStringRepairingIllFormedUTF8([]) // expected-error {{'fromCStringRepairingIllFormedUTF8' is unavailable: Please use String.init(cString:) instead. Note that it no longer accepts NULL as a valid input. See also String.decodeCString if you need more control.}} {{none}}
}
func _CTypes<T>(x: Unmanaged<T>) {
func fn(_: COpaquePointer) {} // expected-error {{'COpaquePointer' has been renamed to 'OpaquePointer'}} {{14-28=OpaquePointer}} {{none}}
_ = OpaquePointer(bitPattern: x) // expected-error {{'init(bitPattern:)' is unavailable: use 'Unmanaged.toOpaque()' instead}} {{none}}
}
func _ClosedRange(x: ClosedRange<Int>) {
_ = x.startIndex // expected-error {{'startIndex' has been renamed to 'lowerBound'}} {{9-19=lowerBound}} {{none}}
_ = x.endIndex // expected-error {{'endIndex' has been renamed to 'upperBound'}} {{9-17=upperBound}} {{none}}
}
func _Collection() {
func fn(a: Bit) {} // expected-error {{'Bit' is unavailable: Bit enum has been removed. Please use Int instead.}} {{none}}
func fn<T>(b: IndexingGenerator<T>) {} // expected-error {{'IndexingGenerator' has been renamed to 'IndexingIterator'}} {{17-34=IndexingIterator}} {{none}}
func fn<T : CollectionType>(c: T) {} // expected-error {{'CollectionType' has been renamed to 'Collection'}} {{15-29=Collection}} {{none}}
func fn<T>(d: PermutationGenerator<T, T>) {} // expected-error {{'PermutationGenerator' is unavailable: PermutationGenerator has been removed in Swift 3}}
}
func _Collection<C : Collection>(c: C) {
func fn<T : Collection, U>(_: T, _: U) where T.Generator == U {} // expected-error {{'Generator' has been renamed to 'Iterator'}} {{50-59=Iterator}} {{none}}
_ = c.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}}
_ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}}
_ = c.split(1) { _ in return true} // expected-error {{split(maxSplits:omittingEmptySubsequences:whereSeparator:) instead}} {{none}}
}
func _Collection<C : Collection, E>(c: C, e: E) where C.Iterator.Element: Equatable, C.Iterator.Element == E {
_ = c.split(e) // expected-error {{'split(_:maxSplit:allowEmptySlices:)' is unavailable: Please use split(separator:maxSplits:omittingEmptySubsequences:) instead}} {{none}}
}
func _CollectionAlgorithms<C : MutableCollection, I>(c: C, i: I) where C : RandomAccessCollection, C.Index == I {
var c = c
_ = c.partition(i..<i) { _, _ in true } // expected-error {{slice the collection using the range, and call partition(by:)}} {{none}}
c.sortInPlace { _, _ in true } // expected-error {{'sortInPlace' has been renamed to 'sort(by:)'}} {{5-16=sort}} {{none}}
_ = c.partition { _, _ in true } // expected-error {{call partition(by:)}} {{none}}
}
func _CollectionAlgorithms<C : MutableCollection, I>(c: C, i: I) where C : RandomAccessCollection, C.Iterator.Element : Comparable, C.Index == I {
var c = c
_ = c.partition() // expected-error {{call partition(by:)}} {{none}}
_ = c.partition(i..<i) // expected-error {{slice the collection using the range, and call partition(by:)}} {{none}}
c.sortInPlace() // expected-error {{'sortInPlace()' has been renamed to 'sort()'}} {{5-16=sort}} {{none}}
}
func _CollectionAlgorithms<C : Collection, E>(c: C, e: E) where C.Iterator.Element : Equatable, C.Iterator.Element == E {
_ = c.indexOf(e) // expected-error {{'indexOf' has been renamed to 'index(of:)'}} {{9-16=index}} {{17-17=of: }} {{none}}
}
func _CollectionAlgorithms<C : Collection>(c: C) {
_ = c.indexOf { _ in true } // expected-error {{'indexOf' has been renamed to 'index(where:)'}} {{9-16=index}} {{none}}
}
func _CollectionAlgorithms<C : Sequence>(c: C) {
_ = c.sort { _, _ in true } // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{9-13=sorted}} {{none}}
_ = c.sort({ _, _ in true }) // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{9-13=sorted}} {{14-14=by: }} {{none}}
}
func _CollectionAlgorithms<C : Sequence>(c: C) where C.Iterator.Element : Comparable {
_ = c.sort() // expected-error {{'sort()' has been renamed to 'sorted()'}} {{9-13=sorted}} {{none}}
}
func _CollectionAlgorithms<C : MutableCollection>(c: C) {
_ = c.sort { _, _ in true } // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{9-13=sorted}} {{none}}
_ = c.sort({ _, _ in true }) // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{9-13=sorted}} {{14-14=by: }} {{none}}
}
func _CollectionAlgorithms<C : MutableCollection>(c: C) where C.Iterator.Element : Comparable {
_ = c.sort() // expected-error {{'sort()' has been renamed to 'sorted()'}} {{9-13=sorted}} {{none}}
var a: [Int] = [1,2,3]
var _: [Int] = a.sort() // expected-error {{'sort()' has been renamed to 'sorted()'}} {{20-24=sorted}} {{none}}
var _: [Int] = a.sort { _, _ in true } // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{20-24=sorted}} {{none}}
var _: [Int] = a.sort({ _, _ in true }) // expected-error {{'sort' has been renamed to 'sorted(by:)'}} {{20-24=sorted}} {{25-25=by: }} {{none}}
_ = a.sort() // OK, in `Void`able context, `sort()` is a renamed `sortInPlace()`.
_ = a.sort { _, _ in true } // OK, `Void`able context, `sort(by:)` is a renamed `sortInPlace(_:)`.
}
func _CollectionOfOne<T>(i: IteratorOverOne<T>) {
func fn(_: GeneratorOfOne<T>) {} // expected-error {{'GeneratorOfOne' has been renamed to 'IteratorOverOne'}} {{14-28=IteratorOverOne}} {{none}}
_ = i.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}}
}
func _CompilerProtocols() {
func fn(_: BooleanType) {} // expected-error {{'BooleanType' has been renamed to 'Bool'}} {{14-25=Bool}} {{none}}
}
func _EmptyCollection<T>(i: EmptyIterator<T>) {
func fn(_: EmptyGenerator<T>) {} // expected-error {{'EmptyGenerator' has been renamed to 'EmptyIterator'}} {{14-28=EmptyIterator}} {{none}}
_ = i.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}}
}
func _ErrorType() {
func fn(_: ErrorType) {} // expected-error {{'ErrorType' has been renamed to 'Error'}} {{14-23=Error}}
}
func _ExistentialCollection<T>(i: AnyIterator<T>) {
func fn1<T>(_: AnyGenerator<T>) {} // expected-error {{'AnyGenerator' has been renamed to 'AnyIterator'}} {{18-30=AnyIterator}} {{none}}
func fn2<T : AnyCollectionType>(_: T) {} // expected-error {{'AnyCollectionType' has been renamed to '_AnyCollectionProtocol'}} {{16-33=_AnyCollectionProtocol}} {{none}}
func fn3(_: AnyForwardIndex) {} // expected-error {{'AnyForwardIndex' has been renamed to 'AnyIndex'}} {{15-30=AnyIndex}} {{none}}
func fn4(_: AnyBidirectionalIndex) {} // expected-error {{'AnyBidirectionalIndex' has been renamed to 'AnyIndex'}} {{15-36=AnyIndex}} {{none}}
func fn5(_: AnyRandomAccessIndex) {} // expected-error {{'AnyRandomAccessIndex' has been renamed to 'AnyIndex'}} {{15-35=AnyIndex}} {{none}}
_ = anyGenerator(i) // expected-error {{'anyGenerator' has been replaced by 'AnyIterator.init(_:)'}} {{7-19=AnyIterator}} {{none}}
_ = anyGenerator { i.next() } // expected-error {{'anyGenerator' has been replaced by 'AnyIterator.init(_:)'}} {{7-19=AnyIterator}} {{none}}
}
func _ExistentialCollection<T>(s: AnySequence<T>) {
_ = s.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}}
}
func _ExistentialCollection<T>(c: AnyCollection<T>) {
_ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}}
}
func _ExistentialCollection<T>(c: AnyBidirectionalCollection<T>) {
_ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}}
}
func _ExistentialCollection<T>(c: AnyRandomAccessCollection<T>) {
_ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}}
}
func _ExistentialCollection<C : _AnyCollectionProtocol>(c: C) {
_ = c.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}}
}
func _Filter() {
func fn<T>(_: LazyFilterGenerator<T>) {} // expected-error {{'LazyFilterGenerator' has been renamed to 'LazyFilterIterator'}} {{17-36=LazyFilterIterator}} {{none}}
}
func _Filter<I : IteratorProtocol>(i: I) {
_ = LazyFilterIterator(i) { _ in true } // expected-error {{'init(_:whereElementsSatisfy:)' is unavailable: use '.lazy.filter' on the sequence}}
}
func _Filter<S : Sequence>(s: S) {
_ = LazyFilterSequence(s) { _ in true } // expected-error {{'init(_:whereElementsSatisfy:)' is unavailable: use '.lazy.filter' on the sequence}}
}
func _Filter<S>(s: LazyFilterSequence<S>) {
_ = s.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}}
}
func _Filter<C : Collection>(c: C) {
_ = LazyFilterCollection(c) { _ in true} // expected-error {{'init(_:whereElementsSatisfy:)' is unavailable: use '.lazy.filter' on the collection}}
}
func _Filter<C>(c: LazyFilterCollection<C>) {
_ = c.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}}
}
func _Flatten() {
func fn<T>(i: FlattenGenerator<T>) {} // expected-error {{'FlattenGenerator' has been renamed to 'FlattenIterator'}} {{17-33=FlattenIterator}} {{none}}
}
func _Flatten<T>(s: FlattenSequence<T>) {
_ = s.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}}
}
func _Flatten<T>(c: FlattenCollection<T>) {
_ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}}
}
func _Flatten<T>(c: FlattenBidirectionalCollection<T>) {
_ = c.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}}
}
func _FloatingPoint() {
func fn<F : FloatingPointType>(f: F) {} // expected-error {{'FloatingPointType' has been renamed to 'FloatingPoint'}} {{15-32=FloatingPoint}} {{none}}
}
func _FloatingPoint<F : BinaryFloatingPoint>(f: F) {
_ = f.isSignaling // expected-error {{'isSignaling' has been renamed to 'isSignalingNaN'}} {{9-20=isSignalingNaN}} {{none}}
}
func _FloatingPointTypes() {
var x: Float = 1, y: Float = 1
x += 1
y += 1
// FIXME: isSignMinus -> sign is OK? different type.
_ = x.isSignMinus // expected-error {{'isSignMinus' has been renamed to 'sign'}} {{9-20=sign}} {{none}}
_ = x % y // expected-error {{'%' is unavailable: Use truncatingRemainder instead}} {{none}}
x %= y // expected-error {{'%=' is unavailable: Use formTruncatingRemainder instead}} {{none}}
++x // expected-error {{'++' is unavailable: it has been removed in Swift 3}} {{3-5=}} {{6-6= += 1}} {{none}}
--x // expected-error {{'--' is unavailable: it has been removed in Swift 3}} {{3-5=}} {{6-6= -= 1}} {{none}}
x++ // expected-error {{'++' is unavailable: it has been removed in Swift 3}} {{4-6= += 1}} {{none}}
x-- // expected-error {{'--' is unavailable: it has been removed in Swift 3}} {{4-6= -= 1}} {{none}}
}
func _HashedCollection<T>(x: Set<T>, i: Set<T>.Index, e: T) {
var x = x
_ = x.removeAtIndex(i) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}}
_ = x.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}}
_ = x.indexOf(e) // expected-error {{'indexOf' has been renamed to 'index(of:)'}} {{9-16=index}} {{17-17=of: }} {{none}}
}
func _HashedCollection<K, V>(x: Dictionary<K, V>, i: Dictionary<K, V>.Index, k: K) {
var x = x
_ = x.removeAtIndex(i) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}}
_ = x.indexForKey(k) // expected-error {{'indexForKey' has been renamed to 'index(forKey:)'}} {{9-20=index}} {{21-21=forKey: }} {{none}}
_ = x.removeValueForKey(k) // expected-error {{'removeValueForKey' has been renamed to 'removeValue(forKey:)'}} {{9-26=removeValue}} {{27-27=forKey: }} {{none}}
_ = x.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}}
}
func _ImplicitlyUnwrappedOptional<T>(x: ImplicitlyUnwrappedOptional<T>) {
_ = ImplicitlyUnwrappedOptional<T>() // expected-error {{'init()' is unavailable: Please use nil literal instead.}} {{none}}
_ = ImplicitlyUnwrappedOptional<T>.map(x)() { _ in true } // expected-error {{'map' is unavailable: Has been removed in Swift 3.}}
_ = ImplicitlyUnwrappedOptional<T>.flatMap(x)() { _ in true } // expected-error {{'flatMap' is unavailable: Has been removed in Swift 3.}}
// FIXME: No way to call map and flatMap as method?
// _ = (x as ImplicitlyUnwrappedOptional).map { _ in true } // xpected-error {{}} {{none}}
// _ = (x as ImplicitlyUnwrappedOptional).flatMap { _ in true } // xpected-error {{}} {{none}}
}
func _Index<T : _Incrementable>(i: T) {
var i = i
--i // expected-error {{'--' is unavailable: it has been removed in Swift 3}} {{3-5=}} {{6-6= = i.predecessor()}} {{none}}
i-- // expected-error {{'--' is unavailable: it has been removed in Swift 3}} {{4-6= = i.predecessor()}} {{none}}
++i // expected-error {{'++' is unavailable: it has been removed in Swift 3}} {{3-5=}} {{6-6= = i.successor()}} {{none}}
i++ // expected-error {{'++' is unavailable: it has been removed in Swift 3}} {{4-6= = i.successor()}} {{none}}
}
func _Index() {
func fn1<T : ForwardIndexType>(_: T) {} // expected-error {{'ForwardIndexType' has been renamed to 'Comparable'}} {{16-32=Comparable}} {{none}}
func fn2<T : BidirectionalIndexType>(_: T) {} // expected-error {{'BidirectionalIndexType' has been renamed to 'Comparable'}} {{16-38=Comparable}} {{none}}
func fn3<T : RandomAccessIndexType>(_: T) {} // expected-error {{'RandomAccessIndexType' has been renamed to 'Strideable'}} {{16-37=Strideable}} {{none}}
}
func _InputStream() {
_ = readLine(stripNewline: true) // expected-error {{'readLine(stripNewline:)' has been renamed to 'readLine(strippingNewline:)'}} {{7-15=readLine}} {{16-28=strippingNewline}} {{none}}
_ = readLine() // ok
}
func _Join() {
func fn<T>(_: JoinGenerator<T>) {} // expected-error {{'JoinGenerator' has been renamed to 'JoinedIterator'}} {{17-30=JoinedIterator}} {{none}}
}
func _Join<T>(s: JoinedSequence<T>) {
_ = s.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}}
}
func _Join<S : Sequence>(s: S) where S.Iterator.Element : Sequence {
_ = s.joinWithSeparator(s) // expected-error {{'joinWithSeparator' has been renamed to 'joined(separator:)'}} {{9-26=joined}} {{27-27=separator: }} {{none}}
}
func _LazyCollection() {
func fn<T : LazyCollectionType>(_: T) {} // expected-error {{'LazyCollectionType' has been renamed to 'LazyCollectionProtocol'}} {{15-33=LazyCollectionProtocol}} {{none}}
}
func _LazySequence() {
func fn<T : LazySequenceType>(_: T) {} // expected-error {{'LazySequenceType' has been renamed to 'LazySequenceProtocol'}} {{15-31=LazySequenceProtocol}} {{none}}
}
func _LazySequence<S : LazySequenceProtocol>(s: S) {
_ = s.array // expected-error {{'array' is unavailable: Please use Array initializer instead.}} {{none}}
}
func _LifetimeManager<T>(x: T) {
var x = x
_ = withUnsafeMutablePointer(&x) { _ in } // expected-error {{'withUnsafeMutablePointer' has been renamed to 'withUnsafeMutablePointer(to:_:)'}} {{7-31=withUnsafeMutablePointer}} {{32-32=to: }} {{none}}
_ = withUnsafeMutablePointers(&x, &x) { _, _ in } // expected-error {{'withUnsafeMutablePointers' is unavailable: use nested withUnsafeMutablePointer(to:_:) instead}} {{none}}
_ = withUnsafeMutablePointers(&x, &x, &x) { _, _, _ in } // expected-error {{'withUnsafeMutablePointers' is unavailable: use nested withUnsafeMutablePointer(to:_:) instead}} {{none}}
_ = withUnsafePointer(&x) { _ in } // expected-error {{'withUnsafePointer' has been renamed to 'withUnsafePointer(to:_:)'}} {7-24=withUnsafePointer}} {{25-25=to: }} {{none}}
_ = withUnsafePointers(&x, &x) { _, _ in } // expected-error {{'withUnsafePointers' is unavailable: use nested withUnsafePointer(to:_:) instead}} {{none}}
_ = withUnsafePointers(&x, &x, &x) { _, _, _ in } // expected-error {{'withUnsafePointers' is unavailable: use nested withUnsafePointer(to:_:) instead}} {{none}}
}
func _ManagedBuffer<H, E>(x: ManagedBufferPointer<H, E>, h: H, bc: AnyClass) {
_ = x.allocatedElementCount // expected-error {{'allocatedElementCount' has been renamed to 'capacity'}} {{9-30=capacity}} {{none}}
_ = ManagedBuffer<H, E>.create(1) { _ in h } // expected-error {{'create(_:initialValue:)' has been renamed to 'create(minimumCapacity:makingHeaderWith:)'}} {{27-33=create}} {{34-34=minimumCapacity: }} {{none}}
_ = ManagedBuffer<H, E>.create(1, initialValue: { _ in h }) // expected-error {{'create(_:initialValue:)' has been renamed to 'create(minimumCapacity:makingHeaderWith:)'}} {{27-33=create}} {{34-34=minimumCapacity: }} {{37-49=makingHeaderWith}} {{none}}
_ = ManagedBufferPointer<H, E>(bufferClass: bc, minimumCapacity: 1, initialValue: { _, _ in h }) // expected-error {{'init(bufferClass:minimumCapacity:initialValue:)' has been renamed to 'init(bufferClass:minimumCapacity:makingHeaderWith:)'}} {{71-83=makingHeaderWith}} {{none}}
_ = ManagedBufferPointer<H, E>(bufferClass: bc, minimumCapacity: 1) { _, _ in h } // OK
func fn(_: ManagedProtoBuffer<H, E>) {} // expected-error {{'ManagedProtoBuffer' has been renamed to 'ManagedBuffer'}} {{14-32=ManagedBuffer}} {{none}}
}
func _Map() {
func fn<B, E>(_: LazyMapGenerator<B, E>) {} // expected-error {{'LazyMapGenerator' has been renamed to 'LazyMapIterator'}} {{20-36=LazyMapIterator}} {{none}}
}
func _Map<S : Sequence>(s: S) {
_ = LazyMapSequence(s) { _ in true } // expected-error {{'init(_:transform:)' is unavailable: use '.lazy.map' on the sequence}} {{none}}
}
func _Map<C : Collection>(c: C) {
_ = LazyMapCollection(c) { _ in true } // expected-error {{'init(_:transform:)' is unavailable: use '.lazy.map' on the collection}} {{none}}
}
func _MemoryLayout<T>(t: T) {
_ = sizeof(T.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{15-21=>.size}} {{none}}
_ = alignof(T.self) // expected-error {{'alignof' is unavailable: use MemoryLayout<T>.alignment instead.}} {{7-15=MemoryLayout<}} {{16-22=>.alignment}} {{none}}
_ = strideof(T.self) // expected-error {{'strideof' is unavailable: use MemoryLayout<T>.stride instead.}} {{7-16=MemoryLayout<}} {{17-23=>.stride}} {{none}}
_ = sizeofValue(t) // expected-error {{'sizeofValue' has been replaced by 'MemoryLayout.size(ofValue:)'}} {{7-18=MemoryLayout.size}} {{19-19=ofValue: }} {{none}}
_ = alignofValue(t) // expected-error {{'alignofValue' has been replaced by 'MemoryLayout.alignment(ofValue:)'}} {{7-19=MemoryLayout.alignment}} {{20-20=ofValue: }} {{none}}
_ = strideofValue(t) // expected-error {{'strideofValue' has been replaced by 'MemoryLayout.stride(ofValue:)'}} {{7-20=MemoryLayout.stride}} {{21-21=ofValue: }} {{none}}
}
func _Mirror() {
func fn<M : MirrorPathType>(_: M) {} // expected-error {{'MirrorPathType' has been renamed to 'MirrorPath'}} {{15-29=MirrorPath}} {{none}}
}
func _MutableCollection() {
func fn1<C : MutableCollectionType>(_: C) {} // expected-error {{'MutableCollectionType' has been renamed to 'MutableCollection'}} {{16-37=MutableCollection}} {{none}}
func fn2<C : MutableSliceable>(_: C) {} // expected-error {{'MutableSliceable' is unavailable: Please use 'Collection where SubSequence : MutableCollection'}} {{none}}
}
func _OptionSet() {
func fn<O : OptionSetType>(_: O) {} // expected-error {{'OptionSetType' has been renamed to 'OptionSet'}} {{15-28=OptionSet}} {{none}}
}
func _Optional<T>(x: T) {
_ = Optional<T>.None // expected-error {{'None' has been renamed to 'none'}} {{19-23=none}} {{none}}
_ = Optional<T>.Some(x) // expected-error {{'Some' has been renamed to 'some'}} {{19-23=some}} {{none}}
}
func _TextOutputStream() {
func fn<S : OutputStreamType>(_: S) {} // expected-error {{'OutputStreamType' has been renamed to 'TextOutputStream'}} {{15-31=TextOutputStream}} {{none}}
}
func _TextOutputStream<S : TextOutputStreamable, O : TextOutputStream>(s: S, o: O) {
var o = o
s.writeTo(&o) // expected-error {{'writeTo' has been renamed to 'write(to:)'}} {{5-12=write}} {{13-13=to: }} {{none}}
}
func _Print<T, O : TextOutputStream>(x: T, out: O) {
var out = out
print(x, toStream: &out) // expected-error {{'print(_:separator:terminator:toStream:)' has been renamed to 'print(_:separator:terminator:to:)'}} {{3-8=print}} {{12-20=to}} {{none}}
print(x, x, separator: "/", toStream: &out) // expected-error {{'print(_:separator:terminator:toStream:)' has been renamed to 'print(_:separator:terminator:to:)'}} {{3-8=print}} {{31-39=to}} {{none}}
print(terminator: "|", toStream: &out) // expected-error {{'print(_:separator:terminator:toStream:)' has been renamed to 'print(_:separator:terminator:to:)'}} {{3-8=print}} {{26-34=to}} {{none}}
print(x, separator: "*", terminator: "$", toStream: &out) // expected-error {{'print(_:separator:terminator:toStream:)' has been renamed to 'print(_:separator:terminator:to:)'}} {{3-8=print}} {{45-53=to}} {{none}}
debugPrint(x, toStream: &out) // expected-error {{'debugPrint(_:separator:terminator:toStream:)' has been renamed to 'debugPrint(_:separator:terminator:to:)'}} {{3-13=debugPrint}} {{17-25=to}} {{none}}
}
func _Print<T>(x: T) {
print(x, appendNewline: true) // expected-error {{'print(_:appendNewline:)' is unavailable: Please use 'terminator: ""' instead of 'appendNewline: false': 'print((...), terminator: "")'}} {{none}}
debugPrint(x, appendNewline: true) // expected-error {{'debugPrint(_:appendNewline:)' is unavailable: Please use 'terminator: ""' instead of 'appendNewline: false': 'debugPrint((...), terminator: "")'}} {{none}}
}
func _Print<T, O : TextOutputStream>(x: T, o: O) {
// FIXME: Not working due to <rdar://22101775>
//var o = o
//print(x, &o) // xpected-error {{}} {{none}}
//debugPrint(x, &o) // xpected-error {{}} {{none}}
//print(x, &o, appendNewline: true) // xpected-error {{}} {{none}}
//debugPrint(x, &o, appendNewline: true) // xpected-error {{}} {{none}}
}
func _Range() {
func fn1<B>(_: RangeGenerator<B>) {} // expected-error {{'RangeGenerator' has been renamed to 'IndexingIterator'}} {{18-32=IndexingIterator}} {{none}}
func fn2<I : IntervalType>(_: I) {} // expected-error {{'IntervalType' is unavailable: IntervalType has been removed in Swift 3. Use ranges instead.}} {{none}}
func fn3<B>(_: HalfOpenInterval<B>) {} // expected-error {{'HalfOpenInterval' has been renamed to 'Range'}} {{18-34=Range}} {{none}}
func fn4<B>(_: ClosedInterval<B>) {} // expected-error {{'ClosedInterval' has been renamed to 'ClosedRange'}} {{18-32=ClosedRange}} {{none}}
}
func _Range<T>(r: Range<T>) {
_ = r.startIndex // expected-error {{'startIndex' has been renamed to 'lowerBound'}} {{9-19=lowerBound}} {{none}}
_ = r.endIndex // expected-error {{'endIndex' has been renamed to 'upperBound'}} {{9-17=upperBound}} {{none}}
}
func _Range<T>(r: ClosedRange<T>) {
_ = r.clamp(r) // expected-error {{'clamp' is unavailable: Call clamped(to:) and swap the argument and the receiver. For example, x.clamp(y) becomes y.clamped(to: x) in Swift 3.}} {{none}}
}
func _Range<T>(r: CountableClosedRange<T>) {
_ = r.clamp(r) // expected-error {{'clamp' is unavailable: Call clamped(to:) and swap the argument and the receiver. For example, x.clamp(y) becomes y.clamped(to: x) in Swift 3.}} {{none}}
}
func _RangeReplaceableCollection() {
func fn<I : RangeReplaceableCollectionType>(_: I) {} // expected-error {{'RangeReplaceableCollectionType' has been renamed to 'RangeReplaceableCollection'}} {{15-45=RangeReplaceableCollection}} {{none}}
}
func _RangeReplaceableCollection<C : RangeReplaceableCollection>(c: C, i: C.Index) {
var c = c
c.replaceRange(i..<i, with: []) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange(_:with:)'}} {{5-17=replaceSubrange}} {{none}}
_ = c.removeAtIndex(i) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}}
c.removeRange(i..<i) // expected-error {{'removeRange' has been renamed to 'removeSubrange'}} {{5-16=removeSubrange}} {{none}}
c.appendContentsOf([]) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{5-21=append}} {{22-22=contentsOf: }} {{none}}
c.insertContentsOf(c, at: i) // expected-error {{'insertContentsOf(_:at:)' has been renamed to 'insert(contentsOf:at:)'}} {{5-21=insert}} {{22-22=contentsOf: }} {{none}}
}
func _Reflection(x: ObjectIdentifier) {
_ = x.uintValue // expected-error {{'uintValue' is unavailable: use the 'UInt(_:)' initializer}} {{none}}
}
func _Repeat() {
func fn<E>(_: Repeat<E>) {} // expected-error {{'Repeat' has been renamed to 'Repeated'}} {{17-23=Repeated}} {{none}}
}
func _Repeat<E>(e: E) {
_ = Repeated(count: 0, repeatedValue: e) // expected-error {{'init(count:repeatedValue:)' is unavailable: Please use repeatElement(_:count:) function instead}} {{none}}
}
func _Reverse<C : BidirectionalCollection>(c: C) {
_ = ReverseCollection(c) // expected-error {{'ReverseCollection' has been renamed to 'ReversedCollection'}} {{7-24=ReversedCollection}} {{none}}
_ = ReversedCollection(c) // expected-error {{'init' has been replaced by instance method 'BidirectionalCollection.reversed()'}} {{7-25=c.reversed}} {{26-27=}} {{none}}
_ = c.reverse() // expected-error {{'reverse()' has been renamed to 'reversed()'}} {{9-16=reversed}} {{none}}
}
func _Reverse<C : RandomAccessCollection>(c: C) {
_ = ReverseRandomAccessCollection(c) // expected-error {{'ReverseRandomAccessCollection' has been renamed to 'ReversedRandomAccessCollection'}} {{7-36=ReversedRandomAccessCollection}} {{none}}
_ = ReversedRandomAccessCollection(c) // expected-error {{'init' has been replaced by instance method 'RandomAccessCollection.reversed()'}} {{7-37=c.reversed}} {{38-39=}} {{none}}
_ = c.reverse() // expected-error {{'reverse()' has been renamed to 'reversed()'}} {{9-16=reversed}} {{none}}
}
func _Reverse<C : LazyCollectionProtocol>(c: C) where C : BidirectionalCollection, C.Elements : BidirectionalCollection {
_ = c.reverse() // expected-error {{'reverse()' has been renamed to 'reversed()'}} {{9-16=reversed}} {{none}}
}
func _Reverse<C : LazyCollectionProtocol>(c: C) where C : RandomAccessCollection, C.Elements : RandomAccessCollection {
_ = c.reverse() // expected-error {{'reverse()' has been renamed to 'reversed()'}} {{9-16=reversed}} {{none}}
}
func _Sequence() {
func fn1<G : GeneratorType>(_: G) {} // expected-error {{'GeneratorType' has been renamed to 'IteratorProtocol'}} {{16-29=IteratorProtocol}} {{none}}
func fn2<S : SequenceType>(_: S) {} // expected-error {{'SequenceType' has been renamed to 'Sequence'}} {{16-28=Sequence}} {{none}}
func fn3<I : IteratorProtocol>(_: GeneratorSequence<I>) {} // expected-error {{'GeneratorSequence' has been renamed to 'IteratorSequence'}} {{37-54=IteratorSequence}} {{none}}
}
func _Sequence<S : Sequence>(s: S) {
_ = s.generate() // expected-error {{'generate()' has been renamed to 'makeIterator()'}} {{9-17=makeIterator}} {{none}}
_ = s.underestimateCount() // expected-error {{'underestimateCount()' has been replaced by 'underestimatedCount'}} {{9-27=underestimatedCount}} {{27-29=}} {{none}}
_ = s.split(1, allowEmptySlices: true) { _ in true } // expected-error {{'split(_:allowEmptySlices:isSeparator:)' is unavailable: call 'split(maxSplits:omittingEmptySubsequences:whereSeparator:)' and invert the 'allowEmptySlices' argument}} {{none}}
}
func _Sequence<S : Sequence>(s: S, e: S.Iterator.Element) where S.Iterator.Element : Equatable {
_ = s.split(e, maxSplit: 1, allowEmptySlices: true) // expected-error {{'split(_:maxSplit:allowEmptySlices:)' is unavailable: call 'split(separator:maxSplits:omittingEmptySubsequences:)' and invert the 'allowEmptySlices' argument}} {{none}}
}
func _SequenceAlgorithms<S : Sequence>(x: S) {
_ = x.enumerate() // expected-error {{'enumerate()' has been renamed to 'enumerated()'}} {{9-18=enumerated}} {{none}}
_ = x.minElement { _, _ in true } // expected-error {{'minElement' has been renamed to 'min(by:)'}} {{9-19=min}} {{none}}
_ = x.maxElement { _, _ in true } // expected-error {{'maxElement' has been renamed to 'max(by:)'}} {{9-19=max}} {{none}}
_ = x.reverse() // expected-error {{'reverse()' has been renamed to 'reversed()'}} {{9-16=reversed}} {{none}}
_ = x.startsWith([]) { _ in true } // expected-error {{'startsWith(_:isEquivalent:)' has been renamed to 'starts(with:by:)'}} {{9-19=starts}} {{20-20=with: }} {{none}}
_ = x.elementsEqual([], isEquivalent: { _, _ in true }) // expected-error {{'elementsEqual(_:isEquivalent:)' has been renamed to 'elementsEqual(_:by:)'}} {{9-22=elementsEqual}} {{27-39=by}} {{none}}
_ = x.elementsEqual([]) { _, _ in true } // OK
_ = x.lexicographicalCompare([]) { _, _ in true } // expected-error {{'lexicographicalCompare(_:isOrderedBefore:)' has been renamed to 'lexicographicallyPrecedes(_:by:)'}} {{9-31=lexicographicallyPrecedes}}{{none}}
_ = x.contains({ _ in true }) // expected-error {{'contains' has been renamed to 'contains(where:)'}} {{9-17=contains}} {{18-18=where: }} {{none}}
_ = x.contains { _ in true } // OK
_ = x.reduce(1, combine: { _, _ in 1 }) // expected-error {{'reduce(_:combine:)' has been renamed to 'reduce(_:_:)'}} {{9-15=reduce}} {{19-28=}} {{none}}
_ = x.reduce(1) { _, _ in 1 } // OK
}
func _SequenceAlgorithms<S : Sequence>(x: S) where S.Iterator.Element : Comparable {
_ = x.minElement() // expected-error {{'minElement()' has been renamed to 'min()'}} {{9-19=min}} {{none}}
_ = x.maxElement() // expected-error {{'maxElement()' has been renamed to 'max()'}} {{9-19=max}} {{none}}
_ = x.startsWith([]) // expected-error {{'startsWith' has been renamed to 'starts(with:)'}} {{9-19=starts}} {{20-20=with: }} {{none}}
_ = x.lexicographicalCompare([]) // expected-error {{'lexicographicalCompare' has been renamed to 'lexicographicallyPrecedes'}} {{9-31=lexicographicallyPrecedes}}{{none}}
}
func _SetAlgebra() {
func fn<S : SetAlgebraType>(_: S) {} // expected-error {{'SetAlgebraType' has been renamed to 'SetAlgebra'}} {{15-29=SetAlgebra}} {{none}}
}
func _SetAlgebra<S : SetAlgebra>(s: S) {
var s = s
_ = s.intersect(s) // expected-error {{'intersect' has been renamed to 'intersection(_:)'}} {{9-18=intersection}} {{none}}
_ = s.exclusiveOr(s) // expected-error {{'exclusiveOr' has been renamed to 'symmetricDifference(_:)'}} {{9-20=symmetricDifference}} {{none}}
s.unionInPlace(s) // expected-error {{'unionInPlace' has been renamed to 'formUnion(_:)'}} {{5-17=formUnion}} {{none}}
s.intersectInPlace(s) // expected-error {{'intersectInPlace' has been renamed to 'formIntersection(_:)'}} {{5-21=formIntersection}} {{none}}
s.exclusiveOrInPlace(s) // expected-error {{'exclusiveOrInPlace' has been renamed to 'formSymmetricDifference(_:)'}} {{5-23=formSymmetricDifference}} {{none}}
_ = s.isSubsetOf(s) // expected-error {{'isSubsetOf' has been renamed to 'isSubset(of:)'}} {{9-19=isSubset}} {{20-20=of: }} {{none}}
_ = s.isDisjointWith(s) // expected-error {{'isDisjointWith' has been renamed to 'isDisjoint(with:)'}} {{9-23=isDisjoint}} {{24-24=with: }} {{none}}
s.subtractInPlace(s) // expected-error {{'subtractInPlace' has been renamed to 'subtract(_:)'}} {{5-20=subtract}} {{none}}
_ = s.isStrictSupersetOf(s) // expected-error {{'isStrictSupersetOf' has been renamed to 'isStrictSuperset(of:)'}} {{9-27=isStrictSuperset}} {{28-28=of: }} {{none}}
_ = s.isStrictSubsetOf(s) // expected-error {{'isStrictSubsetOf' has been renamed to 'isStrictSubset(of:)'}} {{9-25=isStrictSubset}} {{26-26=of: }} {{none}}
}
func _StaticString(x: StaticString) {
_ = x.byteSize // expected-error {{'byteSize' has been renamed to 'utf8CodeUnitCount'}} {{9-17=utf8CodeUnitCount}} {{none}}
_ = x.stringValue // expected-error {{'stringValue' is unavailable: use the 'String(_:)' initializer}} {{none}}
}
func _Stride<T : Strideable>(x: T, d: T.Stride) {
func fn1<T>(_: StrideToGenerator<T>) {} // expected-error {{'StrideToGenerator' has been renamed to 'StrideToIterator'}} {{18-35=StrideToIterator}} {{none}}
func fn2<T>(_: StrideThroughGenerator<T>) {} // expected-error {{'StrideThroughGenerator' has been renamed to 'StrideThroughIterator'}} {{18-40=StrideThroughIterator}} {{none}}
_ = x.stride(to: x, by: d) // expected-error {{'stride(to:by:)' is unavailable: Use stride(from:to:by:) free function instead}} {{none}}
_ = x.stride(through: x, by: d) // expected-error {{'stride(through:by:)' is unavailable: Use stride(from:through:by:) free function instead}}
}
func _String<S, C>(x: String, s: S, c: C, i: String.Index)
where S : Sequence, S.Iterator.Element == Character, C : Collection, C.Iterator.Element == Character {
var x = x
x.appendContentsOf(x) // expected-error {{'appendContentsOf' has been renamed to 'append(_:)'}} {{5-21=append}} {{none}}
x.appendContentsOf(s) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{5-21=append}} {{22-22=contentsOf: }} {{none}}
x.insertContentsOf(c, at: i) // expected-error {{'insertContentsOf(_:at:)' has been renamed to 'insert(contentsOf:at:)'}} {{5-21=insert}} {{22-22=contentsOf: }} {{none}}
x.replaceRange(i..<i, with: c) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange'}} {{5-17=replaceSubrange}} {{none}}
x.replaceRange(i..<i, with: x) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange'}} {{5-17=replaceSubrange}} {{none}}
_ = x.removeAtIndex(i) // expected-error {{'removeAtIndex' has been renamed to 'remove(at:)'}} {{9-22=remove}} {{23-23=at: }} {{none}}
x.removeRange(i..<i) // expected-error {{'removeRange' has been renamed to 'removeSubrange'}} {{5-16=removeSubrange}} {{none}}
_ = x.lowercaseString // expected-error {{'lowercaseString' has been renamed to 'lowercased()'}} {{9-24=lowercased()}} {{none}}
_ = x.uppercaseString // expected-error {{'uppercaseString' has been renamed to 'uppercased()'}} {{9-24=uppercased()}} {{none}}
// FIXME: SR-1649 <rdar://problem/26563343>; We should suggest to add '()'
}
func _String<S : Sequence>(s: S, sep: String) where S.Iterator.Element == String {
_ = s.joinWithSeparator(sep) // expected-error {{'joinWithSeparator' has been renamed to 'joined(separator:)'}} {{9-26=joined}} {{27-27=separator: }} {{none}}
}
func _StringCharacterView<S, C>(x: String, s: S, c: C, i: String.Index)
where S : Sequence, S.Iterator.Element == Character, C : Collection, C.Iterator.Element == Character {
var x = x
x.replaceRange(i..<i, with: c) // expected-error {{'replaceRange(_:with:)' has been renamed to 'replaceSubrange'}} {{5-17=replaceSubrange}} {{none}}
x.appendContentsOf(s) // expected-error {{'appendContentsOf' has been renamed to 'append(contentsOf:)'}} {{5-21=append}} {{22-22=contentsOf: }} {{none}}
}
func _StringAppend(s: inout String, u: UnicodeScalar) {
s.append(u) // expected-error {{'append' is unavailable: Replaced by append(_: String)}} {{none}}
}
func _StringLegacy(c: Character, u: UnicodeScalar) {
_ = String(count: 1, repeatedValue: c) // expected-error {{'init(count:repeatedValue:)' is unavailable: Renamed to init(repeating:count:) and reordered parameters}} {{none}}
_ = String(count: 1, repeatedValue: u) // expected-error {{'init(count:repeatedValue:)' is unavailable: Renamed to init(repeating:count:) and reordered parameters}} {{none}}
_ = String(repeating: c, count: 1) // no more error, since String conforms to BidirectionalCollection
_ = String(repeating: u, count: 1) // expected-error {{'init(repeating:count:)' is unavailable: Replaced by init(repeating: String, count: Int)}} {{none}}
}
func _Unicode<C : UnicodeCodec>(s: UnicodeScalar, c: C.Type, out: (C.CodeUnit) -> Void) {
func fn<T : UnicodeCodecType>(_: T) {} // expected-error {{'UnicodeCodecType' has been renamed to 'UnicodeCodec'}} {{15-31=UnicodeCodec}} {{none}}
c.encode(s, output: out) // expected-error {{encode(_:output:)' has been renamed to 'encode(_:into:)}} {{5-11=encode}} {{15-21=into}} {{none}}
c.encode(s) { _ in } // OK
UTF8.encode(s, output: { _ in }) // expected-error {{'encode(_:output:)' has been renamed to 'encode(_:into:)'}} {{8-14=encode}} {{18-24=into}} {{none}}
UTF16.encode(s, output: { _ in }) // expected-error {{'encode(_:output:)' has been renamed to 'encode(_:into:)'}} {{9-15=encode}} {{19-25=into}} {{none}}
UTF32.encode(s, output: { _ in }) // expected-error {{'encode(_:output:)' has been renamed to 'encode(_:into:)'}} {{9-15=encode}} {{19-25=into}} {{none}}
}
func _Unicode<I : IteratorProtocol, E : UnicodeCodec>(i: I, e: E.Type) where I.Element == E.CodeUnit {
_ = transcode(e, e, i, { _ in }, stopOnError: true) // expected-error {{'transcode(_:_:_:_:stopOnError:)' is unavailable: use 'transcode(_:from:to:stoppingOnError:into:)'}} {{none}}
_ = UTF16.measure(e, input: i, repairIllFormedSequences: true) // expected-error {{'measure(_:input:repairIllFormedSequences:)' is unavailable: use 'transcodedLength(of:decodedAs:repairingIllFormedSequences:)'}} {{none}}
}
func _UnicodeScalar(s: UnicodeScalar) {
_ = UnicodeScalar() // expected-error {{'init()' is unavailable: use 'Unicode.Scalar(0)'}} {{none}}
_ = s.escape(asASCII: true) // expected-error {{'escape(asASCII:)' has been renamed to 'escaped(asASCII:)'}} {{9-15=escaped}} {{none}}
}
func _Unmanaged<T>(x: Unmanaged<T>, p: OpaquePointer) {
_ = Unmanaged<T>.fromOpaque(p) // expected-error {{'fromOpaque' is unavailable: use 'fromOpaque(_: UnsafeRawPointer)' instead}} {{none}}
let _: OpaquePointer = x.toOpaque() // expected-error {{'toOpaque()' is unavailable: use 'toOpaque() -> UnsafeRawPointer' instead}} {{none}}
}
func _UnsafeBufferPointer() {
func fn<T>(x: UnsafeBufferPointerGenerator<T>) {} // expected-error {{'UnsafeBufferPointerGenerator' has been renamed to 'UnsafeBufferPointerIterator'}} {{17-45=UnsafeBufferPointerIterator}} {{none}}
}
func _UnsafePointer<T>(x: UnsafePointer<T>) {
_ = UnsafePointer<T>.Memory.self // expected-error {{'Memory' has been renamed to 'Pointee'}} {{24-30=Pointee}} {{none}}
_ = UnsafePointer<T>() // expected-error {{'init()' is unavailable: use 'nil' literal}} {{none}}
_ = x.memory // expected-error {{'memory' has been renamed to 'pointee'}} {{9-15=pointee}} {{none}}
}
func _UnsafePointer<T>(x: UnsafeMutablePointer<T>, e: T) {
var x = x
_ = UnsafeMutablePointer<T>.Memory.self // expected-error {{'Memory' has been renamed to 'Pointee'}} {{31-37=Pointee}} {{none}}
_ = UnsafeMutablePointer<T>() // expected-error {{'init()' is unavailable: use 'nil' literal}} {{none}}
_ = x.memory // expected-error {{'memory' has been renamed to 'pointee'}} {{9-15=pointee}} {{none}}
_ = UnsafeMutablePointer<T>.alloc(1) // expected-error {{'alloc' has been renamed to 'allocate(capacity:)'}} {{31-36=allocate}} {{37-37=capacity: }} {{none}}
x.dealloc(1) // expected-error {{'dealloc' has been renamed to 'deallocate(capacity:)'}} {{5-12=deallocate}} {{13-13=capacity: }} {{none}}
x.memory = e // expected-error {{'memory' has been renamed to 'pointee'}} {{5-11=pointee}} {{none}}
x.initialize(e) // expected-error {{'initialize' has been renamed to 'initialize(to:)'}} {{5-15=initialize}} {{16-16=to: }} {{none}}
x.destroy() // expected-error {{'destroy()' has been renamed to 'deinitialize(count:)'}} {{5-12=deinitialize}} {{none}}
x.destroy(1) // expected-error {{'destroy' has been renamed to 'deinitialize(count:)'}} {{5-12=deinitialize}} {{13-13=count: }} {{none}}
x.initialize(with: e) // expected-error {{'initialize(with:count:)' has been renamed to 'initialize(to:count:)'}} {{5-15=initialize}} {{16-20=to}} {{none}}
let ptr1 = UnsafeMutablePointer<T>(allocatingCapacity: 1) // expected-error {{'init(allocatingCapacity:)' is unavailable: use 'UnsafeMutablePointer.allocate(capacity:)'}} {{none}}
ptr1.initialize(with: e, count: 1) // expected-error {{'initialize(with:count:)' has been renamed to 'initialize(to:count:)'}} {{8-18=initialize}} {{19-23=to}} {{none}}
let ptr2 = UnsafeMutablePointer<T>.allocate(capacity: 1)
ptr2.initializeFrom(ptr1, count: 1) // expected-error {{'initializeFrom(_:count:)' has been renamed to 'initialize(from:count:)'}} {{8-22=initialize}} {{23-23=from: }} {{none}}
ptr1.assignFrom(ptr2, count: 1) // expected-error {{'assignFrom(_:count:)' has been renamed to 'assign(from:count:)'}} {{8-18=assign}} {{19-19=from: }} {{none}}
ptr2.assignBackwardFrom(ptr1, count: 1) // expected-error {{'assignBackwardFrom(_:count:)' has been renamed to 'assign(from:count:)'}} {{8-26=assign}} {{27-27=from: }} {{none}}
ptr1.moveAssignFrom(ptr2, count: 1) // expected-error {{'moveAssignFrom(_:count:)' has been renamed to 'moveAssign(from:count:)'}} {{8-22=moveAssign}} {{23-23=from: }} {{none}}
ptr2.moveInitializeFrom(ptr1, count: 1) // expected-error {{'moveInitializeFrom(_:count:)' has been renamed to 'moveInitialize(from:count:)'}} {{8-26=moveInitialize}} {{27-27=from: }} {{none}}
ptr1.moveInitializeBackwardFrom(ptr1, count: 1) // expected-error {{'moveInitializeBackwardFrom(_:count:)' has been renamed to 'moveInitialize(from:count:)'}} {{8-34=moveInitialize}} {{35-35=from: }} {{none}}
ptr1.deinitialize(count:1)
ptr1.deallocateCapacity(1) // expected-error {{'deallocateCapacity' has been renamed to 'deallocate(capacity:)'}} {{8-26=deallocate}} {{27-27=capacity: }} {{none}}
ptr2.deallocate(capacity: 1)
}
func _UnsafePointer<T, C : Collection>(x: UnsafeMutablePointer<T>, c: C) where C.Iterator.Element == T {
x.initializeFrom(c) // expected-error {{'initializeFrom' has been renamed to 'initialize(from:)'}}
}
func _VarArgs() {
func fn1(_: CVarArgType) {} // expected-error {{'CVarArgType' has been renamed to 'CVarArg'}} {{15-26=CVarArg}}{{none}}
func fn2(_: VaListBuilder) {} // expected-error {{'VaListBuilder' is unavailable}} {{none}}
}
func _Zip<S1 : Sequence, S2: Sequence>(s1: S1, s2: S2) {
_ = Zip2Sequence(s1, s2) // expected-error {{use zip(_:_:) free function instead}} {{none}}
_ = Zip2Sequence<S1, S2>.Generator.self // expected-error {{'Generator' has been renamed to 'Iterator'}} {{28-37=Iterator}} {{none}}
}
| apache-2.0 | 9b32c52a91290f7a87e4f77d37ae1b16 | 76.557789 | 285 | 0.662304 | 3.684705 | false | false | false | false |
xzhangyueqian/JinJiangZhiChuang | JJZC/Pods/WMPageController-Swift/PageController/MenuView.swift | 1 | 12436 | //
// MenuView.swift
// PageController
//
// Created by Mark on 15/10/20.
// Copyright © 2015年 Wecan Studio. All rights reserved.
//
import UIKit
@objc public protocol MenuViewDelegate: NSObjectProtocol {
func menuView(menuView: MenuView, widthForItemAtIndex index: Int) -> CGFloat
optional func menuView(menuView: MenuView, didSelectedIndex index: Int, fromIndex currentIndex: Int)
optional func menuView(menuView: MenuView, itemMarginAtIndex index: Int) -> CGFloat
}
@objc public protocol MenuViewDataSource: NSObjectProtocol {
func menuView(menuView: MenuView, titleAtIndex index: Int) -> String
func numbersOfTitlesInMenuView(menuView: MenuView) -> Int
}
public enum MenuViewStyle {
case Default, Line, Flood, FooldHollow
}
public class MenuView: UIView, MenuItemDelegate {
// MARK: - Public vars
override public var frame: CGRect {
didSet {
guard contentView != nil else { return }
let rightMargin = (rightView == nil) ? contentMargin : contentMargin + rightView!.frame.width
let leftMargin = (leftView == nil) ? contentMargin : contentMargin + leftView!.frame.width
let contentWidth = CGRectGetWidth(contentView.frame) + leftMargin + rightMargin
let startX = (leftView != nil) ? leftView!.frame.origin.x : (contentView.frame.origin.x - contentMargin)
// Make the contentView center, because system will change menuView's frame if it's a titleView.
if (startX + contentWidth / 2 != bounds.width / 2) {
let xOffset = (contentWidth - bounds.width) / 2
contentView.frame.origin.x -= xOffset
rightView?.frame.origin.x -= xOffset
leftView?.frame.origin.x -= xOffset
}
}
}
public weak var leftView: UIView? {
willSet {
leftView?.removeFromSuperview()
}
didSet {
if let lView = leftView {
addSubview(lView)
}
resetFrames()
}
}
public weak var rightView: UIView? {
willSet {
rightView?.removeFromSuperview()
}
didSet {
if let rView = rightView {
addSubview(rView)
}
resetFrames()
}
}
public var contentMargin: CGFloat = 0.0 {
didSet {
guard contentView != nil else { return }
resetFrames()
}
}
public var style = MenuViewStyle.Default
public var fontName: String?
public var progressHeight: CGFloat = 2.0
public var normalSize: CGFloat = 15.0
public var selectedSize: CGFloat = 18.0
public var progressColor: UIColor?
public weak var delegate: MenuViewDelegate?
public weak var dataSource: MenuViewDataSource!
public lazy var normalColor = UIColor.blackColor()
public lazy var selectedColor = UIColor(red: 168.0/255.0, green: 20.0/255.0, blue: 4/255.0, alpha: 1.0)
// MARK: - Private vars
private weak var contentView: UIScrollView!
private weak var progressView: ProgressView?
private weak var selectedItem: MenuItem!
private var itemFrames = [CGRect]()
private let tagGap = 6250
private var itemsCount: Int {
return dataSource.numbersOfTitlesInMenuView(self)
}
public func reload() {
itemFrames.removeAll()
progressView?.removeFromSuperview()
for subview in contentView.subviews {
subview.removeFromSuperview()
}
addMenuItems()
addProgressView()
}
// MARK: - Public funcs
public func slideMenuAtProgress(progress: CGFloat) {
progressView?.progress = progress
let tag = Int(progress) + tagGap
var rate = progress - CGFloat(tag - tagGap)
let currentItem = viewWithTag(tag) as? MenuItem
let nextItem = viewWithTag(tag + 1) as? MenuItem
if rate == 0.0 {
rate = 1.0
selectedItem.selected = false
selectedItem = currentItem
selectedItem.selected = true
refreshContentOffset()
return
}
currentItem?.rate = 1.0 - rate
nextItem?.rate = rate
}
public func selectItemAtIndex(index: Int) {
let tag = index + tagGap
let currentIndex = selectedItem.tag - tagGap
guard currentIndex != index && selectedItem != nil else { return }
let menuItem = viewWithTag(tag) as! MenuItem
selectedItem.selected = false
selectedItem = menuItem
selectedItem.selected = true
progressView?.moveToPosition(index, animation: false)
delegate?.menuView?(self, didSelectedIndex: index, fromIndex: currentIndex)
refreshContentOffset()
}
// MARK: - Update Title
public func updateTitle(title: String, atIndex index: Int, andWidth update: Bool) {
guard index >= 0 && index < itemsCount else { return }
let item = viewWithTag(tagGap + index) as? MenuItem
item?.text = title
guard update else { return }
resetFrames()
}
// MARK: - Update Frames
public func resetFrames() {
var contentFrame = bounds
if let rView = rightView {
var rightFrame = rView.frame
rightFrame.origin.x = contentFrame.width - rightFrame.width
rightView?.frame = rightFrame
contentFrame.size.width -= rightFrame.width
}
if let lView = leftView {
var leftFrame = lView.frame
leftFrame.origin.x = 0
leftView?.frame = leftFrame
contentFrame.origin.x += leftFrame.width
contentFrame.size.width -= leftFrame.width
}
contentFrame.origin.x += contentMargin
contentFrame.size.width -= contentMargin * 2
contentView.frame = contentFrame
resetFramesFromIndex(0)
refreshContentOffset()
}
public func resetFramesFromIndex(index: Int) {
itemFrames.removeAll()
calculateFrames()
for i in index ..< itemsCount {
let item = viewWithTag(tagGap + i) as? MenuItem
item?.frame = itemFrames[i]
}
if let progress = progressView {
var pFrame = progress.frame
pFrame.size.width = contentView.contentSize.width
if progress.isKindOfClass(FooldView.self) {
pFrame.origin.y = 0
} else {
pFrame.origin.y = frame.size.height - progressHeight
}
progress.frame = pFrame
progress.itemFrames = itemFrames
progress.setNeedsDisplay()
}
}
// MARK: - Private funcs
override public func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
guard contentView == nil else { return }
addScollView()
addMenuItems()
addProgressView()
}
private func refreshContentOffset() {
let itemFrame = selectedItem.frame
let itemX = itemFrame.origin.x
let width = contentView.frame.size.width
let contentWidth = contentView.contentSize.width
if itemX > (width / 2) {
var targetX: CGFloat = itemFrame.origin.x - width/2 + itemFrame.size.width/2
if (contentWidth - itemX) <= (width / 2) {
targetX = contentWidth - width
}
if (targetX + width) > contentWidth {
targetX = contentWidth - width
}
contentView.setContentOffset(CGPointMake(targetX, 0), animated: true)
} else {
contentView.setContentOffset(CGPointZero, animated: true)
}
}
// MARK: - Create Views
private func addScollView() {
let scrollViewFrame = CGRect(x: contentMargin, y: 0, width: frame.size.width - contentMargin * 2, height: frame.size.height)
let scrollView = UIScrollView(frame: scrollViewFrame)
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.backgroundColor = .clearColor()
scrollView.scrollsToTop = false
addSubview(scrollView)
contentView = scrollView
}
private func addMenuItems() {
calculateFrames()
for index in 0 ..< itemsCount {
let menuItemFrame = itemFrames[index]
let menuItem = MenuItem(frame: menuItemFrame)
menuItem.tag = index + tagGap
menuItem.delegate = self
menuItem.text = dataSource.menuView(self, titleAtIndex: index)
menuItem.textColor = normalColor
if let optionalFontName = fontName {
menuItem.font = UIFont(name: optionalFontName, size: selectedSize)
} else {
menuItem.font = UIFont.systemFontOfSize(selectedSize)
}
menuItem.normalSize = normalSize
menuItem.selectedSize = selectedSize
menuItem.normalColor = normalColor
menuItem.selectedColor = selectedColor
menuItem.selected = (index == 0) ? true : false
if index == 0 { selectedItem = menuItem }
contentView.addSubview(menuItem)
}
}
private func addProgressView() {
var optionalType: ProgressView.Type?
var hollow = false
switch style {
case .Default: break
case .Line: optionalType = ProgressView.self
case .FooldHollow:
optionalType = FooldView.self
hollow = true
case .Flood: optionalType = FooldView.self
}
if let viewType = optionalType {
let pView = viewType.init()
let height = (style == .Line) ? progressHeight : frame.size.height
let progressY = (style == .Line) ? (frame.size.height - progressHeight) : 0
pView.frame = CGRect(x: 0, y: progressY, width: contentView.contentSize.width, height: height)
pView.itemFrames = itemFrames
if (progressColor == nil) {
progressColor = selectedColor
}
pView.color = (progressColor?.CGColor)!
pView.backgroundColor = .clearColor()
if let fooldView = pView as? FooldView {
fooldView.hollow = hollow
}
contentView.insertSubview(pView, atIndex: 0)
progressView = pView
}
}
// MARK: - Calculate Frames
private func calculateFrames() {
var contentWidth: CGFloat = itemMarginAtIndex(0)
for index in 0 ..< itemsCount {
let itemWidth = delegate!.menuView(self, widthForItemAtIndex: index)
let itemFrame = CGRect(x: contentWidth, y: 0, width: itemWidth, height: frame.size.height)
itemFrames.append(itemFrame)
contentWidth += itemWidth + itemMarginAtIndex(index + 1)
}
if contentWidth < contentView.frame.size.width {
let distance = contentView.frame.size.width - contentWidth
let itemMargin = distance / CGFloat(itemsCount + 1)
for index in 0 ..< itemsCount {
var itemFrame = itemFrames[index]
itemFrame.origin.x += itemMargin * CGFloat(index + 1)
itemFrames[index] = itemFrame
}
contentWidth = contentView.frame.size.width
}
contentView.contentSize = CGSize(width: contentWidth, height: frame.size.height)
}
private func itemMarginAtIndex(index: Int) -> CGFloat {
if let itemMargin = delegate?.menuView?(self, itemMarginAtIndex: index) {
return itemMargin
}
return 0.0
}
// MARK: - MenuItemDelegate
func didSelectedMenuItem(menuItem: MenuItem) {
if selectedItem == menuItem { return }
let position = menuItem.tag - tagGap
let currentIndex = selectedItem.tag - tagGap
progressView?.moveToPosition(position, animation: true)
delegate?.menuView?(self, didSelectedIndex: position, fromIndex: currentIndex)
menuItem.selectWithAnimation(true)
selectedItem.selectWithAnimation(false)
selectedItem = menuItem
refreshContentOffset()
}
}
| apache-2.0 | 93ac21fc1533f19bbf61bc139884a5e1 | 35.567647 | 132 | 0.600097 | 5.210813 | false | false | false | false |
zhangxigithub/Bonjour | Bonjour.swift | 1 | 4891 | //
// AppDelegate.swift
// demo
//
// Created by zhangxi on 12/25/15.
// Copyright © 2015 http://zhangxi.me. All rights reserved.
//
import UIKit
import MultipeerConnectivity
let BonjourNotificationPeerKey = "BonjourNotificationPeerKey"
let BonjourNotificationMessageKey = "BonjourNotificationMessageKey"
protocol BonjourDelegate
{
func didConnectPeer(peerID:MCPeerID)
func didDisconnectPeer(peerID:MCPeerID)
func didReceiveMessage(message:String,peerID:MCPeerID)
func didLost(peerID:MCPeerID)
}
class Bonjour : NSObject,MCSessionDelegate,MCNearbyServiceBrowserDelegate,MCNearbyServiceAdvertiserDelegate
{
var delegate:BonjourDelegate?
var advertisier:MCNearbyServiceAdvertiser!
var browser:MCNearbyServiceBrowser!
var session:MCSession!
var peerID : MCPeerID?
let serviceType = "zx-bonjour"
func bonjour(name:String? = nil)
{
if name == nil
{
peerID = MCPeerID(displayName: UIDevice.current.name)
}else
{
peerID = MCPeerID(displayName: name!)
}
browser = MCNearbyServiceBrowser(peer: peerID!, serviceType: serviceType)
browser.delegate = self
browser.startBrowsingForPeers()
advertisier = MCNearbyServiceAdvertiser(peer: peerID!, discoveryInfo: nil, serviceType: serviceType)
advertisier.delegate = self
advertisier.startAdvertisingPeer()
session = MCSession(peer: peerID!)
session.delegate = self
}
func sendMessage(message:String,mode:MCSessionSendDataMode = MCSessionSendDataMode.reliable)
{
do {
if let data = message.data(using: .utf8)
{
try session.send(data, toPeers: session.connectedPeers, with: mode)
}
}
catch{}
}
func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
browser.invitePeer(peerID, to: session, withContext: nil, timeout: 20)
}
func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
self.delegate?.didLost(peerID: peerID)
}
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) {
invitationHandler(true,session)
}
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
}
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
DispatchQueue.main.async {
if let message = String(data: data, encoding: .utf8)
{
self.delegate?.didReceiveMessage(message: message, peerID: peerID)
}
}
}
func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
}
func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
}
func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {
}
}
/*
//MARK: - MCNearbyServiceBrowserDelegate
func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?)
{
browser.invitePeer(peerID, toSession: session, withContext: nil, timeout: 20)
}
func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID)
{
browser.invitePeer(peerID, toSession: session, withContext: nil, timeout: 20)
}
//MARK: - MCSessionDelegate
func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState)
{
switch state
{
case .NotConnected:
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.delegate?.didDisconnectPeer?(peerID)
}
case .Connecting:
break
case .Connected:
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.delegate?.didConnectPeer?(peerID)
}
}
}
func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID)
{
dispatch_async(dispatch_get_main_queue()) { () -> Void in
if let message = String(data: data, encoding: NSUTF8StringEncoding)
{
self.delegate?.didReceiveMessage?(message, peerID: peerID)
}
}
}
*/
| apache-2.0 | 5254fabbee5c13f7aa9105acb3edef4e | 27.764706 | 194 | 0.634151 | 5.109718 | false | false | false | false |
hgani/ganilib-ios | glib/Classes/View/Layout/GVerticalPanel.swift | 1 | 7000 | import UIKit
open class GVerticalPanel: UIView, IView {
private var helper: ViewHelper!
private var previousViewElement: UIView!
private var previousConstraint: NSLayoutConstraint!
private var event: EventHelper<GVerticalPanel>!
private var totalGap = Float(0.0)
public var size: CGSize {
return helper.size
}
private var paddings: Paddings {
return helper.paddings
}
public init() {
super.init(frame: .zero)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
helper = ViewHelper(self)
event = EventHelper(self)
_ = paddings(top: 0, left: 0, bottom: 0, right: 0)
addInitialBottomConstraint()
}
private func addInitialBottomConstraint() {
previousConstraint = NSLayoutConstraint(item: self,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: 0.0)
previousConstraint.priority = UILayoutPriority(rawValue: 900) // Lower priority than fixed height
addConstraint(previousConstraint)
}
open override func didMoveToSuperview() {
super.didMoveToSuperview()
helper.didMoveToSuperview()
}
public func clearViews() {
// Remove it explicitly because it's not necessarily related to a child view, thus won't be removed
// as part of view.removeFromSuperview()
removeConstraint(previousConstraint)
addInitialBottomConstraint()
previousViewElement = nil
for view in subviews {
view.removeFromSuperview()
}
}
public func addView(_ child: UIView, top: Float = 0) {
totalGap += top
// The hope is this makes things more predictable
child.translatesAutoresizingMaskIntoConstraints = false
super.addSubview(child)
initChildConstraints(child: child, top: top)
adjustSelfConstraints(child: child)
previousViewElement = child
}
public func clear() -> Self {
clearViews()
return self
}
@discardableResult
public func append(_ child: UIView, top: Float = 0) -> Self {
addView(child, top: top)
return self
}
// See https://github.com/zaxonus/AutoLayScroll/blob/master/AutoLayScroll/ViewController.swift
private func initChildConstraints(child: UIView, top: Float) {
child.snp.makeConstraints { make in
if previousViewElement == nil {
make.top.equalTo(self.snp.topMargin).offset(top)
} else {
make.top.equalTo(previousViewElement.snp.bottom).offset(top)
}
// make.left.equalTo(self.snp.leftMargin)
switch horizontalAlign {
case .center: make.centerX.equalTo(self)
case .right: make.right.equalTo(self.snp.rightMargin)
case .left: make.left.equalTo(self.snp.leftMargin)
}
}
}
private func adjustSelfConstraints(child: UIView) {
snp.makeConstraints { (make) -> Void in
make.rightMargin.greaterThanOrEqualTo(child.snp.right)
}
if !helper.shouldHeightMatchParent() {
removeConstraint(previousConstraint)
previousConstraint = NSLayoutConstraint(item: child,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .bottomMargin,
multiplier: 1.0,
constant: 0.0)
previousConstraint.priority = UILayoutPriority(rawValue: 900)
// At this point previousViewElement refers to the last subview, that is the one at the bottom.
addConstraint(previousConstraint)
}
}
@discardableResult
public func width(_ width: Int) -> Self {
helper.width(width)
return self
}
@discardableResult
public func width(_ width: LayoutSize) -> Self {
helper.width(width)
return self
}
@discardableResult
public func width(weight: Float) -> Self {
helper.width(weight: weight)
return self
}
@discardableResult
public func height(_ height: Int) -> Self {
helper.height(height)
return self
}
@discardableResult
public func height(_ height: LayoutSize) -> Self {
helper.height(height)
return self
}
@discardableResult
public func paddings(top: Float? = nil, left: Float? = nil, bottom: Float? = nil, right: Float? = nil) -> Self {
helper.paddings(t: top, l: left, b: bottom, r: right)
return self
}
@discardableResult
public func color(bg: UIColor) -> Self {
backgroundColor = bg
return self
}
open override func addSubview(_: UIView) {
fatalError("Use addView() instead")
}
public func border(color: UIColor?, width: Float = 1, corner: Float = 6) -> Self {
helper.border(color: color, width: width, corner: corner)
return self
}
public func hidden(_ hidden: Bool) -> Self {
isHidden = hidden
return self
}
public func onClick(_ command: @escaping (GVerticalPanel) -> Void) -> Self {
event.onClick(command)
return self
}
public func tap(_ command: (GVerticalPanel) -> Void) -> Self {
command(self)
return self
}
@discardableResult
public func bg(image: UIImage?, repeatTexture: Bool) -> Self {
helper.bg(image: image, repeatTexture: repeatTexture)
return self
}
public func split() -> Self {
let count = subviews.count
GLog.i("Splitting \(count) views ...")
let weight = 1.0 / Float(count)
let offset = -(totalGap + paddings.top + paddings.bottom) / Float(count)
for view in subviews {
if let weightable = view as? GWeightable {
_ = weightable.height(weight: weight, offset: offset)
} else {
GLog.e("Invalid child view: \(view)")
}
}
return self
}
// MARK: - Alignment
private var horizontalAlign: GAligner.GAlignerHorizontalGravity = .left
public func align(_ align: GAligner.GAlignerHorizontalGravity) -> Self {
horizontalAlign = align
return self
}
public func done() {
// Ends chaining
}
}
| mit | 0345c87ece42aa8f151fb2f8e27a201b | 28.91453 | 116 | 0.562 | 5.079826 | false | false | false | false |
SwiftGen/SwiftGen | Sources/SwiftGenKit/Parsers/Strings/FileTypeParser/StringsFileParser.swift | 1 | 1063 | //
// SwiftGenKit
// Copyright © 2022 SwiftGen
// MIT Licence
//
import Foundation
import PathKit
extension Strings {
final class StringsFileParser: StringsFileTypeParser {
private let options: ParserOptionValues
init(options: ParserOptionValues) {
self.options = options
}
static let extensions = ["strings"]
// Localizable.strings files are generally UTF16, not UTF8!
func parseFile(at path: Path) throws -> [Strings.Entry] {
guard let data = try? path.read() else {
throw ParserError.failureOnLoading(path: path)
}
let entries = try PropertyListDecoder()
.decode([String: String].self, from: data)
.map { key, translation in
try Entry(key: key, translation: translation, keyStructureSeparator: options[Option.separator])
}
var dict = Dictionary(uniqueKeysWithValues: entries.map { ($0.key, $0) })
if let parser = StringsFileWithCommentsParser(file: path) {
parser.enrich(entries: &dict)
}
return Array(dict.values)
}
}
}
| mit | 6f60b734e58d762e69fa7b0cff7fe4b4 | 25.55 | 105 | 0.661017 | 4.317073 | false | false | false | false |
ikait/KernLabel | KernLabel/KernLabel/Extensions/NSAttributedString+Extension.swift | 1 | 3473 | //
// NSAttributedString+Extension.swift
// KernLabel
//
// Created by ikai on 2016/05/26.
// Copyright © 2016年 Taishi Ikai. All rights reserved.
//
import UIKit
extension NSAttributedString {
var lineHeight: CGFloat {
guard let paragraphStyle = self.attributes[NSParagraphStyleAttributeName] as? NSParagraphStyle else {
return self.font.lineHeight
}
let lineHeightMultiple = paragraphStyle.lineHeightMultiple
return self.font.lineHeight * ((lineHeightMultiple.isZero) ? 1 : lineHeightMultiple)
}
var textAlignment: NSTextAlignment? {
guard let paragraphStyle = self.attributes[NSParagraphStyleAttributeName] as? NSParagraphStyle else {
return nil
}
return paragraphStyle.alignment
}
var backgroundColor: UIColor? {
return self.attributes[NSBackgroundColorAttributeName] as? UIColor
}
var attributes: [String : Any] {
if self.length != 0 {
return self.attributes(at: 0, effectiveRange: nil)
} else {
return [:]
}
}
var font: UIFont {
if let font = self.attributes[NSFontAttributeName] as? UIFont {
return font
}
return UIFont.systemFont(ofSize: UIFont.systemFontSize)
}
func substring(_ range: NSRange) -> String {
return self.attributedSubstring(from: range).string
}
func substring(_ location: Int, _ length: Int) -> String {
return self.substring(NSMakeRange(location, length))
}
func getFont(_ location: Int) -> UIFont? {
if let font = self.attributes(at: location, effectiveRange: nil)[NSFontAttributeName] as? UIFont {
return font
}
return nil
}
func getLineHeight(_ location: Int) -> CGFloat {
guard let paragraphStyle = self.attributes(at: location, effectiveRange: nil)[NSParagraphStyleAttributeName] as? NSParagraphStyle, let font = self.getFont(location) else {
return self.font.lineHeight
}
let lineHeightMultiple = paragraphStyle.lineHeightMultiple
return font.lineHeight * ((lineHeightMultiple.isZero) ? 1 : lineHeightMultiple)
}
func getTextAlignment(_ location: Int) -> NSTextAlignment? {
guard let paragraphStyle = self.attributes(at: location, effectiveRange: nil)[NSParagraphStyleAttributeName] as? NSParagraphStyle else {
return nil
}
return paragraphStyle.alignment
}
func mutableAttributedString(from range: NSRange) -> NSMutableAttributedString {
return NSMutableAttributedString(attributedString: self.attributedSubstring(from: range))
}
func boundingWidth(options: NSStringDrawingOptions, context: NSStringDrawingContext?) -> CGFloat {
return self.boundingRect(options: options, context: context).size.width
}
func boundingRect(options: NSStringDrawingOptions, context: NSStringDrawingContext?) -> CGRect {
return self.boundingRect(with: CGSize(width: kCGFloatHuge, height: kCGFloatHuge), options: options, context: context)
}
func boundingRectWithSize(_ size: CGSize, options: NSStringDrawingOptions, numberOfLines: Int, context: NSStringDrawingContext?) -> CGRect {
let boundingRect = self.boundingRect(
with: CGSize(width: size.width, height: self.lineHeight * CGFloat(numberOfLines)), options: options, context: context)
return boundingRect
}
}
| mit | b52e93eabc2690d6f99a5228ab285609 | 35.914894 | 179 | 0.678098 | 5.265554 | false | false | false | false |
necrowman/CRLAlamofireFuture | Examples/SimpleTvOSCarthage/Carthage/Checkouts/RunLoop/RunLoop/Sync.swift | 111 | 1914 | //===--- Sync.swift ----------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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 Boilerplate
import Result
public extension RunLoopType {
private func syncThroughAsync<ReturnType>(task:() throws -> ReturnType) throws -> ReturnType {
if let settled = self as? SettledType where settled.isHome {
return try task()
}
var result:Result<ReturnType, AnyError>?
let sema = RunLoop.current.semaphore()
self.execute {
defer {
sema.signal()
}
result = materializeAny(task)
}
sema.wait()
return try result!.dematerializeAny()
}
private func syncThroughAsync2<ReturnType>(task:() throws -> ReturnType) rethrows -> ReturnType {
//rethrow hack
return try {
try self.syncThroughAsync(task)
}()
}
/*public func sync<ReturnType>(@autoclosure(escaping) task:() throws -> ReturnType) rethrows -> ReturnType {
return try syncThroughAsync2(task)
}*/
public func sync<ReturnType>(task:() throws -> ReturnType) rethrows -> ReturnType {
return try syncThroughAsync2(task)
}
} | mit | 5f7ea6ea2ca0f3377ad74d31d6d2d644 | 32.017241 | 112 | 0.596134 | 5.076923 | false | false | false | false |
Piwigo/Piwigo-Mobile | piwigo/Settings/Help/Help01ViewController.swift | 1 | 3024 | //
// Help01ViewController.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 30/11/2020.
// Copyright © 2020 Piwigo.org. All rights reserved.
//
import UIKit
import piwigoKit
class Help01ViewController: UIViewController {
@IBOutlet weak var legend: UILabel!
@IBOutlet weak var imageView: UIImageView!
private let helpID: UInt16 = 0b00000000_00000001
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Initialise mutable attributed string
let legendAttributedString = NSMutableAttributedString(string: "")
// Title
let titleString = "\(NSLocalizedString("help01_header", comment: "Multiple Selection"))\n"
let titleAttributedString = NSMutableAttributedString(string: titleString)
titleAttributedString.addAttribute(.font, value: view.bounds.size.width > 320 ? UIFont.piwigoFontBold() : UIFont.piwigoFontSemiBold(), range: NSRange(location: 0, length: titleString.count))
legendAttributedString.append(titleAttributedString)
// Text
let textString = NSLocalizedString("help01_text", comment: "Slide your finger from left to right (or right to left) then down, etc.")
let textAttributedString = NSMutableAttributedString(string: textString)
textAttributedString.addAttribute(.font, value: view.bounds.size.width > 320 ? UIFont.piwigoFontNormal() : UIFont.piwigoFontSmall(), range: NSRange(location: 0, length: textString.count))
legendAttributedString.append(textAttributedString)
// Set legend
legend.attributedText = legendAttributedString
// Set image view
guard let imageUrl = Bundle.main.url(forResource: "help01", withExtension: "png") else {
fatalError("!!! Could not find help01 image !!!")
}
imageView.layoutIfNeeded() // Ensure imageView is in its final size.
let size = imageView.bounds.size
let scale = imageView.traitCollection.displayScale
imageView.image = ImageUtilities.downsample(imageAt: imageUrl, to: size, scale: scale)
// Remember that this view was watched
AppVars.shared.didWatchHelpViews = AppVars.shared.didWatchHelpViews | helpID
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Set colors, fonts, etc.
applyColorPalette()
// Register palette changes
NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette),
name: .pwgPaletteChanged, object: nil)
}
@objc func applyColorPalette() {
// Background color of the view
view.backgroundColor = .piwigoColorBackground()
// Legend color
legend.textColor = .piwigoColorText()
}
deinit {
// Unregister palette changes
NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil)
}
}
| mit | 6478858b2921c090bc6dbf5d9fb8ca4d | 38.763158 | 198 | 0.672733 | 5.210345 | false | false | false | false |
sschiau/swift | test/APINotes/versioned-objc.swift | 2 | 9050 | // RUN: %empty-directory(%t)
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 5 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-5 %s
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 4 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-4 %s
// REQUIRES: objc_interop
import APINotesFrameworkTest
// CHECK-DIAGS-5-NOT: versioned-objc.swift:[[@LINE-1]]:
class ProtoWithVersionedUnavailableMemberImpl: ProtoWithVersionedUnavailableMember {
// CHECK-DIAGS-4: versioned-objc.swift:[[@LINE-1]]:7: error: type 'ProtoWithVersionedUnavailableMemberImpl' cannot conform to protocol 'ProtoWithVersionedUnavailableMember' because it has requirements that cannot be satisfied
func requirement() -> Any? { return nil }
}
func testNonGeneric() {
// CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: cannot convert value of type 'Any' to specified type 'Int'
let _: Int = NewlyGenericSub.defaultElement()
// CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: generic parameter 'Element' could not be inferred
// CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: cannot specialize non-generic type 'NewlyGenericSub'
let _: Int = NewlyGenericSub<Base>.defaultElement()
// CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: cannot convert value of type 'Base' to specified type 'Int'
}
func testRenamedGeneric() {
// CHECK-DIAGS-4-NOT: 'RenamedGeneric' has been renamed to 'OldRenamedGeneric'
let _: OldRenamedGeneric<Base> = RenamedGeneric<Base>()
// CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' has been renamed to 'RenamedGeneric'
// CHECK-DIAGS-4-NOT: 'RenamedGeneric' has been renamed to 'OldRenamedGeneric'
let _: RenamedGeneric<Base> = OldRenamedGeneric<Base>()
// CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' has been renamed to 'RenamedGeneric'
class SwiftClass {}
// CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' requires that 'SwiftClass' inherit from 'Base'
let _: OldRenamedGeneric<SwiftClass> = RenamedGeneric<SwiftClass>()
// CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' requires that 'SwiftClass' inherit from 'Base'
// CHECK-DIAGS-4:[[@LINE+1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base'
let _: RenamedGeneric<SwiftClass> = OldRenamedGeneric<SwiftClass>()
// CHECK-DIAGS-5:[[@LINE-1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base'
}
func testRenamedClassMembers(obj: ClassWithManyRenames) {
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'classWithManyRenamesForInt' has been replaced by 'init(swift4Factory:)'
_ = ClassWithManyRenames.classWithManyRenamesForInt(0)
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'classWithManyRenamesForInt' has been replaced by 'init(for:)'
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(forInt:)' has been renamed to 'init(swift4Factory:)'
_ = ClassWithManyRenames(forInt: 0)
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(forInt:)' has been renamed to 'init(for:)'
// CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}:
_ = ClassWithManyRenames(swift4Factory: 0)
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift4Factory:)' has been renamed to 'init(for:)'
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(for:)' has been renamed to 'init(swift4Factory:)'
_ = ClassWithManyRenames(for: 0)
// CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(swift4Boolean:)'
_ = ClassWithManyRenames(boolean: false)
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(finalBoolean:)'
// CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}:
_ = ClassWithManyRenames(swift4Boolean: false)
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift4Boolean:)' has been renamed to 'init(finalBoolean:)'
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(finalBoolean:)' has been renamed to 'init(swift4Boolean:)'
_ = ClassWithManyRenames(finalBoolean: false)
// CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'swift4DoImportantThings()'
obj.doImportantThings()
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'finalDoImportantThings()'
// CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}:
obj.swift4DoImportantThings()
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4DoImportantThings()' has been renamed to 'finalDoImportantThings()'
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalDoImportantThings()' has been renamed to 'swift4DoImportantThings()'
obj.finalDoImportantThings()
// CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'swift4ClassProperty'
_ = ClassWithManyRenames.importantClassProperty
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'finalClassProperty'
// CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}:
_ = ClassWithManyRenames.swift4ClassProperty
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4ClassProperty' has been renamed to 'finalClassProperty'
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalClassProperty' has been renamed to 'swift4ClassProperty'
_ = ClassWithManyRenames.finalClassProperty
// CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}:
}
func testRenamedProtocolMembers(obj: ProtoWithManyRenames) {
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(swift4Boolean:)'
_ = type(of: obj).init(boolean: false)
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(finalBoolean:)'
// CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}:
_ = type(of: obj).init(swift4Boolean: false)
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift4Boolean:)' has been renamed to 'init(finalBoolean:)'
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'init(finalBoolean:)' has been renamed to 'init(swift4Boolean:)'
_ = type(of: obj).init(finalBoolean: false)
// CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'swift4DoImportantThings()'
obj.doImportantThings()
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'finalDoImportantThings()'
// CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}:
obj.swift4DoImportantThings()
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4DoImportantThings()' has been renamed to 'finalDoImportantThings()'
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalDoImportantThings()' has been renamed to 'swift4DoImportantThings()'
obj.finalDoImportantThings()
// CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'swift4ClassProperty'
_ = type(of: obj).importantClassProperty
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'finalClassProperty'
// CHECK-DIAGS-4-NOT: :[[@LINE+1]]:{{[0-9]+}}:
_ = type(of: obj).swift4ClassProperty
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: 'swift4ClassProperty' has been renamed to 'finalClassProperty'
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: error: 'finalClassProperty' has been renamed to 'swift4ClassProperty'
_ = type(of: obj).finalClassProperty
// CHECK-DIAGS-5-NOT: :[[@LINE-1]]:{{[0-9]+}}:
}
extension PrintingRenamed {
func testDroppingRenamedPrints() {
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to instance method
print()
// CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to instance method
print(self)
// CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}:
}
static func testDroppingRenamedPrints() {
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to class method
print()
// CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to class method
print(self)
// CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}:
}
}
extension PrintingInterference {
func testDroppingRenamedPrints() {
// CHECK-DIAGS-4: [[@LINE+1]]:{{[0-9]+}}: warning: use of 'print' treated as a reference to instance method
print(self)
// CHECK-DIAGS-5: [[@LINE-1]]:{{[0-9]+}}: error: missing argument for parameter 'extra' in call
// CHECK-DIAGS-4-NOT: [[@LINE+1]]:{{[0-9]+}}:
print(self, extra: self)
// CHECK-DIAGS-5-NOT: [[@LINE-1]]:{{[0-9]+}}:
}
}
let unrelatedDiagnostic: Int = nil
| apache-2.0 | 4977a55ec689548ca8d03919de6424b5 | 50.129944 | 227 | 0.647514 | 3.631621 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureCardIssuing/Sources/FeatureCardIssuingDomain/Model/Card.swift | 1 | 3119 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public struct Card: Codable, Equatable, Identifiable {
public let id: String
public let type: CardType
public let last4: String
/// Expiry date of the card in mm/yy format
public let expiry: String
public let brand: Brand
public let status: Status
public let orderStatus: [OrderStatus]?
public let createdAt: String
public init(
id: String,
type: Card.CardType,
last4: String,
expiry: String,
brand: Card.Brand,
status: Card.Status,
orderStatus: [Card.OrderStatus]?,
createdAt: String
) {
self.id = id
self.type = type
self.last4 = last4
self.expiry = expiry
self.brand = brand
self.status = status
self.orderStatus = orderStatus
self.createdAt = createdAt
}
}
extension Card {
public enum CardType: String, Codable {
case virtual = "VIRTUAL"
case physical = "PHYSICAL"
}
public enum Brand: String, Codable {
case visa = "VISA"
case mastercard = "MASTERCARD"
}
public enum Status: String, Codable {
case initiated = "INITIATED"
case created = "CREATED"
case active = "ACTIVE"
case terminated = "TERMINATED"
case suspended = "SUSPENDED"
case unsupported = "UNSUPPORTED"
case unactivated = "UNACTIVATED"
case limited = "LIMITED"
case locked = "LOCKED"
}
public struct OrderStatus: Codable, Equatable {
let status: Status
let date: Date
}
public struct Address: Codable, Hashable {
public enum Constants {
static let usIsoCode = "US"
public static let usPrefix = "US-"
}
public let line1: String?
public let line2: String?
public let city: String?
public let postCode: String?
public let state: String?
/// Country code in ISO-2
public let country: String?
public init(
line1: String?,
line2: String?,
city: String?,
postCode: String?,
state: String?,
country: String?
) {
self.line1 = line1
self.line2 = line2
self.city = city
self.postCode = postCode
self.country = country
if let state = state,
country == Constants.usIsoCode,
!state.hasPrefix(Constants.usPrefix)
{
self.state = Constants.usPrefix + state
} else {
self.state = state
}
}
}
}
extension Card.OrderStatus {
public enum Status: String, Codable {
case ordered = "ORDERED"
case shipped = "SHIPPED"
case delivered = "DELIVERED"
}
}
extension Card {
public var creationDate: Date? {
DateFormatter.iso8601Format.date(from: createdAt)
}
public var isLocked: Bool {
status == .locked
}
}
| lgpl-3.0 | 62bbdf0918d8aa4e850593fe2b840ef2 | 21.594203 | 62 | 0.557729 | 4.565154 | false | false | false | false |
farion/eloquence | Eloquence/Core/EloConnection.swift | 1 | 11978 | import Foundation
import XMPPFramework
@objc
protocol EloConnectionDelegate: NSObjectProtocol {
}
class EloConnection: NSObject, XMPPRosterDelegate,XMPPStreamDelegate, XMPPCapabilitiesDelegate, MulticastDelegateContainer {
private let account:EloAccount
private let xmppStream:XMPPStream
private let xmppRoster:XMPPRoster
private let xmppCapabilities:XMPPCapabilities
private let xmppMessageArchiveManagement: EloXMPPMessageArchiveManagement
// let xmppvCardTempModule:XMPPvCardTempModule
typealias DelegateType = EloConnectionDelegate;
var multicastDelegate = [EloConnectionDelegate]()
init(account:EloAccount){
self.account = account
xmppStream = XMPPStream();
xmppRoster = XMPPRoster(rosterStorage: EloXMPPRosterCoreDataStorage.sharedInstance())
// xmppvCardTempModule = XMPPvCardTempModule.init(withvCardStorage: XMPPvCardCoreDataStorage.sharedInstance())
// xmppvCardTempModule!.activate(xmppStream)
xmppRoster.autoFetchRoster = true;
xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = true;
xmppRoster.activate(xmppStream);
xmppCapabilities = XMPPCapabilities(capabilitiesStorage: XMPPCapabilitiesCoreDataStorage.sharedInstance());
//get server capabilities => XEP0030
xmppCapabilities.autoFetchMyServerCapabilities = true;
xmppCapabilities.activate(xmppStream)
xmppMessageArchiveManagement = EloXMPPMessageArchiveManagement(messageArchiveManagementStorage: EloXMPPMessageArchiveManagementWithContactCoreDataStorage.sharedInstance())
xmppMessageArchiveManagement.activate(xmppStream)
super.init();
xmppRoster.addDelegate(self, delegateQueue: dispatch_get_main_queue())
xmppStream.addDelegate(self, delegateQueue: dispatch_get_main_queue())
xmppCapabilities.addDelegate(self, delegateQueue: dispatch_get_main_queue())
xmppMessageArchiveManagement.addDelegate(self, delegateQueue: dispatch_get_main_queue())
}
func isConnected() -> Bool {
return xmppStream.isConnected();
}
func getXMPPStream() -> XMPPStream {
return xmppStream;
}
func getArchive() -> EloXMPPMessageArchiveManagement {
return xmppMessageArchiveManagement;
}
func connect(){
NSLog("Connect");
if(!xmppStream.isConnected()){
// var presence = XMPPPresence();
// let priority = DDXMLElement.elementWithName("priority", stringValue: "1") as! DDXMLElement;
var resource = account.getResource();
if(resource == nil || resource!.isEmpty){
resource = "Eloquence";
}
xmppStream.myJID = XMPPJID.jidWithString(account.getJid().jid,resource:resource);
let port = account.getPort();
if(port != nil && port > 0){
xmppStream.hostPort = UInt16.init(port!);
}
let domain = account.getServer();
if(domain != nil && domain!.isEmpty){
xmppStream.hostName = domain;
}
do {
try xmppStream.connectWithTimeout(XMPPStreamTimeoutNone);
}catch {
NSLog("error");
print(error);
}
}
}
//MARK: XMPP Delegates
func xmppStreamDidConnect(sender: XMPPStream!) {
NSLog("Did Connect");
do {
try xmppStream.authenticateWithPassword(account.getPassword());
}catch {
NSLog("error");
print(error);
}
}
func xmppStreamWillConnect(sender:XMPPStream) {
NSLog("Will Connect");
}
func xmppStream(sender: XMPPStream!, alternativeResourceForConflictingResource conflictingResource: String!) -> String! {
NSLog("alternativeResourceForConflictingResource");
return conflictingResource;
}
func xmppStream(sender: XMPPStream!, didFailToSendIQ iq: XMPPIQ!, error: NSError!) {
NSLog("didFailToSendIQ");
}
func xmppStream(sender: XMPPStream!, didFailToSendMessage message: XMPPMessage!, error: NSError!) {
NSLog("didFailToSendMessage");
}
func xmppStream(sender: XMPPStream!, didFailToSendPresence presence: XMPPPresence!, error: NSError!) {
NSLog("didFailToSendPresence");
}
#if os(iOS)
func xmppStream(sender: XMPPStream!, didNotAuthenticate error: DDXMLElement!) {
NSLog("didNotAuthenticate");
}
#else
func xmppStream(sender: XMPPStream!, didNotAuthenticate error: NSXMLElement!) {
NSLog("didNotAuthenticate");
}
#endif
#if os(iOS)
func xmppStream(sender: XMPPStream!, didNotRegister error: DDXMLElement!) {
NSLog("didNotRegister");
}
#else
func xmppStream(sender: XMPPStream!, didNotRegister error: NSXMLElement!) {
NSLog("didNotRegister");
}
#endif
#if os(iOS)
func xmppStream(sender: XMPPStream!, didReceiveCustomElement element: DDXMLElement!) {
NSLog("didReceiveCustomElement");
}
#else
func xmppStream(sender: XMPPStream!, didReceiveCustomElement element: NSXMLElement!) {
NSLog("didReceiveCustomElement");
}
#endif
#if os(iOS)
func xmppStream(sender: XMPPStream!, didReceiveError error: DDXMLElement!) {
NSLog("didReceiveError");
}
#else
func xmppStream(sender: XMPPStream!, didReceiveError error: NSXMLElement!) {
NSLog("didReceiveError");
}
#endif
func xmppStream(sender: XMPPStream!, didReceiveIQ iq: XMPPIQ!) -> Bool {
NSLog("didReceiveIQ");
/*
let queryElement = iq.elementForName("query",xmlns:"jabber:iq:roster");
if(queryElement != nil){
let itemElements = queryElement!.elementsForName("item");
for var i = 0; i < itemElements.count; ++i {
let jid = itemElements[i].attributeForName("jid")!.stringValue;
NSLog("%@",jid!);
}
}
*/
return true;
}
func xmppStream(sender: XMPPStream!, didReceiveMessage message: XMPPMessage!) {
NSLog("didReceiveMessage");
}
#if os(iOS)
func xmppStream(sender: XMPPStream!, didReceiveP2PFeatures streamFeatures: DDXMLElement!) {
NSLog("didReceiveP2PFeatures");
}
#else
func xmppStream(sender: XMPPStream!, didReceiveP2PFeatures streamFeatures: NSXMLElement!) {
NSLog("didReceiveP2PFeatures");
}
#endif
func xmppStream(sender: XMPPStream!, didReceivePresence presence: XMPPPresence!) {
NSLog("didReceivePresence");
}
func xmppStream(sender: XMPPStream!, didReceiveTrust trust: SecTrust!, completionHandler: ((Bool) -> Void)!) {
NSLog("didReceiveTrust");
}
func xmppStream(sender: XMPPStream!, didRegisterModule module: AnyObject!) {
NSLog("didRegisterModule");
}
#if os(iOS)
func xmppStream(sender: XMPPStream!, didSendCustomElement element: DDXMLElement!) {
NSLog("didSendCustomElement");
}
#else
func xmppStream(sender: XMPPStream!, didSendCustomElement element: NSXMLElement!) {
NSLog("didSendCustomElement");
}
#endif
func xmppStream(sender: XMPPStream!, didSendIQ iq: XMPPIQ!) {
NSLog("didSendIQ");
}
func xmppStream(sender: XMPPStream!, didSendMessage message: XMPPMessage!) {
NSLog("didSendMessage");
}
func xmppStream(sender: XMPPStream!, didSendPresence presence: XMPPPresence!) {
NSLog("didSendPresence");
}
func xmppStream(sender: XMPPStream!, willReceiveIQ iq: XMPPIQ!) -> XMPPIQ! {
NSLog("willReceiveIQ");
return iq;
}
func xmppStream(sender: XMPPStream!, willReceiveMessage message: XMPPMessage!) -> XMPPMessage! {
NSLog("willReceiveMessage");
return message;
}
func xmppStream(sender: XMPPStream!, willReceivePresence presence: XMPPPresence!) -> XMPPPresence! {
NSLog("willReceivePresence");
return presence;
}
func xmppStream(sender: XMPPStream!, willSecureWithSettings settings: NSMutableDictionary!) {
NSLog("willSecureWithSettings");
}
func xmppStream(sender: XMPPStream!, willSendIQ iq: XMPPIQ!) -> XMPPIQ! {
NSLog("willSendIQ");
return iq;
}
func xmppStream(sender: XMPPStream!, willSendMessage message: XMPPMessage!) -> XMPPMessage! {
NSLog("willSendMessage");
return message;
}
#if os(iOS)
func xmppStream(sender: XMPPStream!, willSendP2PFeatures streamFeatures: DDXMLElement!) {
NSLog("willSendP2PFeatures");
}
#else
func xmppStream(sender: XMPPStream!, willSendP2PFeatures streamFeatures: NSXMLElement!) {
NSLog("willSendP2PFeatures");
}
#endif
func xmppStream(sender: XMPPStream!, willSendPresence presence: XMPPPresence!) -> XMPPPresence! {
NSLog("willSendPresence");
return presence;
}
func xmppStream(sender: XMPPStream!, willUnregisterModule module: AnyObject!) {
NSLog("willUnregisterModule");
}
func xmppStreamConnectDidTimeout(sender: XMPPStream!) {
NSLog("xmppStreamConnectDidTimeout");
}
func xmppStreamDidAuthenticate(sender: XMPPStream!) {
NSLog("xmppStreamDidAuthenticate");
NSNotificationCenter.defaultCenter().postNotificationName(EloConstants.CONNECTION_ONLINE, object: self);
// EloXMPPMessageArchiveManagement.mamQueryWith(sender.myJID , andStart: nil, andEnd: nil, andResultSet: nil)
}
func xmppStreamDidChangeMyJID(xmppStream: XMPPStream!) {
NSLog("xmppStreamDidChangeMyJID");
}
func xmppStreamDidDisconnect(sender: XMPPStream!, withError error: NSError!) {
NSLog("xmppStreamDidDisconnect");
}
func xmppStreamDidFilterStanza(sender: XMPPStream!) {
NSLog("xmppStreamDidFilterStanza");
}
func xmppStreamDidRegister(sender: XMPPStream!) {
NSLog("xmppStreamDidRegister");
}
func xmppStreamDidSecure(sender: XMPPStream!) {
NSLog("xmppStreamDidSecure");
}
func xmppStreamDidSendClosingStreamStanza(sender: XMPPStream!) {
NSLog("xmppStreamDidSendClosingStreamStanza");
}
func xmppStreamDidStartNegotiation(sender: XMPPStream!) {
NSLog("xmppStreamDidStartNegotiation");
}
func xmppStreamWasToldToDisconnect(sender: XMPPStream!) {
NSLog("xmppStreamWasToldToDisconnect");
}
func xmppRosterDidEndPopulating(sender: XMPPRoster!) {
NSLog("xmppRosterDidEndPopulating");
}
func xmppRoster(sender: XMPPRoster!, didReceiveRosterPush iq: XMPPIQ!) {
}
#if os(iOS)
func xmppRoster(sender: XMPPRoster!, didReceiveRosterItem item: DDXMLElement!) {
}
#else
func xmppRoster(sender: XMPPRoster!, didReceiveRosterItem item: NSXMLElement!) {
}
#endif
func xmppRoster(sender: XMPPRoster!, didReceivePresenceSubscriptionRequest presence: XMPPPresence!) {
NSLog("xmppRosterdidReceivePresenceSubscriptionRequest");
}
func xmppRosterDidBeginPopulating(sender: XMPPRoster!, withVersion version: String!) {
NSLog("xmppRosterdidReceivePresenceSubscriptionRequest");
}
#if os(iOS)
func xmppCapabilities(sender: XMPPCapabilities!, didDiscoverCapabilities caps: DDXMLElement!, forJID jid: XMPPJID!) {
NSLog("xmppCapabilities %@",jid.bare());
}
#else
func xmppCapabilities(sender: XMPPCapabilities!, didDiscoverCapabilities caps: NSXMLElement!, forJID jid: XMPPJID!) {
NSLog("xmppCapabilities %@",jid.bare());
}
#endif
} | apache-2.0 | 1bcb9f59586665245438231687bb25d4 | 31.909341 | 179 | 0.651194 | 5.34971 | false | false | false | false |
object-kazu/JabberwockProtoType | JabberWock/JabberWock/ViewController.swift | 1 | 1867 | //
// ViewController.swift
// JabberWock
//
// Created by 清水 一征 on 2016/12/01.
// Copyright © 2016年 momiji-mac. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
jqueryLoad()
// パスを取得する
// ドキュメントパス
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
// ファイル名
let fileName = EXPORT_TEST_File
// // 保存する場所
let path = documentsPath + "/" + fileName
let url = NSURL(string: path)!
// リクエストを生成する
let request = NSURLRequest(url: url as URL)
// リクエストを投げる
webView.loadRequest(request as URLRequest)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// ロード時にインジケータをまわす
func webViewDidStartLoad(_ webView: UIWebView) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
print("indicator on")
}
// ロード完了でインジケータ非表示
func webViewDidFinishLoad(_ webView: UIWebView) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
print("indicator off")
}
// js load
func jqueryLoad(){
let path = Bundle.main.path(forResource: "jquery-3.1.1.min", ofType: "js")
let jsCode = try? String(contentsOfFile: path!, encoding: String.Encoding.utf8)
webView.stringByEvaluatingJavaScript(from: jsCode!)
}
}
| mit | 368d6dda3f38d0b8a30893a14286a876 | 25.65625 | 119 | 0.629543 | 4.47769 | false | false | false | false |
kuririnz/KkListActionSheet-Swift | KkListActionSheetSwift/source/KkListActionSheet.swift | 1 | 16178 | //
// KkListActionSheet.swift
// KkListActionSheetSwift
//
// Created by keisuke kuribayashi on 2015/10/11.
// Copyright © 2015年 keisuke kuribayashi. All rights reserved.
//
import UIKit
let ANIM_ALPHA_KEY = "animAlpha"
let ANIM_MOVE_KEY = "animMove"
let ORIENT_VERTICAL = "PORTRAIT"
let ORIENT_HORIZONTAL = "LANDSCAPE"
var styleIndex = HIGHSTYLE.DEFAULT
public enum HIGHSTYLE : Int {
case DEFAULT = 0
case MIDDLE = 1
case LOW = 2
}
@objc public protocol KkListActionSheetDelegate: class {
// required Delegate MEthod
// set row index
func kkTableView(tableView: UITableView, rowsInSection section: NSInteger) -> NSInteger
// create row cell instance
func kkTableView(tableView: UITableView, currentIndx indexPath: NSIndexPath) -> UITableViewCell
// oprional Delegate Method
// set the selected item Action in this tableview
optional func kkTableView(tableView: UITableView, selectIndex indexPath: NSIndexPath)
// set each row height in this tableview
optional func kkTableView(tableView: UITableView, heightRowIndex indexPath: NSIndexPath) -> CGFloat
}
public class KkListActionSheet: UIView, UITableViewDelegate, UITableViewDataSource {
// MARK: self delegate
public weak var delegate : KkListActionSheetDelegate! = nil
// MARK: Member Variable
@IBOutlet weak var kkTableView : UITableView!
@IBOutlet weak var kkActionSheetBackGround : UIView!
@IBOutlet weak var kkActionSheet : UIView!
@IBOutlet weak var titleLabel : UILabel!
@IBOutlet weak var kkCloseButton : KkListCloseButton!
var displaySize : CGRect = CGRectMake(0, 0, 0, 0)
var centerY : CGFloat = 0.0
var orientList : NSArray = []
var supportOrientList : NSArray = []
var animatingFlg : Bool = false
var screenStyle : CGSize = CGSizeMake(0, 0)
// MARK: initialized
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// init process
displaySize = UIScreen.mainScreen().bounds
self.setHighPosition()
orientList = ["UIInterfaceOrientationPortrait",
"UIInterfaceOrientationPortraitUpsideDown",
"UIInterfaceOrientationLandscapeLeft",
"UIInterfaceOrientationLandscapeRight"]
if Float(UIDevice.currentDevice().systemVersion) > 8.0 {
supportOrientList = NSBundle.mainBundle().objectForInfoDictionaryKey("UISupportedInterfaceOrientations") as! NSArray
} else {
let infoDictionary = NSBundle.mainBundle().infoDictionary! as Dictionary
supportOrientList = infoDictionary["UISupportedInterfaceOrientations"]! as! NSArray
}
self.hidden = true
}
override public func awakeFromNib() {
super.awakeFromNib()
self.initialKkListActionSheet()
}
public class func createInit(parent: UIViewController) -> KkListActionSheet {
let className = NSStringFromClass(KkListActionSheet)
let currentIdx = className.rangeOfString(".")
styleIndex = HIGHSTYLE.DEFAULT
// NSBundleを調べる
let frameworkBundle = NSBundle(forClass: KkListActionSheet.self)
let nib = UINib(nibName: className.substringFromIndex(currentIdx!.endIndex), bundle: frameworkBundle)
let initClass = nib.instantiateWithOwner(nil, options: nil).first as! KkListActionSheet
parent.view.addSubview(initClass)
return initClass
}
public class func createInit(parent: UIViewController, style styleIdx:HIGHSTYLE) -> KkListActionSheet {
let className = NSStringFromClass(KkListActionSheet)
let currentIdx = className.rangeOfString(".")
styleIndex = styleIdx
let initClass = NSBundle.mainBundle().loadNibNamed(className.substringFromIndex(currentIdx!.endIndex), owner: nil, options: nil).first as! KkListActionSheet
parent.view.addSubview(initClass)
return initClass
}
// initial Method
private func initialKkListActionSheet() {
animatingFlg = false
// Set BackGround Alpha
kkActionSheetBackGround.alpha = 0.0
let largeOrientation = displaySize.size.width > displaySize.size.height ? displaySize.size.width:displaySize.size.height
// Setting BackGround Layout
kkActionSheetBackGround.translatesAutoresizingMaskIntoConstraints = true
var kkActionSheetBgRect = kkActionSheetBackGround.frame as CGRect
kkActionSheetBgRect.size.width = largeOrientation
kkActionSheetBgRect.size.height = largeOrientation
kkActionSheetBackGround.frame = kkActionSheetBgRect
// Setting ListActionSheet Layout
kkActionSheet.translatesAutoresizingMaskIntoConstraints = true
var kkActionSheetRect = kkActionSheet.frame as CGRect
kkActionSheetRect.origin = CGPointMake(0, displaySize.size.height - screenStyle.height)
kkActionSheetRect.size.width = displaySize.size.width
kkActionSheetRect.size.height = screenStyle.height
kkActionSheet.frame = kkActionSheetRect
// Setting CloseButton Layout
kkCloseButton.translatesAutoresizingMaskIntoConstraints = true
var closeBtnRect = kkCloseButton.frame
closeBtnRect.size.width = largeOrientation
closeBtnRect.size.height = displaySize.size.height * 0.085
let tmpX = closeBtnRect.size.width - displaySize.size.width
closeBtnRect.origin = CGPointMake(tmpX > 0 ? tmpX / 2 : 0, 0)
kkCloseButton.frame = closeBtnRect
centerY = kkActionSheet.center.y
// TapGesuture Event
let backGroundGesture = UITapGestureRecognizer(target: self, action: Selector("onTapGesture:"))
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("onTapGesture:"))
kkActionSheetBackGround.addGestureRecognizer(backGroundGesture)
kkCloseButton.addGestureRecognizer(tapGesture)
// PanGesture Event
if styleIndex != HIGHSTYLE.LOW {
let panGesture = UIPanGestureRecognizer(target: self, action: Selector("onPanGesture:"))
kkCloseButton.addGestureRecognizer(panGesture)
}
// set device change notification center
if supportOrientList.count > 1 {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "didRotation:",
name: "UIDeviceOrientationDidChangeNotification",
object: nil)
}
}
func setHighPosition () {
screenStyle.width = displaySize.width
if displaySize.size.width > displaySize.size.height {
screenStyle.height = styleIndex == HIGHSTYLE.DEFAULT ? displaySize.size.height * 2 / 3 : displaySize.size.height / 2
} else {
if styleIndex == HIGHSTYLE.MIDDLE {
screenStyle.height = displaySize.size.height / 2
} else if styleIndex == HIGHSTYLE.LOW {
screenStyle.height = displaySize.size.height / 3
} else {
screenStyle.height = displaySize.size.height * 2 / 3
}
}
}
public func setHiddenTitle () {
titleLabel.translatesAutoresizingMaskIntoConstraints = true
titleLabel.hidden = true
var tmpRect = titleLabel.frame
tmpRect.size.height = 0
titleLabel.frame = tmpRect
}
public func setHiddenScrollbar (value: Bool) {
kkTableView.showsVerticalScrollIndicator = value
kkTableView.showsHorizontalScrollIndicator = value
}
// MARK: Customize Method
public func setTitle (title: String) {
self.titleLabel.text = title
}
public func setAttrTitle (attrTitle: NSAttributedString) {
self.titleLabel.attributedText = attrTitle
}
// MARK: Gesture Recognizer Action
func onTapGesture(recognizer: UITapGestureRecognizer) {
self.showHide()
}
func onPanGesture(recognizer: UIPanGestureRecognizer) {
let location = recognizer.translationInView(self)
var moveRect = self.kkActionSheet.frame
let afterPosition = moveRect.origin.y + location.y
if recognizer.state == UIGestureRecognizerState.Ended {
if centerY > afterPosition {
self.kkListActionSheetReturenAnimation(afterPosition)
} else {
self.kkListActionSheetAnimation(afterPosition)
}
} else {
let checkHeight = styleIndex == HIGHSTYLE.DEFAULT ? displaySize.size.height / 3 : screenStyle.height
if checkHeight < afterPosition {
moveRect.origin = CGPointMake(0, afterPosition)
self.kkActionSheet.frame = moveRect
}
}
recognizer.setTranslation(CGPointZero, inView: self)
}
// MARK: KkListAction Animation Method
public func showHide () {
self.kkListActionSheetAnimation(self.kkActionSheet.frame.size.height)
}
private func kkListActionSheetAnimation (param: CGFloat) {
if animatingFlg { return }
animatingFlg = true
var fromPositionY :CGFloat
var toPositionY :CGFloat
var toAlpha :CGFloat
let currentAlpha = kkActionSheetBackGround.alpha
if currentAlpha == 0.0 {
fromPositionY = param
toPositionY = 0
toAlpha = 0.8
} else {
fromPositionY = 0.0
toPositionY = param
toAlpha = 0.0
}
let moveAnim = CABasicAnimation(keyPath: "transform.translation.y")
moveAnim.duration = 0.5
moveAnim.repeatCount = 1
moveAnim.autoreverses = false
moveAnim.removedOnCompletion = false
moveAnim.fillMode = kCAFillModeForwards
moveAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
moveAnim.fromValue = fromPositionY as NSNumber
moveAnim.toValue = toPositionY as NSNumber
let alphaAnim = CABasicAnimation(keyPath: "opacity")
alphaAnim.delegate = self
alphaAnim.duration = 0.4
alphaAnim.repeatCount = 1
alphaAnim.autoreverses = false
alphaAnim.removedOnCompletion = false
alphaAnim.fillMode = kCAFillModeForwards
alphaAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
alphaAnim.fromValue = currentAlpha as NSNumber
alphaAnim.toValue = toAlpha
self.hidden = false
kkActionSheet.layer.addAnimation(moveAnim, forKey: ANIM_MOVE_KEY)
kkActionSheetBackGround.layer.addAnimation(alphaAnim, forKey: ANIM_ALPHA_KEY)
}
private func kkListActionSheetReturenAnimation(param: CGFloat) {
if animatingFlg { return }
animatingFlg = true
UIView.animateWithDuration(0.5,
delay: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: {
var tmp = self.kkActionSheet.frame as CGRect
tmp.origin = CGPointMake(0, self.displaySize.height - self.screenStyle.height)
self.kkActionSheet.frame = tmp
}, completion: {(finish: Bool) in
self.animatingFlg = false
}
)
}
// MARK: CABasicAnimation Inheritance Method
override public func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if anim == kkActionSheetBackGround.layer.animationForKey(ANIM_ALPHA_KEY) {
let currentAnimation = anim as! CABasicAnimation
kkActionSheetBackGround.alpha = currentAnimation.toValue as! CGFloat
kkActionSheetBackGround.layer.removeAnimationForKey(ANIM_ALPHA_KEY)
if kkActionSheetBackGround.alpha == 0.0 {
self.hidden = true
var tmpPosition = kkActionSheet.frame
tmpPosition.origin = CGPointMake(0, displaySize.size.height - screenStyle.height)
kkActionSheet.frame = tmpPosition
}
animatingFlg = false
}
}
// MARK: Change Device Rotate Method
func didRotation(notification: NSNotification) {
let orientation = UIDevice.currentDevice().orientation as UIDeviceOrientation
if !orientation.isPortrait && !orientation.isLandscape { return }
let nowRotate = orientList.objectAtIndex(orientation.rawValue - 1) as! String
if orientation.isPortrait {
if self.supportOrientList.indexOfObject(nowRotate) != NSNotFound { self.changeOrientationTransform(nowRotate) }
} else if orientation.isLandscape {
if self.supportOrientList.indexOfObject(nowRotate) != NSNotFound { self.changeOrientationTransform(nowRotate) }
}
}
private func changeOrientationTransform (orientState: String) {
if !animatingFlg {
UIView.animateWithDuration(0.5,
delay: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: {
if Float(UIDevice.currentDevice().systemVersion) > 9.0 {
self.displaySize.size = UIScreen.mainScreen().bounds.size
} else {
let tmpWidth = UIScreen.mainScreen().bounds.size.width
let tmpHeight = UIScreen.mainScreen().bounds.size.height
let isLargeWidth = tmpWidth > tmpHeight
if orientState == ORIENT_VERTICAL {
self.displaySize.size.width = isLargeWidth ? tmpHeight: tmpWidth
self.displaySize.size.height = isLargeWidth ? tmpWidth : tmpHeight
} else if orientState == ORIENT_HORIZONTAL {
self.displaySize.size.width = isLargeWidth ? tmpWidth : tmpHeight
self.displaySize.size.height = isLargeWidth ? tmpHeight : tmpWidth
}
}
self.setHighPosition()
let tmpX = self.kkCloseButton.frame.size.width - self.displaySize.size.width
self.kkActionSheet.translatesAutoresizingMaskIntoConstraints = true
self.kkActionSheet.frame.origin = CGPointMake(0, self.displaySize.size.height - self.screenStyle.height)
self.kkActionSheet.frame.size.width = self.displaySize.size.width
self.kkActionSheet.frame.size.height = self.screenStyle.height
self.kkCloseButton.frame.origin = CGPointMake(tmpX > 0 ? -(tmpX / 2) : 0, 0)
self.centerY = self.kkActionSheet.center.y;
},
completion: {(finish: Bool) in
self.animatingFlg = false
})
}
}
// MARK: UITableView Delegate / Datasource
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return self.delegate.kkTableView(tableView, currentIndx: indexPath)
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.delegate.kkTableView(tableView, rowsInSection: section)
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.delegate.kkTableView!(tableView, selectIndex: indexPath)
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var tmpHeight = self.delegate.kkTableView?(tableView, heightRowIndex: indexPath)
if tmpHeight == nil {
let cell = self.tableView(tableView, cellForRowAtIndexPath: indexPath)
tmpHeight = cell.frame.size.height
}
return tmpHeight!
}
}
| mit | 24dff01f576a8a4696da565347b7ff8e | 42.343164 | 164 | 0.647739 | 5.594118 | false | false | false | false |
Jnosh/swift | test/expr/closure/closures.swift | 6 | 13781 | // RUN: %target-typecheck-verify-swift
var func6 : (_ fn : (Int,Int) -> Int) -> ()
var func6a : ((Int, Int) -> Int) -> ()
var func6b : (Int, (Int, Int) -> Int) -> ()
func func6c(_ f: (Int, Int) -> Int, _ n: Int = 0) {}
// Expressions can be auto-closurified, so that they can be evaluated separately
// from their definition.
var closure1 : () -> Int = {4} // Function producing 4 whenever it is called.
var closure2 : (Int,Int) -> Int = { 4 } // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{36-36= _,_ in}}
var closure3a : () -> () -> (Int,Int) = {{ (4, 2) }} // multi-level closing.
var closure3b : (Int,Int) -> (Int) -> (Int,Int) = {{ (4, 2) }} // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{52-52=_,_ in }}
var closure4 : (Int,Int) -> Int = { $0 + $1 }
var closure5 : (Double) -> Int = {
$0 + 1.0 // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}}
}
var closure6 = $0 // expected-error {{anonymous closure argument not contained in a closure}}
var closure7 : Int =
{ 4 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{9-9=()}}
var capturedVariable = 1
var closure8 = { [capturedVariable] in
capturedVariable += 1 // expected-error {{left side of mutating operator isn't mutable: 'capturedVariable' is an immutable capture}}
}
func funcdecl1(_ a: Int, _ y: Int) {}
func funcdecl3() -> Int {}
func funcdecl4(_ a: ((Int) -> Int), _ b: Int) {}
func funcdecl5(_ a: Int, _ y: Int) {
// Pass in a closure containing the call to funcdecl3.
funcdecl4({ funcdecl3() }, 12) // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{14-14= _ in}}
func6({$0 + $1}) // Closure with two named anonymous arguments
func6({($0) + $1}) // Closure with sequence expr inferred type
func6({($0) + $0}) // // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
var testfunc : ((), Int) -> Int // expected-note {{'testfunc' declared here}}
testfunc({$0+1}) // expected-error {{missing argument for parameter #2 in call}}
funcdecl5(1, 2) // recursion.
// Element access from a tuple.
var a : (Int, f : Int, Int)
var b = a.1+a.f
// Tuple expressions with named elements.
var i : (y : Int, x : Int) = (x : 42, y : 11)
funcdecl1(123, 444)
// Calls.
4() // expected-error {{cannot call value of non-function type 'Int'}}{{4-6=}}
// rdar://12017658 - Infer some argument types from func6.
func6({ a, b -> Int in a+b})
// Return type inference.
func6({ a,b in a+b })
// Infer incompatible type.
func6({a,b -> Float in 4.0 }) // expected-error {{declared closure result 'Float' is incompatible with contextual type 'Int'}} {{17-22=Int}} // Pattern doesn't need to name arguments.
func6({ _,_ in 4 })
func6({a,b in 4.0 }) // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}}
// TODO: This diagnostic can be improved: rdar://22128205
func6({(a : Float, b) in 4 }) // expected-error {{cannot convert value of type '(Float, _) -> Int' to expected argument type '(Int, Int) -> Int'}}
var fn = {}
var fn2 = { 4 }
var c : Int = { a,b -> Int in a+b} // expected-error{{cannot convert value of type '(Int, Int) -> Int' to specified type 'Int'}}
}
func unlabeledClosureArgument() {
func add(_ x: Int, y: Int) -> Int { return x + y }
func6a({$0 + $1}) // single closure argument
func6a(add)
func6b(1, {$0 + $1}) // second arg is closure
func6b(1, add)
func6c({$0 + $1}) // second arg is default int
func6c(add)
}
// rdar://11935352 - closure with no body.
func closure_no_body(_ p: () -> ()) {
return closure_no_body({})
}
// rdar://12019415
func t() {
let u8 : UInt8 = 1
let x : Bool = true
if 0xA0..<0xBF ~= Int(u8) && x {
}
}
// <rdar://problem/11927184>
func f0(_ a: Any) -> Int { return 1 }
assert(f0(1) == 1)
var selfRef = { selfRef() } // expected-error {{variable used within its own initial value}}
var nestedSelfRef = {
var recursive = { nestedSelfRef() } // expected-error {{variable used within its own initial value}}
recursive()
}
var shadowed = { (shadowed: Int) -> Int in
let x = shadowed
return x
} // no-warning
var shadowedShort = { (shadowedShort: Int) -> Int in shadowedShort+1 } // no-warning
func anonymousClosureArgsInClosureWithArgs() {
func f(_: String) {}
var a1 = { () in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a2 = { () -> Int in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a3 = { (z: Int) in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{26-28=z}}
var a4 = { (z: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{7-9=z}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
var a5 = { (_: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
}
func doStuff(_ fn : @escaping () -> Int) {}
func doVoidStuff(_ fn : @escaping () -> ()) {}
// <rdar://problem/16193162> Require specifying self for locations in code where strong reference cycles are likely
class ExplicitSelfRequiredTest {
var x = 42
func method() -> Int {
// explicit closure requires an explicit "self." base.
doVoidStuff({ self.x += 1 })
doStuff({ x+1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}}
doVoidStuff({ x += 1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{19-19=self.}}
// Methods follow the same rules as properties, uses of 'self' must be marked with "self."
doStuff { method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}}
doVoidStuff { _ = method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{23-23=self.}}
doStuff { self.method() }
// <rdar://problem/18877391> "self." shouldn't be required in the initializer expression in a capture list
// This should not produce an error, "x" isn't being captured by the closure.
doStuff({ [myX = x] in myX })
// This should produce an error, since x is used within the inner closure.
doStuff({ [myX = {x}] in 4 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{23-23=self.}}
// expected-warning @-1 {{capture 'myX' was never used}}
return 42
}
}
class SomeClass {
var field : SomeClass?
func foo() -> Int {}
}
func testCaptureBehavior(_ ptr : SomeClass) {
// Test normal captures.
weak var wv : SomeClass? = ptr
unowned let uv : SomeClass = ptr
unowned(unsafe) let uv1 : SomeClass = ptr
unowned(safe) let uv2 : SomeClass = ptr
doStuff { wv!.foo() }
doStuff { uv.foo() }
doStuff { uv1.foo() }
doStuff { uv2.foo() }
// Capture list tests
let v1 : SomeClass? = ptr
let v2 : SomeClass = ptr
doStuff { [weak v1] in v1!.foo() }
// expected-warning @+2 {{variable 'v1' was written to, but never read}}
doStuff { [weak v1, // expected-note {{previous}}
weak v1] in v1!.foo() } // expected-error {{definition conflicts with previous value}}
doStuff { [unowned v2] in v2.foo() }
doStuff { [unowned(unsafe) v2] in v2.foo() }
doStuff { [unowned(safe) v2] in v2.foo() }
doStuff { [weak v1, weak v2] in v1!.foo() + v2!.foo() }
let i = 42
// expected-warning @+1 {{variable 'i' was never mutated}} {{19-20=let}}
doStuff { [weak i] in i! } // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
}
extension SomeClass {
func bar() {
doStuff { [unowned self] in self.foo() }
doStuff { [unowned xyz = self.field!] in xyz.foo() }
doStuff { [weak xyz = self.field] in xyz!.foo() }
// rdar://16889886 - Assert when trying to weak capture a property of self in a lazy closure
doStuff { [weak self.field] in field!.foo() } // expected-error {{fields may only be captured by assigning to a specific name}} expected-error {{reference to property 'field' in closure requires explicit 'self.' to make capture semantics explicit}} {{36-36=self.}}
// expected-warning @+1 {{variable 'self' was written to, but never read}}
doStuff { [weak self&field] in 42 } // expected-error {{expected ']' at end of capture list}}
}
func strong_in_capture_list() {
// <rdar://problem/18819742> QOI: "[strong self]" in capture list generates unhelpful error message
_ = {[strong self] () -> () in return } // expected-error {{expected 'weak', 'unowned', or no specifier in capture list}}
}
}
// <rdar://problem/16955318> Observed variable in a closure triggers an assertion
var closureWithObservedProperty: () -> () = {
var a: Int = 42 {
willSet {
_ = "Will set a to \(newValue)"
}
didSet {
_ = "Did set a with old value of \(oldValue)"
}
}
}
;
{}() // expected-error{{top-level statement cannot begin with a closure expression}}
// rdar://19179412 - Crash on valid code.
func rdar19179412() -> (Int) -> Int {
return { x in
class A {
let d : Int = 0
}
}
}
// Test coercion of single-expression closure return types to void.
func takesVoidFunc(_ f: () -> ()) {}
var i: Int = 1
// expected-warning @+1 {{expression of type 'Int' is unused}}
takesVoidFunc({i})
// expected-warning @+1 {{expression of type 'Int' is unused}}
var f1: () -> () = {i}
var x = {return $0}(1)
func returnsInt() -> Int { return 0 }
takesVoidFunc(returnsInt) // expected-error {{cannot convert value of type '() -> Int' to expected argument type '() -> ()'}}
takesVoidFunc({() -> Int in 0}) // expected-error {{declared closure result 'Int' is incompatible with contextual type '()'}} {{22-25=()}}
// These used to crash the compiler, but were fixed to support the implementation of rdar://problem/17228969
Void(0) // expected-error{{argument passed to call that takes no arguments}}
_ = {0}
// <rdar://problem/22086634> "multi-statement closures require an explicit return type" should be an error not a note
let samples = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{16-16= () -> Bool in }}
if (i > 10) { return true }
else { return false }
}()
// <rdar://problem/19756953> Swift error: cannot capture '$0' before it is declared
func f(_ fp : (Bool, Bool) -> Bool) {}
f { $0 && !$1 }
// <rdar://problem/18123596> unexpected error on self. capture inside class method
func TakesIntReturnsVoid(_ fp : ((Int) -> ())) {}
struct TestStructWithStaticMethod {
static func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
class TestClassWithStaticMethod {
class func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
// Test that we can infer () as the result type of these closures.
func genericOne<T>(_ a: () -> T) {}
func genericTwo<T>(_ a: () -> T, _ b: () -> T) {}
genericOne {}
genericTwo({}, {})
// <rdar://problem/22344208> QoI: Warning for unused capture list variable should be customized
class r22344208 {
func f() {
let q = 42
let _: () -> Int = {
[unowned self, // expected-warning {{capture 'self' was never used}}
q] in // expected-warning {{capture 'q' was never used}}
1 }
}
}
var f = { (s: Undeclared) -> Int in 0 } // expected-error {{use of undeclared type 'Undeclared'}}
// <rdar://problem/21375863> Swift compiler crashes when using closure, declared to return illegal type.
func r21375863() {
var width = 0
var height = 0
var bufs: [[UInt8]] = (0..<4).map { _ -> [asdf] in // expected-error {{use of undeclared type 'asdf'}}
[UInt8](repeating: 0, count: width*height)
}
}
// <rdar://problem/25993258>
// Don't crash if we infer a closure argument to have a tuple type containing inouts.
func r25993258_helper(_ fn: (inout Int, Int) -> ()) {}
func r25993258a() {
r25993258_helper { x in () } // expected-error {{named parameter has type '(inout Int, Int)' which includes nested inout parameters}}
}
func r25993258b() {
r25993258_helper { _ in () }
}
// We have to map the captured var type into the right generic environment.
class GenericClass<T> {}
func lvalueCapture<T>(c: GenericClass<T>) {
var cc = c
weak var wc = c
func innerGeneric<U>(_: U) {
_ = cc
_ = wc
cc = wc!
}
}
| apache-2.0 | 5a29125c47230886534e3c179d0d63e0 | 37.819718 | 270 | 0.640955 | 3.55547 | false | false | false | false |
simonnarang/Fandom | Desktop/Fandom-IOS-master/Fandomm/TabBarViewController.swift | 1 | 1973 | //
// TabBarViewController.swift
// Fandomm
//
// Created by Simon Narang on 11/29/15.
// Copyright © 2015 Simon Narang. All rights reserved.
//
import UIKit
class TabBarViewController: UITabBarController {
var usernameTwo = String()
override func viewDidLoad() {
super.viewDidLoad()
let dataTransferViewControllerOne = (self.viewControllers?[0] as! UINavigationController).viewControllers[0] as! FeedTableViewController
dataTransferViewControllerOne.usernameTwoTextOne = usernameTwo
let dataTransferViewControllerTwo = (self.viewControllers?[1] as! UINavigationController).viewControllers[0] as! SearchTableViewController
dataTransferViewControllerTwo.usernameTwoTextTwo = usernameTwo
let dataTransferViewControllerThree = (self.viewControllers?[2] as! UINavigationController).viewControllers[0] as! PostViewController
dataTransferViewControllerThree.usernameTwoTextThree = usernameTwo
let dataTransferViewControllerFour = (self.viewControllers?[3] as! UINavigationController).viewControllers[0] as! ProfileViewController
dataTransferViewControllerFour.usernameTwoTextFour = usernameTwo
let dataTransferViewControllerFive = (self.viewControllers?[4] as! UINavigationController).viewControllers[0] as! PreferecesTableViewController
dataTransferViewControllerFive.userameTwoTextFive = usernameTwo
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| unlicense | 50ae5a94f2d0c1a725a9694c99ad496f | 40.083333 | 151 | 0.742901 | 5.921922 | false | false | false | false |
onebytecode/krugozor-iOSVisitors | krugozor-visitorsApp/Visit.swift | 1 | 432 | //
// Visit.swift
// krugozor-visitorsApp
//
// Created by Alexander Danilin on 21/10/2017.
// Copyright © 2017 oneByteCode. All rights reserved.
//
import Foundation
import RealmSwift
class Visit: Object {
@objc dynamic var id = 0
@objc dynamic var startAt = ""
@objc dynamic var startDate = ""
@objc dynamic var finishDate = ""
@objc dynamic var duration = 0
@objc dynamic var totalPrice = 0
}
| apache-2.0 | 747218f6e920f4b7ce077af532913513 | 20.55 | 54 | 0.663573 | 3.652542 | false | false | false | false |
jwalsh/mal | swift3/Sources/types.swift | 3 | 6077 |
enum MalError: ErrorType {
case Reader(msg: String)
case General(msg: String)
case MalException(obj: MalVal)
}
class MutableAtom {
var val: MalVal
init(val: MalVal) {
self.val = val
}
}
enum MalVal {
case MalNil
case MalTrue
case MalFalse
case MalInt(Int)
case MalFloat(Float)
case MalString(String)
case MalSymbol(String)
case MalList(Array<MalVal>, meta: Array<MalVal>?)
case MalVector(Array<MalVal>, meta: Array<MalVal>?)
case MalHashMap(Dictionary<String,MalVal>, meta: Array<MalVal>?)
// TODO: internal MalVals are wrapped in arrays because otherwise
// compiler throws a fault
case MalFunc((Array<MalVal>) throws -> MalVal,
ast: Array<MalVal>?,
env: Env?,
params: Array<MalVal>?,
macro: Bool,
meta: Array<MalVal>?)
case MalAtom(MutableAtom)
}
typealias MV = MalVal
// General functions
func wraptf(a: Bool) -> MalVal {
return a ? MV.MalTrue : MV.MalFalse
}
// equality functions
func cmp_seqs(a: Array<MalVal>, _ b: Array<MalVal>) -> Bool {
if a.count != b.count { return false }
var idx = a.startIndex
while idx < a.endIndex {
if !equal_Q(a[idx], b[idx]) { return false }
idx = idx.successor()
}
return true
}
func cmp_maps(a: Dictionary<String,MalVal>,
_ b: Dictionary<String,MalVal>) -> Bool {
if a.count != b.count { return false }
for (k,v1) in a {
if b[k] == nil { return false }
if !equal_Q(v1, b[k]!) { return false }
}
return true
}
func equal_Q(a: MalVal, _ b: MalVal) -> Bool {
switch (a, b) {
case (MV.MalNil, MV.MalNil): return true
case (MV.MalFalse, MV.MalFalse): return true
case (MV.MalTrue, MV.MalTrue): return true
case (MV.MalInt(let i1), MV.MalInt(let i2)): return i1 == i2
case (MV.MalString(let s1), MV.MalString(let s2)): return s1 == s2
case (MV.MalSymbol(let s1), MV.MalSymbol(let s2)): return s1 == s2
case (MV.MalList(let l1,_), MV.MalList(let l2,_)):
return cmp_seqs(l1, l2)
case (MV.MalList(let l1,_), MV.MalVector(let l2,_)):
return cmp_seqs(l1, l2)
case (MV.MalVector(let l1,_), MV.MalList(let l2,_)):
return cmp_seqs(l1, l2)
case (MV.MalVector(let l1,_), MV.MalVector(let l2,_)):
return cmp_seqs(l1, l2)
case (MV.MalHashMap(let d1,_), MV.MalHashMap(let d2,_)):
return cmp_maps(d1, d2)
default:
return false
}
}
// list and vector functions
func list(lst: Array<MalVal>) -> MalVal {
return MV.MalList(lst, meta:nil)
}
func list(lst: Array<MalVal>, meta: MalVal) -> MalVal {
return MV.MalList(lst, meta:[meta])
}
func vector(lst: Array<MalVal>) -> MalVal {
return MV.MalVector(lst, meta:nil)
}
func vector(lst: Array<MalVal>, meta: MalVal) -> MalVal {
return MV.MalVector(lst, meta:[meta])
}
// hash-map functions
func _assoc(src: Dictionary<String,MalVal>, _ mvs: Array<MalVal>)
throws -> Dictionary<String,MalVal> {
var d = src
if mvs.count % 2 != 0 {
throw MalError.General(msg: "Odd number of args to assoc_BANG")
}
var pos = mvs.startIndex
while pos < mvs.count {
switch (mvs[pos], mvs[pos+1]) {
case (MV.MalString(let k), let mv):
d[k] = mv
default:
throw MalError.General(msg: "Invalid _assoc call")
}
pos += 2
}
return d
}
func _dissoc(src: Dictionary<String,MalVal>, _ mvs: Array<MalVal>)
throws -> Dictionary<String,MalVal> {
var d = src
for mv in mvs {
switch mv {
case MV.MalString(let k): d.removeValueForKey(k)
default: throw MalError.General(msg: "Invalid _dissoc call")
}
}
return d
}
func hash_map(dict: Dictionary<String,MalVal>) -> MalVal {
return MV.MalHashMap(dict, meta:nil)
}
func hash_map(dict: Dictionary<String,MalVal>, meta:MalVal) -> MalVal {
return MV.MalHashMap(dict, meta:[meta])
}
func hash_map(arr: Array<MalVal>) throws -> MalVal {
let d = Dictionary<String,MalVal>();
return MV.MalHashMap(try _assoc(d, arr), meta:nil)
}
// function functions
func malfunc(fn: (Array<MalVal>) throws -> MalVal) -> MalVal {
return MV.MalFunc(fn, ast: nil, env: nil, params: nil,
macro: false, meta: nil)
}
func malfunc(fn: (Array<MalVal>) throws -> MalVal,
ast: Array<MalVal>?,
env: Env?,
params: Array<MalVal>?) -> MalVal {
return MV.MalFunc(fn, ast: ast, env: env, params: params,
macro: false, meta: nil)
}
func malfunc(fn: (Array<MalVal>) throws -> MalVal,
ast: Array<MalVal>?,
env: Env?,
params: Array<MalVal>?,
macro: Bool,
meta: MalVal?) -> MalVal {
return MV.MalFunc(fn, ast: ast, env: env, params: params,
macro: macro, meta: meta != nil ? [meta!] : nil)
}
func malfunc(fn: (Array<MalVal>) throws -> MalVal,
ast: Array<MalVal>?,
env: Env?,
params: Array<MalVal>?,
macro: Bool,
meta: Array<MalVal>?) -> MalVal {
return MV.MalFunc(fn, ast: ast, env: env, params: params,
macro: macro, meta: meta)
}
// sequence functions
func _rest(a: MalVal) throws -> Array<MalVal> {
switch a {
case MV.MalList(let lst,_):
let slc = lst[lst.startIndex.successor()..<lst.endIndex]
return Array(slc)
case MV.MalVector(let lst,_):
let slc = lst[lst.startIndex.successor()..<lst.endIndex]
return Array(slc)
default:
throw MalError.General(msg: "Invalid rest call")
}
}
func rest(a: MalVal) throws -> MalVal {
return list(try _rest(a))
}
func _nth(a: MalVal, _ idx: Int) throws -> MalVal {
switch a {
case MV.MalList(let l,_): return l[l.startIndex.advancedBy(idx)]
case MV.MalVector(let l,_): return l[l.startIndex.advancedBy(idx)]
default: throw MalError.General(msg: "Invalid nth call")
}
}
| mpl-2.0 | e3753fa357c7a3bb1ca87e8ceb713da9 | 27.938095 | 71 | 0.587296 | 3.492529 | false | false | false | false |
MetalheadSanya/SideMenuController | Example/Example/AppDelegate.swift | 3 | 2729 | //
// AppDelegate.swift
// Example
//
// Created by Teodor Patras on 16/06/16.
// Copyright © 2016 teodorpatras. All rights reserved.
//
import UIKit
import SideMenuController
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
SideMenuController.preferences.drawing.menuButtonImage = UIImage(named: "menu")
SideMenuController.preferences.drawing.sidePanelPosition = .underCenterPanelLeft
SideMenuController.preferences.drawing.sidePanelWidth = 300
SideMenuController.preferences.drawing.centerPanelShadow = true
SideMenuController.preferences.animating.statusBarBehaviour = .horizontalPan
SideMenuController.preferences.animating.transitionAnimator = FadeAnimator.self
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | ba228ada55fcbb9327de92cc0f9427d7 | 52.490196 | 285 | 0.752199 | 5.779661 | false | false | false | false |
sudeepag/Phobia | Phobia/Word.swift | 1 | 714 | //
// Word.swift
// Phobia
//
// Created by Sudeep Agarwal on 11/21/15.
// Copyright © 2015 Sudeep Agarwal. All rights reserved.
//
import Foundation
import UIKit
enum WordType {
case Neutral
case TriggerSpiders
case TriggerSnakes
case TriggerHeights
}
enum ColorType {
case Red
case Blue
case Green
}
class Word: Hashable {
var color: ColorType!
var text: String!
var type: WordType!
var hashValue: Int {
return text.hashValue
}
init(text: String, color: ColorType, type: WordType) {
self.text = text
self.color = color
self.type = type
}
}
func ==(lhs: Word, rhs: Word) -> Bool {
return lhs == rhs
} | mit | 09db08bb355961fcab1b2759676d1b60 | 15.227273 | 58 | 0.611501 | 3.675258 | false | false | false | false |
AbelSu131/SimpleMemo | Memo/印象便签 WatchKit Extension/MemoInterfaceController.swift | 1 | 3717 | //
// MemoInterfaceController.swift
// Memo
//
// Created by 李俊 on 15/8/8.
// Copyright (c) 2015年 李俊. All rights reserved.
//
import WatchKit
import Foundation
import WatchConnectivity
class MemoInterfaceController: WKInterfaceController {
@IBOutlet weak var memoTable: WKInterfaceTable!
var newMemo = [String: AnyObject]()
var memos = [[String: AnyObject]]()
var isPush = false
var wcSession: WCSession?
lazy var sharedDefaults: NSUserDefaults? = {
return NSUserDefaults(suiteName: "group.likumb.com.Memo")
}()
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
wcSession = sharedSession()
loadData(sharedDefaults)
// setTable()
}
@IBAction func addMemo() {
self.presentTextInputControllerWithSuggestions(nil, allowedInputMode: .Plain, completion: { (content) -> Void in
if content == nil {
return
}
if let text = content?[0] as? String {
self.saveNewMemo(text)
self.setTable()
}
})
}
private func saveNewMemo(content: String){
var memo = [String: AnyObject]()
memo["text"] = content
memo["changeDate"] = NSDate()
memos.insert(memo, atIndex: 0)
shareMessage(memo)
// 将新笔记共享给iPhone
let sharedDefaults = NSUserDefaults(suiteName: "group.likumb.com.Memo")
var results = sharedDefaults?.objectForKey("MemoContent") as? [AnyObject]
if results != nil {
results!.append(memo)
sharedDefaults?.setObject(results, forKey: "MemoContent")
} else{
let contents = [memo]
sharedDefaults?.setObject(contents, forKey: "MemoContent")
}
// 共享apple watch共享数据池里的数据
sharedDefaults?.setObject(memos, forKey: "WatchMemo")
sharedDefaults!.synchronize()
}
func setTable(){
memoTable.setNumberOfRows(memos.count, withRowType: "memoRow")
for (index, memo) in memos.enumerate() {
let controller = memoTable.rowControllerAtIndex(index) as! MemoRowController
let text = memo["text"] as! String
let memoText = text.deleteBlankLine()
controller.memoLabel.setText(memoText)
}
}
func loadData(userDefaults: NSUserDefaults?){
let data = userDefaults?.objectForKey("WatchMemo") as? [[String: AnyObject]]
if let memoList = data {
memos = memoList
}
setTable()
}
override func willActivate() {
super.willActivate()
if !isPush {
loadData(sharedDefaults)
// setTable()
}
isPush = false
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? {
if segueIdentifier == "memoDetail" {
isPush = true
let memo = memos[rowIndex]
return (memo["text"] as! String)
}
return nil
}
}
| mit | 660756af9caaa45c227808c224e32376 | 23.790541 | 136 | 0.53366 | 5.286744 | false | false | false | false |
otto-schnurr/FileInput-swift | Source/FileInput.swift | 1 | 6019 | //
// FileInput.swift
//
// Created by Otto Schnurr on 8/23/2014.
// Copyright (c) 2014 Otto Schnurr. All rights reserved.
//
// MIT License
// file: ../../LICENSE.txt
// http://opensource.org/licenses/MIT
//
import Darwin
/// Creates a FileInput sequence to iterate over lines of all files listed
/// in command line arguments. If that list is empty then standard input is
/// used.
///
/// A file path of "-" is replaced with standard input.
public func input() -> FileInput {
let arguments = CommandLine.arguments.dropFirst()
guard !arguments.isEmpty else { return FileInput() }
return FileInput(filePaths: Array(arguments))
}
// MARK: -
/// A collection of characters typically ending with a newline.
/// The last line of a file might not contain a newline.
public typealias LineOfText = String
/// A sequence that vends LineOfText objects.
open class FileInput: Sequence {
public typealias Iterator = AnyIterator<LineOfText>
open func makeIterator() -> Iterator {
return AnyIterator { return self.nextLine() }
}
/// Constructs a sequence to iterate lines of standrd input.
convenience public init() {
self.init(filePath: "-")
}
/// Constructs a sequence to iterate lines of a file.
/// A filePath of "-" is replaced with standard input.
convenience public init(filePath: String) {
self.init(filePaths: [filePath])
}
/// Constructs a sequence to iterate lines over a collection of files.
/// Each filePath of "-" is replaced with standard input.
public init(filePaths: [String]) {
self.filePaths = filePaths
self.openNextFile()
}
/// The file used in the previous call to nextLine().
open var filePath: String? {
return filePaths.count > 0 ? filePaths[0] : nil
}
/// Newline characters that delimit lines are not removed.
open func nextLine() -> LineOfText? {
var result: LineOfText? = self.lines?.nextLine()
while result == nil && self.filePath != nil {
filePaths.remove(at: 0)
self.openNextFile()
result = self.lines?.nextLine()
}
return result
}
// MARK: Private
fileprivate var filePaths: [String]
fileprivate var lines: _FileLines? = nil
fileprivate func openNextFile() {
if let filePath = self.filePath {
self.lines = _FileLines.linesForFilePath(filePath)
}
}
}
// MARK: -
extension String {
/// Creates a copy of this string with no white space at the beginning.
public func removeLeadingSpace() -> String {
let characters = self.unicodeScalars
var start = characters.startIndex
while start < characters.endIndex {
if !characters[start].isSpace() {
break
}
start = characters.index(after: start)
}
return String(characters[start..<characters.endIndex])
}
/// Creates a copy of this string with no white space at the end.
public func removeTrailingSpace() -> String {
let characters = self.unicodeScalars
var end = characters.endIndex
while characters.startIndex < end {
let previousIndex = characters.index(before: end)
if !characters[previousIndex].isSpace() {
break
}
end = previousIndex
}
return String(characters[characters.startIndex..<end])
}
/// - returns: An index of the first white space character in this string.
public func findFirstSpace() -> String.Index? {
var result: String.Index? = nil
for index in self.indices {
if self[index].isSpace() {
result = index
break
}
}
return result
}
}
// MARK: - Private
private let _stdinPath = "-"
private class _FileLines: Sequence {
typealias Iterator = AnyIterator<LineOfText>
let file: UnsafeMutablePointer<FILE>?
var charBuffer = [CChar](repeating: 0, count: 512)
init(file: UnsafeMutablePointer<FILE>) {
self.file = file
}
deinit {
if file != nil {
fclose(file)
}
}
class func linesForFilePath(_ filePath: String) -> _FileLines? {
var lines: _FileLines? = nil
if filePath == _stdinPath {
lines = _FileLines(file: __stdinp)
} else {
let file = fopen(filePath, "r")
if file == nil {
print("can't open \(filePath)")
}
else {
lines = _FileLines(file: file!)
}
}
return lines
}
func makeIterator() -> Iterator { return AnyIterator { self.nextLine() } }
func nextChunk() -> String? {
var result: String? = nil;
if file != nil {
if fgets(&charBuffer, Int32(charBuffer.count), file) != nil {
result = String(cString: charBuffer)
}
}
return result
}
func nextLine() -> LineOfText? {
var line: LineOfText = LineOfText()
while let nextChunk = self.nextChunk() {
line += nextChunk
if line.hasSuffix("\n") {
break
}
}
return line.isEmpty ? nil : line
}
}
// MARK: - Private
extension Character {
fileprivate func isSpace() -> Bool {
let characterString = String(self)
for uCharacter in characterString.unicodeScalars {
if !uCharacter.isSpace() {
return false
}
}
return true
}
}
extension UnicodeScalar {
fileprivate func isSpace() -> Bool {
let wCharacter = wint_t(self.value)
return iswspace(wCharacter) != 0
}
}
| mit | 9709e6f9e1c137fc2d922acfc74c4602 | 24.612766 | 78 | 0.564213 | 4.784579 | false | false | false | false |
eebean2/RS_Combat | RS Combat/OSMain.swift | 1 | 15368 | //
// OSMain.swift
// RS Combat
//
// Created by Erik Bean on 2/8/17.
// Copyright © 2017 Erik Bean. All rights reserved.
//
import UIKit
import GoogleMobileAds
class OSMain: UIViewController, UITextFieldDelegate {
// Static Get Levels
@IBOutlet var staticAttack: UILabel!
@IBOutlet var staticStrength: UILabel!
@IBOutlet var staticDefence: UILabel!
@IBOutlet var staticMagic: UILabel!
@IBOutlet var staticRange: UILabel!
@IBOutlet var staticPrayer: UILabel!
@IBOutlet var staticHP: UILabel!
// Get Level TextFields
@IBOutlet var attackIn: UITextField!
@IBOutlet var strengthIn: UITextField!
@IBOutlet var defenceIn: UITextField!
@IBOutlet var magicIn: UITextField!
@IBOutlet var rangeIn: UITextField!
@IBOutlet var prayerIn: UITextField!
@IBOutlet var hpIn: UITextField!
// Static Set Levels
@IBOutlet var staticSetAttack: UILabel!
@IBOutlet var staticSetStrength: UILabel!
@IBOutlet var staticSetDefence: UILabel!
@IBOutlet var staticSetMagic: UILabel!
@IBOutlet var staticSetRange: UILabel!
@IBOutlet var staticSetPrayer: UILabel!
@IBOutlet var staticSetHP: UILabel!
// Set Level Labels
@IBOutlet var attackOut: UILabel!
@IBOutlet var strengthOut: UILabel!
@IBOutlet var defenceOut: UILabel!
@IBOutlet var magicOut: UILabel!
@IBOutlet var rangeOut: UILabel!
@IBOutlet var prayerOut: UILabel!
@IBOutlet var hpOut: UILabel!
// Other
@IBOutlet var button: UIButton!
@IBOutlet var scroll: UIScrollView!
@IBOutlet var currentLevel: UILabel!
@IBOutlet var currentStatic: UILabel!
@IBOutlet var nextLevel: UILabel!
@IBOutlet var nextStatic: UILabel!
@IBOutlet var needStatic: UILabel!
// Variable Management
var calculated = false
var activeField: UITextField? = nil
var lvl: Int = 0
var fightTitle: FightTitle!
var state: ButtonState = .calculate
var attack: Int {
if attackIn.text != "" {
return Int(attackIn.text!)!
} else {
return 1
}
}
var strength: Int {
if strengthIn.text != "" {
return Int(strengthIn.text!)!
} else {
return 1
}
}
var defence: Int {
if defenceIn.text != "" {
return Int(defenceIn.text!)!
} else {
return 1
}
}
var magic: Int {
if magicIn.text != "" {
return Int(magicIn.text!)!
} else {
return 1
}
}
var range: Int {
if rangeIn.text != "" {
return Int(rangeIn.text!)!
} else {
return 1
}
}
var prayer: Int {
if prayerIn.text != "" {
return Int(prayerIn.text!)!
} else {
return 1
}
}
var hp: Int {
if hpIn.text != "" {
return Int(hpIn.text!)!
} else {
return 10
}
}
// melee = floor(0.25(Defence + Hits + floor(Prayer/2)) + 0.325(Attack + Strength))
var sumPrayer: Float {
return floor(Float(prayer / 2))
}
var base: Float {
return (Float(defence) + Float(hp) + sumPrayer) / 4
}
var warrior: Float {
return (Float(attack) + Float(strength)) * 0.325
}
var ranger: Float {
return floor(Float(range) * 1.5) * 0.325
}
var mage: Float {
return floor(Float(magic) * 1.5) * 0.325
}
// View Setup, Destruction, and Keyboard Management
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: .UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name: .UIKeyboardDidHide, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
button.layer.cornerRadius = 5
view.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "768osBackground.png"))
if UIDevice().model == "iPad" {
visible()
calcuate(self)
}
let dv = UIToolbar()
dv.sizeToFit()
let db = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(donePressed))
dv.setItems([db], animated: false)
attackIn.inputAccessoryView = dv
strengthIn.inputAccessoryView = dv
defenceIn.inputAccessoryView = dv
magicIn.inputAccessoryView = dv
rangeIn.inputAccessoryView = dv
prayerIn.inputAccessoryView = dv
hpIn.inputAccessoryView = dv
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)
scroll.addGestureRecognizer(tap)
let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
bannerView.adUnitID = "ca-app-pub-9515262034988468/4212206831"
bannerView.rootViewController = self
view.addSubview(bannerView)
bannerView.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: bannerView, attribute: .bottom, relatedBy: .equal, toItem: scroll, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: bannerView, attribute: .bottom, relatedBy: .equal, toItem: scroll, attribute: .bottom, multiplier: 1, constant: 0))
let request = GADRequest()
request.testDevices = [kGADSimulatorID]
bannerView.load(request)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardDidShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardDidHide, object: nil)
}
@objc func keyboardDidShow(_ sender: Notification) {
if let userInfo = sender.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let buttonOrigin = activeField!.frame.origin
let buttonHeight = activeField!.frame.size.height
var visibleRect = view.frame
visibleRect.size.height -= keyboardSize.height
if !visibleRect.contains(buttonOrigin) {
let scrollPoint = CGPoint(x: 0, y: buttonOrigin.y - visibleRect.size.height + buttonHeight)
scroll.setContentOffset(scrollPoint, animated: true)
}
} else {
print("Scroll Error! No Keyboard Data")
}
} else {
print("Scroll Error! No Notification Information")
}
}
@objc func keyboardDidHide(_ sender: Notification) {
scroll.setContentOffset(CGPoint.zero, animated: true)
}
@objc func donePressed(_ sender: UIBarButtonItem) {
view.endEditing(true)
}
@objc func dismissKeyboard(_ sender: UITapGestureRecognizer) {
if activeField != nil {
activeField!.resignFirstResponder()
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
activeField = textField
}
// View Management
@IBAction func buttonDidPress(_ sender: UIButton) {
if !calculated { calcuate(sender) }
visible()
staticAttack.isHidden = !staticAttack.isHidden
staticStrength.isHidden = !staticStrength.isHidden
staticDefence.isHidden = !staticDefence.isHidden
staticMagic.isHidden = !staticMagic.isHidden
staticRange.isHidden = !staticRange.isHidden
staticPrayer.isHidden = !staticPrayer.isHidden
staticHP.isHidden = !staticHP.isHidden
attackIn.isHidden = !attackIn.isHidden
strengthIn.isHidden = !strengthIn.isHidden
defenceIn.isHidden = !defenceIn.isHidden
magicIn.isHidden = !magicIn.isHidden
rangeIn.isHidden = !rangeIn.isHidden
prayerIn.isHidden = !prayerIn.isHidden
hpIn.isHidden = !hpIn.isHidden
if state == .calculate {
button.setTitle(NSLocalizedString("Done", comment: ""), for: .normal)
state = .done
} else {
button.setTitle(NSLocalizedString("Calculate", comment: ""), for: .normal)
state = .calculate
}
}
func visible() {
staticSetAttack.isHidden = !staticSetAttack.isHidden
staticSetStrength.isHidden = !staticSetStrength.isHidden
staticSetDefence.isHidden = !staticSetDefence.isHidden
staticSetMagic.isHidden = !staticSetMagic.isHidden
staticSetRange.isHidden = !staticSetRange.isHidden
staticSetPrayer.isHidden = !staticSetPrayer.isHidden
staticSetHP.isHidden = !staticSetHP.isHidden
attackOut.isHidden = !attackOut.isHidden
strengthOut.isHidden = !strengthOut.isHidden
defenceOut.isHidden = !defenceOut.isHidden
magicOut.isHidden = !magicOut.isHidden
rangeOut.isHidden = !rangeOut.isHidden
prayerOut.isHidden = !prayerOut.isHidden
hpOut.isHidden = !hpOut.isHidden
needStatic.isHidden = !needStatic.isHidden
currentLevel.isHidden = !currentLevel.isHidden
currentStatic.isHidden = !currentStatic.isHidden
nextLevel.isHidden = !nextLevel.isHidden
nextStatic.isHidden = !nextStatic.isHidden
}
// Combact Calculation
@IBAction func calcuate(_ sender: AnyObject) {
if !calculated { calculated = true }
if floor(warrior + base) > floor(ranger + base) && floor(warrior + base) > floor(mage + base) {
lvl = Int(base + warrior)
fightTitle = .melee
} else if floor(ranger + base) > floor(warrior + base) && floor(ranger + base) > floor(mage + base) {
lvl = Int(base + ranger)
fightTitle = .range
} else if floor(mage + base) > floor(warrior + base) && floor(mage + base) > floor(ranger + base) {
lvl = Int(base + mage)
fightTitle = .mage
} else {
if floor(warrior + base) < floor(mage + base) && floor(warrior + base) < floor(ranger + base) {
lvl = Int(base + mage)
fightTitle = .mage
} else {
lvl = Int(base + warrior)
fightTitle = .skiller
}
}
currentLevel.text = String(lvl)
if lvl == 126 {
nextLevel.text = "Maxed"
nextLevel.sizeToFit()
} else {
nextLevel.text = String(lvl + 1)
}
// Attack
var i: Int = 1
var c: Int = 0
var temp: Int = attack
if temp == 99 {
attackOut.text = "-"
} else {
while i <= lvl {
temp += 1
let a = (Float(temp) + Float(strength)) * 0.325
i = Int(base + a)
c += 1
if i > lvl {
if c > (99 - attack) {
attackOut.text = "-"
} else {
attackOut.text = String(c)
}
}
}
}
// Strength
i = 1
c = 0
temp = strength
if temp == 99 {
strengthOut.text = "-"
} else {
while i <= lvl {
temp += 1
let a = (Float(temp) + Float(attack)) * 0.325
i = Int(base + a)
c += 1
if i > lvl {
if c > (99 - strength) {
strengthOut.text = "-"
} else {
strengthOut.text = String(c)
}
}
}
}
// Defence
i = 1
c = 0
temp = defence
if temp == 99 {
defenceOut.text = "-"
} else {
while i <= lvl {
temp += 1
let a = (Float(temp) + Float(hp) + sumPrayer) / 4
switch fightTitle! {
case .melee, .skiller:
i = Int(a + warrior)
case .range:
i = Int(a + ranger)
case .mage:
i = Int(a + mage)
}
c += 1
if i > lvl {
if c > (99 - defence) {
defenceOut.text = "-"
} else {
defenceOut.text = String(c)
}
}
}
}
// Magic
i = 1
c = 0
temp = magic
if temp == 99 {
magicOut.text = "-"
} else {
while i <= lvl {
temp += 1
let a = Float(Int(Float(temp) * 1.5)) * 0.325
i = Int(base + a)
c += 1
if i > lvl {
if c > (99 - magic) {
magicOut.text = "-"
} else {
magicOut.text = String(c)
}
}
}
}
// Range
i = 1
c = 0
temp = range
if temp == 99 {
rangeOut.text = "-"
} else {
while i <= lvl {
temp += 1
let a = Float(Int(Float(temp) * 1.5)) * 0.325
i = Int(base + a)
c += 1
if i > lvl {
if c > (99 - range) {
rangeOut.text = "-"
} else {
rangeOut.text = String(c)
}
}
}
}
// Prayer
i = 1
c = 0
temp = prayer
if temp == 99 {
prayerOut.text = "-"
} else {
while i <= lvl {
temp += 1
let a = (Float(Int(temp / 2)) + Float(defence) + Float(hp)) / 4
switch fightTitle! {
case .melee, .skiller:
i = Int(a + warrior)
case .range:
i = Int(a + ranger)
case .mage:
i = Int(a + mage)
}
c += 1
if i > lvl {
if c > (99 - prayer) {
prayerOut.text = "-"
} else {
prayerOut.text = String(c)
}
}
}
}
// HP
i = 1
c = 0
temp = hp
if temp == 99 {
hpOut.text = "-"
} else {
while i <= lvl {
temp += 1
let a = (Float(defence) + Float(temp) + sumPrayer) / 4
switch fightTitle! {
case .melee, .skiller:
i = Int(a + warrior)
case .range:
i = Int(a + ranger)
case .mage:
i = Int(a + mage)
}
c += 1
if i > lvl {
if c > (99 - hp) {
hpOut.text = "-"
} else {
hpOut.text = String(c)
}
}
}
}
}
}
| mit | aadc6b6e3a45e03fa780253e6d91ebb4 | 31.215933 | 167 | 0.515195 | 4.644001 | false | false | false | false |
ArturAzarau/chatter | Chatter/Chatter/ChatVC.swift | 1 | 1688 | //
// ChatVC.swift
// Chatter
//
// Created by Artur Azarov on 08.09.17.
// Copyright © 2017 Artur Azarov. All rights reserved.
//
import Cocoa
final class ChatVC: NSViewController {
// MARK: - Outlets
@IBOutlet weak var channelTitleLabel: NSTextField!
@IBOutlet weak var channelDescriptionLabel: NSTextField!
@IBOutlet weak var tableView: NSScrollView!
@IBOutlet weak var typingUserLabel: NSTextField!
@IBOutlet weak var messageOutlineView: NSView!
@IBOutlet weak var messageTextView: NSTextField!
@IBOutlet weak var sendMessageButton: NSButton!
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear() {
super.viewWillAppear()
setUpView()
}
// MARK: - View methods
private func setUpView() {
// setup main view
view.wantsLayer = true
view.layer?.backgroundColor = CGColor.white
// setup message outline view
messageOutlineView.wantsLayer = true
messageOutlineView.layer?.backgroundColor = CGColor.white
messageOutlineView.layer?.borderColor = NSColor.controlHighlightColor.cgColor
messageOutlineView.layer?.borderWidth = 2
messageOutlineView.layer?.cornerRadius = 5
// setup send message button
sendMessageButton.styleButtonText(button: sendMessageButton, buttonName: "Send", fontColor: .darkGray, alignment: .center, font: Fonts.avenirRegular, size: 13)
}
// MARK: - Actions
@IBAction func sendMessageButtonClicked(_ sender: NSButton) {
}
}
| mit | 593f7b46e51b8b9aeb3b8761fb86713b | 26.209677 | 167 | 0.649081 | 5.22291 | false | false | false | false |
howardhsien/EasyTaipei-iOS | EasyTaipei/EasyTaipei/controller/MapViewController.swift | 1 | 8272 | //
// MapViewController.swift
// EasyTaipei
//
// Created by howard hsien on 2016/7/5.
// Copyright © 2016年 AppWorks School Hsien. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController{
//MARK: outlets
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var detailPanel: UIView!
@IBOutlet weak var detailPanelTitleLabel: UILabel!
@IBOutlet weak var detailPanelSubtitleLabel: UILabel!
@IBOutlet weak var detailPanelSideLabel: UILabel!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var mapNavigateButton: UIButton!
@IBOutlet weak var markerImageView: UIImageView!
//MARK: helpers
var locationManager = CLLocationManager()
var jsonParser = JSONParser.sharedInstance()
var annotationAdded = false
var dataType :DataType?
//reuse images to save memory
var toiletIcon : UIImage? = {
if let image = UIImage(named: "toilet")
{
return image.imageWithRenderingMode(.AlwaysTemplate)
}
else{ return nil }
}()
var youbikeIcon : UIImage? = {
if let image = UIImage(named: "bike")
{
return image.imageWithRenderingMode(.AlwaysTemplate)
}
else{ return nil }
}()
//MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupDetailPanel()
setupStyle()
setupMapAndLocationManager()
setupMapRegion()
setupActivityIndicator()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if !annotationAdded{
guard let dataType = dataType else{ return }
showInfoType(dataType: dataType)
}
}
//MARK: Style Setting
private func bringViewToFront(){
view.bringSubviewToFront(mapNavigateButton)
view.bringSubviewToFront(activityIndicatorView)
}
private func setupActivityIndicator(){
activityIndicatorView.hidden = true
activityIndicatorView.hidesWhenStopped = true
}
private func setupStyle(){
self.view.bringSubviewToFront(detailPanel)
markerImageView.image = markerImageView.image?.imageWithRenderingMode(.AlwaysTemplate)
markerImageView.tintColor = UIColor.esyOffWhiteColor()
}
private func setupDetailPanel(){
detailPanel.hidden = true
}
//MARK: Display Infomation
func showInfoType(dataType type: DataType){
activityIndicatorView?.startAnimating()
jsonParser.request?.cancel()
jsonParser.getDataWithCompletionHandler(type, completion: {[unowned self] in
self.dataType = type
guard let _ = self.mapView else { return }
self.addAnnotationOnMapview(dataType: type)
self.activityIndicatorView?.stopAnimating()
}
)
}
func reloadData(){
guard let dataType = self.dataType else { return }
showInfoType(dataType: dataType)
}
}
//MARK: MapView and LocationManager Method
extension MapViewController: MKMapViewDelegate, CLLocationManagerDelegate {
//MARK: locationManager
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
print("didChangeAuthorizationStatus")
setupMapRegion()
}
func setupMapAndLocationManager(){
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
mapView.delegate = self
mapView.showsUserLocation = true
mapNavigateButton.addTarget(self, action: #selector(setupMapRegion), forControlEvents: .TouchUpInside)
}
//MARK: Method
func addAnnotationOnMapview(dataType type: DataType){
mapView.removeAnnotations(mapView.annotations)
switch type {
case .Toilet:
if jsonParser.toilets.isEmpty { return }
for toilet in jsonParser.toilets{
let annotation = CustomMKPointAnnotation()
annotation.type = type
annotation.toilet = toilet
annotation.updateInfo()
mapView.addAnnotation(annotation)
}
case .Youbike:
if jsonParser.youbikes.isEmpty { return }
for youbike in jsonParser.youbikes{
let annotation = CustomMKPointAnnotation()
annotation.type = type
annotation.youbike = youbike
annotation.updateInfo()
mapView.addAnnotation(annotation)
}
}
self.annotationAdded = true
}
func setupMapRegion(){
let span = MKCoordinateSpanMake(0.006, 0.006)
if let location = locationManager.location {
let region = MKCoordinateRegion(center: location.coordinate , span: span)
mapView.setRegion(region, animated: true)
}
else{
let location = mapView.userLocation
let region = MKCoordinateRegion(center: location.coordinate , span: span)
mapView.setRegion(region, animated: true)
}
}
//MARK: MapView
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
guard let annotation = annotation as? CustomMKPointAnnotation else { return nil}
var annotationView: CustomAnnotationView?
let annotationViewDiameter:CGFloat = 35;
switch annotation.type! {
case .Toilet:
let reuseIdentifier = " toiletAnnotationView" //handle reuse identifier to better manage the memory
if let view = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseIdentifier){ annotationView = view as? CustomAnnotationView }
else {
annotationView = CustomAnnotationView(frame:CGRectMake(0, 0, annotationViewDiameter, annotationViewDiameter),annotation: annotation, reuseIdentifier: reuseIdentifier)
if let icon = toiletIcon{
annotationView?.setCustomImage(icon)
}
}
case .Youbike:
let reuseIdentifier = " youbikeAnnotationView"
if let view = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseIdentifier){ annotationView = view as? CustomAnnotationView }
else {
annotationView = CustomAnnotationView(frame:CGRectMake(0, 0, annotationViewDiameter, annotationViewDiameter),annotation: annotation, reuseIdentifier: reuseIdentifier)
if let icon = youbikeIcon{
annotationView?.setCustomImage(icon)
}
}
}
annotationView?.canShowCallout = true
return annotationView
}
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
if let annotation = view.annotation as? CustomMKPointAnnotation {
view.backgroundColor = UIColor.esyRobinsEggBlueColor()
detailPanel.hidden = false
let annotationLocation = CLLocation( latitude:annotation.coordinate.latitude, longitude: annotation.coordinate.longitude)
if let userLocation = locationManager.location{
let distance = annotationLocation.distanceFromLocation(userLocation)
let distanceInTime = distance / (3 / 3.6 * 60) //distance in time is not accurate now
let roundDistanceInTime = ceil(distanceInTime)
detailPanelSideLabel.text = String(format: "%0.0f min(s)", roundDistanceInTime)
}
detailPanelTitleLabel.text = annotation.title
detailPanelSubtitleLabel.text = annotation.address
}
}
func mapView(mapView: MKMapView, didDeselectAnnotationView view: MKAnnotationView) {
if view.annotation is MKUserLocation{
return
}
detailPanel.hidden = true
view.backgroundColor = UIColor.whiteColor()
}
}
| mit | 47cf63edd065d2e1451272a42dbba67f | 34.642241 | 182 | 0.641432 | 5.823239 | false | false | false | false |
logansease/SeaseAssist | Pod/Classes/String+EmojiCheck.swift | 1 | 2784 | //
// String+emojiCheck.swift
// SeaseAssist
//
// Created by lsease on 2/28/17.
// Copyright © 2017 Logan Sease. All rights reserved.
//
import UIKit
public extension UnicodeScalar {
var isEmoji: Bool {
switch value {
case 0x3030, 0x00AE, 0x00A9, // Special Characters
0x1D000 ... 0x1F77F, // Emoticons
0x2100 ... 0x27BF, // Misc symbols and Dingbats
0xFE00 ... 0xFE0F, // Variation Selectors
0x1F900 ... 0x1F9FF: // Supplemental Symbols and Pictographs
return true
default: return false
}
}
var isZeroWidthJoiner: Bool {
return value == 8205
}
}
public extension String {
var glyphCount: Int {
let richText = NSAttributedString(string: self)
let line = CTLineCreateWithAttributedString(richText)
return CTLineGetGlyphCount(line)
}
var isSingleEmoji: Bool {
return glyphCount == 1 && containsEmoji
}
var containsEmoji: Bool {
return !unicodeScalars.filter { $0.isEmoji }.isEmpty
}
var containsOnlyEmoji: Bool {
return unicodeScalars.first(where: { !$0.isEmoji && !$0.isZeroWidthJoiner }) == nil
}
// The next tricks are mostly to demonstrate how tricky it can be to determine emoji's
// If anyone has suggestions how to improve this, please let me know
var emojiString: String {
return emojiScalars.map { String($0) }.reduce("", +)
}
var emojis: [String] {
var scalars: [[UnicodeScalar]] = []
var currentScalarSet: [UnicodeScalar] = []
var previousScalar: UnicodeScalar?
for scalar in emojiScalars {
if let prev = previousScalar, !prev.isZeroWidthJoiner && !scalar.isZeroWidthJoiner {
scalars.append(currentScalarSet)
currentScalarSet = []
}
currentScalarSet.append(scalar)
previousScalar = scalar
}
scalars.append(currentScalarSet)
return scalars.map { $0.map{ String($0) } .reduce("", +) }
}
fileprivate var emojiScalars: [UnicodeScalar] {
var chars: [UnicodeScalar] = []
var previous: UnicodeScalar?
for cur in unicodeScalars {
if let previous = previous, previous.isZeroWidthJoiner && cur.isEmoji {
chars.append(previous)
chars.append(cur)
} else if cur.isEmoji {
chars.append(cur)
}
previous = cur
}
return chars
}
}
| mit | 837bbea5716190e0059ef3a6a5f68c07 | 25.254717 | 96 | 0.542939 | 5.09707 | false | false | false | false |
idomizrachi/Regen | regen/Utilities/Logger.swift | 1 | 1484 | //
// Logger.swift
// regen
//
// Created by Ido Mizrachi on 5/12/17.
//
import Foundation
public class Logger {
public enum Level: Int {
case verbose = 0
case debug = 1
case info = 2
case warning = 3
case error = 4
case off = 5
}
private static let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSS"
return formatter
}()
public static var logLevel: Level = .error
public static var color: Bool = true
public static func verbose(_ text: String) {
log(text, level: .verbose)
}
public static func debug(_ text: String) {
log(color ? text.green : text, level: .debug)
}
public static func info(_ text: String) {
log(text, level: .info)
}
public static func warning(_ text: String) {
log(color ? text.yellow.bold : text, level: .warning)
}
public static func error(_ text: String) {
log(color ? text.red.bold : text, level: .error)
}
private static func log(_ text: String, level: Level) {
if shouldLog(level: level) == false {
return
}
let date = formatter.string(from: Date())
print("\(date) \(text)")
}
private static func shouldLog(level: Level) -> Bool {
return level.rawValue >= Logger.logLevel.rawValue
}
}
| mit | d22a9f3e4698a8b2df24f491fe80106b | 21.830769 | 61 | 0.553235 | 4.156863 | false | false | false | false |
jbrudvik/swift-playgrounds | constants.playground/section-1.swift | 1 | 1108 | // `var` defines variables, `let` defines constants
// `let` constants must be initialized when defined
// let causesAnError: Int // causes an error
// Constants may not be assigned more than once
let cannotBeAssignedTwice = 3
// cannotBeAssignedTwice = 3 // causes an error
// `let` affects deeper than the variable reference itself
// `let` arrays may not have their contents changed, nor their lengths changed. This is a change from early versions of Swift, where contents could be changed
let a = [Int](0..<10)
// a[3] = 12 // cannot change existing indexes
a
// a.append(3) // fails because append changes length
// a.removeAll() // fails because removeAll changes length
// `let` dictionaries may not have their contents changed. They are truly immutable.
let d = [
"onlyKey": "onlyValue"
]
d["onlyKey"] // Evaluates to wrapped optional type containing "onlyValue"
d["missingKey"] // Evaluates to nil
// bar["onlyKey"] = "differentValue" // fails because dictionary contents may not be changed
// bar["missingKey"] = "valueNeverAdded" // fails because new dictionary contents may not be added
| mit | aa3f349d652c4ec3946f57fd873ecdd4 | 41.615385 | 158 | 0.734657 | 4.134328 | false | false | false | false |
bustoutsolutions/siesta | Source/Siesta/Request/NetworkRequest.swift | 1 | 5481 | //
// NetworkRequest.swift
// Siesta
//
// Created by Paul on 2015/12/15.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
internal final class NetworkRequestDelegate: RequestDelegate
{
// Basic metadata
private let resource: Resource
internal var config: Configuration
{ resource.configuration(for: underlyingRequest) }
internal let requestDescription: String
// Networking
private let requestBuilder: () -> URLRequest // so repeated() can re-read config
private let underlyingRequest: URLRequest
internal var networking: RequestNetworking? // present only after start()
// Progress
private var progressComputation: RequestProgressComputation
// MARK: Managing request
init(resource: Resource, requestBuilder: @escaping () -> URLRequest)
{
self.resource = resource
self.requestBuilder = requestBuilder
underlyingRequest = requestBuilder()
requestDescription =
SiestaLog.Category.enabled.contains(.network) || SiestaLog.Category.enabled.contains(.networkDetails)
? debugStr([underlyingRequest.httpMethod, underlyingRequest.url])
: "NetworkRequest"
progressComputation = RequestProgressComputation(isGet: underlyingRequest.httpMethod == "GET")
}
func startUnderlyingOperation(passingResponseTo completionHandler: RequestCompletionHandler)
{
let networking = resource.service.networkingProvider.startRequest(underlyingRequest)
{
res, data, err in
DispatchQueue.main.async
{
self.responseReceived(
underlyingResponse: res,
body: data,
error: err,
completionHandler: completionHandler)
}
}
self.networking = networking
}
func cancelUnderlyingOperation()
{
networking?.cancel()
}
func repeated() -> RequestDelegate
{
NetworkRequestDelegate(resource: resource, requestBuilder: requestBuilder)
}
// MARK: Progress
func computeProgress() -> Double
{
if let networking = networking
{ progressComputation.update(from: networking.transferMetrics) }
return progressComputation.fractionDone
}
var progressReportingInterval: TimeInterval
{ config.progressReportingInterval }
// MARK: Response handling
// Entry point for response handling. Triggered by RequestNetworking completion callback.
private func responseReceived(
underlyingResponse: HTTPURLResponse?,
body: Data?,
error: Error?,
completionHandler: RequestCompletionHandler)
{
DispatchQueue.mainThreadPrecondition()
SiestaLog.log(.network, ["Response: ", underlyingResponse?.statusCode ?? error, "←", requestDescription])
SiestaLog.log(.networkDetails, ["Raw response headers:", underlyingResponse?.allHeaderFields])
SiestaLog.log(.networkDetails, ["Raw response body:", body?.count ?? 0, "bytes"])
let responseInfo = interpretResponse(underlyingResponse, body, error)
if completionHandler.willIgnore(responseInfo)
{ return }
progressComputation.complete()
transformResponse(responseInfo, then: completionHandler.broadcastResponse)
}
private func isError(httpStatusCode: Int?) -> Bool
{
guard let httpStatusCode = httpStatusCode else
{ return false }
return httpStatusCode >= 400
}
private func interpretResponse(
_ underlyingResponse: HTTPURLResponse?,
_ body: Data?,
_ error: Error?)
-> ResponseInfo
{
if isError(httpStatusCode: underlyingResponse?.statusCode) || error != nil
{
return ResponseInfo(
response: .failure(RequestError(response: underlyingResponse, content: body, cause: error)))
}
else if underlyingResponse?.statusCode == 304
{
if let entity = resource.latestData
{
return ResponseInfo(response: .success(entity), isNew: false)
}
else
{
return ResponseInfo(
response: .failure(RequestError(
userMessage: NSLocalizedString("No data available", comment: "userMessage"),
cause: RequestError.Cause.NoLocalDataFor304())))
}
}
else
{
return ResponseInfo(response: .success(Entity<Any>(response: underlyingResponse, content: body ?? Data())))
}
}
private func transformResponse(
_ rawInfo: ResponseInfo,
then afterTransformation: @escaping (ResponseInfo) -> Void)
{
let processor = config.pipeline.makeProcessor(rawInfo.response, resource: resource)
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async
{
let processedInfo =
rawInfo.isNew
? ResponseInfo(response: processor(), isNew: true)
: rawInfo
DispatchQueue.main.async
{ afterTransformation(processedInfo) }
}
}
}
| mit | 1c3c6e36f6865e12d03839830ce08abf | 32.814815 | 119 | 0.608251 | 6.026403 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/Alamofire/Tests/UploadTests.swift | 37 | 30653 | // UploadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import Foundation
import XCTest
class UploadFileInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndFile() {
// Given
let URLString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
// When
let request = Alamofire.upload(.POST, URLString, file: imageURL)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndFile() {
// Given
let URLString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
// When
let request = Alamofire.upload(.POST, URLString, headers: ["Authorization": "123456"], file: imageURL)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadDataInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndData() {
// Given
let URLString = "https://httpbin.org/"
// When
let request = Alamofire.upload(.POST, URLString, data: NSData())
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndData() {
// Given
let URLString = "https://httpbin.org/"
// When
let request = Alamofire.upload(.POST, URLString, headers: ["Authorization": "123456"], data: NSData())
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadStreamInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndStream() {
// Given
let URLString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
let imageStream = NSInputStream(URL: imageURL)!
// When
let request = Alamofire.upload(.POST, URLString, stream: imageStream)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndStream() {
// Given
let URLString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
let imageStream = NSInputStream(URL: imageURL)!
// When
let request = Alamofire.upload(.POST, URLString, headers: ["Authorization": "123456"], stream: imageStream)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadDataTestCase: BaseTestCase {
func testUploadDataRequest() {
// Given
let URLString = "https://httpbin.org/post"
let data = "Lorem ipsum dolor sit amet".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let expectation = expectationWithDescription("Upload request should succeed: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.upload(.POST, URLString, data: data)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
}
func testUploadDataRequestWithProgress() {
// Given
let URLString = "https://httpbin.org/post"
let data: NSData = {
var text = ""
for _ in 1...3_000 {
text += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
}
return text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}()
let expectation = expectationWithDescription("Bytes upload progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: NSData?
var responseError: ErrorType?
// When
let upload = Alamofire.upload(.POST, URLString, data: data)
upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
let bytes = (bytes: bytesWritten, totalBytes: totalBytesWritten, totalBytesExpected: totalBytesExpectedToWrite)
byteValues.append(bytes)
let progress = (
completedUnitCount: upload.progress.completedUnitCount,
totalUnitCount: upload.progress.totalUnitCount
)
progressValues.append(progress)
}
upload.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNotNil(responseData, "response data should not be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(
byteValue.totalBytes,
progressValue.completedUnitCount,
"total bytes should be equal to completed unit count"
)
XCTAssertEqual(
byteValue.totalBytesExpected,
progressValue.totalUnitCount,
"total bytes expected should be equal to total unit count"
)
}
}
if let
lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(
progressValueFractionalCompletion,
1.0,
"progress value fractional completion should equal 1.0"
)
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
}
}
// MARK: -
class UploadMultipartFormDataTestCase: BaseTestCase {
// MARK: Tests
func testThatUploadingMultipartFormDataSetsContentTypeHeader() {
// Given
let URLString = "https://httpbin.org/post"
let uploadData = "upload_data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let expectation = expectationWithDescription("multipart form data upload should succeed")
var formData: MultipartFormData?
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
// When
Alamofire.upload(
.POST,
URLString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
formData = multipartFormData
},
encodingCompletion: { result in
switch result {
case .Success(let upload, _, _):
upload.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
case .Failure:
expectation.fulfill()
}
}
)
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
if let
request = request,
multipartFormData = formData,
contentType = request.valueForHTTPHeaderField("Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() {
// Given
let URLString = "https://httpbin.org/post"
let french = "français".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let japanese = "日本語".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let expectation = expectationWithDescription("multipart form data upload should succeed")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
// When
Alamofire.upload(
.POST,
URLString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: french, name: "french")
multipartFormData.appendBodyPart(data: japanese, name: "japanese")
},
encodingCompletion: { result in
switch result {
case .Success(let upload, _, _):
upload.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
case .Failure:
expectation.fulfill()
}
}
)
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
}
func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() {
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false)
}
func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() {
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true)
}
func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() {
// Given
let URLString = "https://httpbin.org/post"
let french = "français".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let japanese = "日本語".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let expectation = expectationWithDescription("multipart form data upload should succeed")
var streamingFromDisk: Bool?
var streamFileURL: NSURL?
// When
Alamofire.upload(
.POST,
URLString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: french, name: "french")
multipartFormData.appendBodyPart(data: japanese, name: "japanese")
},
encodingCompletion: { result in
switch result {
case let .Success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
streamingFromDisk = uploadStreamingFromDisk
streamFileURL = uploadStreamFileURL
upload.response { _, _, _, _ in
expectation.fulfill()
}
case .Failure:
expectation.fulfill()
}
}
)
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
XCTAssertNil(streamFileURL, "stream file URL should be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
}
}
func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() {
// Given
let URLString = "https://httpbin.org/post"
let uploadData = "upload data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let expectation = expectationWithDescription("multipart form data upload should succeed")
var formData: MultipartFormData?
var request: NSURLRequest?
var streamingFromDisk: Bool?
// When
Alamofire.upload(
.POST,
URLString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
formData = multipartFormData
},
encodingCompletion: { result in
switch result {
case let .Success(upload, uploadStreamingFromDisk, _):
streamingFromDisk = uploadStreamingFromDisk
upload.response { responseRequest, _, _, _ in
request = responseRequest
expectation.fulfill()
}
case .Failure:
expectation.fulfill()
}
}
)
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
}
if let
request = request,
multipartFormData = formData,
contentType = request.valueForHTTPHeaderField("Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() {
// Given
let URLString = "https://httpbin.org/post"
let french = "français".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let japanese = "日本語".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let expectation = expectationWithDescription("multipart form data upload should succeed")
var streamingFromDisk: Bool?
var streamFileURL: NSURL?
// When
Alamofire.upload(
.POST,
URLString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: french, name: "french")
multipartFormData.appendBodyPart(data: japanese, name: "japanese")
},
encodingMemoryThreshold: 0,
encodingCompletion: { result in
switch result {
case let .Success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
streamingFromDisk = uploadStreamingFromDisk
streamFileURL = uploadStreamFileURL
upload.response { _, _, _, _ in
expectation.fulfill()
}
case .Failure:
expectation.fulfill()
}
}
)
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
XCTAssertNotNil(streamFileURL, "stream file URL should not be nil")
if let
streamingFromDisk = streamingFromDisk,
streamFilePath = streamFileURL?.path
{
XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
XCTAssertTrue(
NSFileManager.defaultManager().fileExistsAtPath(streamFilePath),
"stream file path should exist"
)
}
}
func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() {
// Given
let URLString = "https://httpbin.org/post"
let uploadData = "upload data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let expectation = expectationWithDescription("multipart form data upload should succeed")
var formData: MultipartFormData?
var request: NSURLRequest?
var streamingFromDisk: Bool?
// When
Alamofire.upload(
.POST,
URLString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
formData = multipartFormData
},
encodingMemoryThreshold: 0,
encodingCompletion: { result in
switch result {
case let .Success(upload, uploadStreamingFromDisk, _):
streamingFromDisk = uploadStreamingFromDisk
upload.response { responseRequest, _, _, _ in
request = responseRequest
expectation.fulfill()
}
case .Failure:
expectation.fulfill()
}
}
)
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
}
if let
request = request,
multipartFormData = formData,
contentType = request.valueForHTTPHeaderField("Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() {
// Given
let manager: Manager = {
let identifier = "com.alamofire.uploadtests.\(NSUUID().UUIDString)"
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationForAllPlatformsWithIdentifier(identifier)
return Manager(configuration: configuration, serverTrustPolicyManager: nil)
}()
let URLString = "https://httpbin.org/post"
let french = "français".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let japanese = "日本語".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let expectation = expectationWithDescription("multipart form data upload should succeed")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
var streamingFromDisk: Bool?
// When
manager.upload(
.POST,
URLString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: french, name: "french")
multipartFormData.appendBodyPart(data: japanese, name: "japanese")
},
encodingCompletion: { result in
switch result {
case let .Success(upload, uploadStreamingFromDisk, _):
streamingFromDisk = uploadStreamingFromDisk
upload.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
case .Failure:
expectation.fulfill()
}
}
)
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
} else {
XCTFail("streaming from disk should not be nil")
}
}
// MARK: Combined Test Execution
private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk streamFromDisk: Bool) {
// Given
let URLString = "https://httpbin.org/post"
let loremData1: NSData = {
var loremValues: [String] = []
for _ in 1...1_500 {
loremValues.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
}
return loremValues.joinWithSeparator(" ").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}()
let loremData2: NSData = {
var loremValues: [String] = []
for _ in 1...1_500 {
loremValues.append("Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.")
}
return loremValues.joinWithSeparator(" ").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}()
let expectation = expectationWithDescription("multipart form data upload should succeed")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
// When
Alamofire.upload(
.POST,
URLString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: loremData1, name: "lorem1")
multipartFormData.appendBodyPart(data: loremData2, name: "lorem2")
},
encodingMemoryThreshold: streamFromDisk ? 0 : 100_000_000,
encodingCompletion: { result in
switch result {
case .Success(let upload, _, _):
upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
let bytes = (
bytes: bytesWritten,
totalBytes: totalBytesWritten,
totalBytesExpected: totalBytesExpectedToWrite
)
byteValues.append(bytes)
let progress = (
completedUnitCount: upload.progress.completedUnitCount,
totalUnitCount: upload.progress.totalUnitCount
)
progressValues.append(progress)
}
upload.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
case .Failure:
expectation.fulfill()
}
}
)
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(
byteValue.totalBytes,
progressValue.completedUnitCount,
"total bytes should be equal to completed unit count"
)
XCTAssertEqual(
byteValue.totalBytesExpected,
progressValue.totalUnitCount,
"total bytes expected should be equal to total unit count"
)
}
}
if let
lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(
progressValueFractionalCompletion,
1.0,
"progress value fractional completion should equal 1.0"
)
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
}
}
| mit | 3582b1f2f93b98956e2fe9746bed09b1 | 38.977807 | 129 | 0.61653 | 6.175237 | false | false | false | false |
zero2launch/z2l-ios-social-network | InstagramClone/Api.swift | 1 | 482 | //
// Api.swift
// InstagramClone
//
// Created by The Zero2Launch Team on 1/8/17.
// Copyright © 2017 The Zero2Launch Team. All rights reserved.
//
import Foundation
struct Api {
static var User = UserApi()
static var Post = PostApi()
static var Comment = CommentApi()
static var Post_Comment = Post_CommentApi()
static var MyPosts = MyPostsApi()
static var Follow = FollowApi()
static var Feed = FeedApi()
static var HashTag = HashTagApi()
}
| mit | 07b2a703732683bb84ce1d8d27e4fe38 | 24.315789 | 63 | 0.673597 | 3.7 | false | false | false | false |
SuPair/firefox-ios | Client/Application/QuickActions.swift | 4 | 6582 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Storage
import Shared
import XCGLogger
enum ShortcutType: String {
case newTab = "NewTab"
case newPrivateTab = "NewPrivateTab"
case openLastBookmark = "OpenLastBookmark"
case qrCode = "QRCode"
init?(fullType: String) {
guard let last = fullType.components(separatedBy: ".").last else { return nil }
self.init(rawValue: last)
}
var type: String {
return Bundle.main.bundleIdentifier! + ".\(self.rawValue)"
}
}
protocol QuickActionHandlerDelegate {
func handleShortCutItemType(_ type: ShortcutType, userData: [String: NSSecureCoding]?)
}
class QuickActions: NSObject {
fileprivate let log = Logger.browserLogger
static let QuickActionsVersion = "1.0"
static let QuickActionsVersionKey = "dynamicQuickActionsVersion"
static let TabURLKey = "url"
static let TabTitleKey = "title"
fileprivate let lastBookmarkTitle = NSLocalizedString("Open Last Bookmark", tableName: "3DTouchActions", comment: "String describing the action of opening the last added bookmark from the home screen Quick Actions via 3D Touch")
fileprivate let _lastTabTitle = NSLocalizedString("Open Last Tab", tableName: "3DTouchActions", comment: "String describing the action of opening the last tab sent to Firefox from the home screen Quick Actions via 3D Touch")
static var sharedInstance = QuickActions()
var launchedShortcutItem: UIApplicationShortcutItem?
// MARK: Administering Quick Actions
func addDynamicApplicationShortcutItemOfType(_ type: ShortcutType, fromShareItem shareItem: ShareItem, toApplication application: UIApplication) {
var userData = [QuickActions.TabURLKey: shareItem.url]
if let title = shareItem.title {
userData[QuickActions.TabTitleKey] = title
}
QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(type, withUserData: userData, toApplication: application)
}
@discardableResult func addDynamicApplicationShortcutItemOfType(_ type: ShortcutType, withUserData userData: [AnyHashable: Any] = [AnyHashable: Any](), toApplication application: UIApplication) -> Bool {
// add the quick actions version so that it is always in the user info
var userData: [AnyHashable: Any] = userData
userData[QuickActions.QuickActionsVersionKey] = QuickActions.QuickActionsVersion
var dynamicShortcutItems = application.shortcutItems ?? [UIApplicationShortcutItem]()
switch type {
case .openLastBookmark:
let openLastBookmarkShortcut = UIMutableApplicationShortcutItem(type: ShortcutType.openLastBookmark.type,
localizedTitle: lastBookmarkTitle,
localizedSubtitle: userData[QuickActions.TabTitleKey] as? String,
icon: UIApplicationShortcutIcon(templateImageName: "quick_action_last_bookmark"),
userInfo: userData
)
if let index = (dynamicShortcutItems.index { $0.type == ShortcutType.openLastBookmark.type }) {
dynamicShortcutItems[index] = openLastBookmarkShortcut
} else {
dynamicShortcutItems.append(openLastBookmarkShortcut)
}
default:
log.warning("Cannot add static shortcut item of type \(type)")
return false
}
application.shortcutItems = dynamicShortcutItems
return true
}
func removeDynamicApplicationShortcutItemOfType(_ type: ShortcutType, fromApplication application: UIApplication) {
guard var dynamicShortcutItems = application.shortcutItems,
let index = (dynamicShortcutItems.index { $0.type == type.type }) else { return }
dynamicShortcutItems.remove(at: index)
application.shortcutItems = dynamicShortcutItems
}
// MARK: Handling Quick Actions
@discardableResult func handleShortCutItem(_ shortcutItem: UIApplicationShortcutItem, withBrowserViewController bvc: BrowserViewController ) -> Bool {
// Verify that the provided `shortcutItem`'s `type` is one handled by the application.
guard let shortCutType = ShortcutType(fullType: shortcutItem.type) else { return false }
DispatchQueue.main.async {
self.handleShortCutItemOfType(shortCutType, userData: shortcutItem.userInfo, browserViewController: bvc)
}
return true
}
fileprivate func handleShortCutItemOfType(_ type: ShortcutType, userData: [String: NSSecureCoding]?, browserViewController: BrowserViewController) {
switch type {
case .newTab:
handleOpenNewTab(withBrowserViewController: browserViewController, isPrivate: false)
case .newPrivateTab:
handleOpenNewTab(withBrowserViewController: browserViewController, isPrivate: true)
// even though we're removing OpenLastTab, it's possible that someone will use an existing last tab quick action to open the app
// the first time after upgrading, so we should still handle it
case .openLastBookmark:
if let urlToOpen = (userData?[QuickActions.TabURLKey] as? String)?.asURL {
handleOpenURL(withBrowserViewController: browserViewController, urlToOpen: urlToOpen)
}
case .qrCode:
handleQRCode(with: browserViewController)
}
}
fileprivate func handleOpenNewTab(withBrowserViewController bvc: BrowserViewController, isPrivate: Bool) {
bvc.openBlankNewTab(focusLocationField: true, isPrivate: isPrivate)
}
fileprivate func handleOpenURL(withBrowserViewController bvc: BrowserViewController, urlToOpen: URL) {
// open bookmark in a non-private browsing tab
bvc.switchToPrivacyMode(isPrivate: false)
// find out if bookmarked URL is currently open
// if so, open to that tab,
// otherwise, create a new tab with the bookmarked URL
bvc.switchToTabForURLOrOpen(urlToOpen, isPrivileged: true)
}
fileprivate func handleQRCode(with vc: QRCodeViewControllerDelegate & UIViewController) {
let qrCodeViewController = QRCodeViewController()
qrCodeViewController.qrCodeDelegate = vc
let controller = UINavigationController(rootViewController: qrCodeViewController)
vc.present(controller, animated: true, completion: nil)
}
}
| mpl-2.0 | a8cfb37c54f1bb180ca6d27113e5c198 | 45.352113 | 232 | 0.710878 | 5.72846 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/SwipeForwardNavigationController.swift | 1 | 12660 | //
// SwipeForwardNavigationController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 7/18/20.
// Copyright © 2020 Haptic Apps. All rights reserved.
//
// Swift code based on Christopher Wendel https://github.com/CEWendel/SWNavigationController/blob/master/SWNavigationController/PodFiles/SWNavigationController.m
//
import UIKit
typealias SWNavigationControllerPushCompletion = () -> Void
class SwipeForwardNavigationController: UINavigationController {
private var percentDrivenInteractiveTransition: UIPercentDrivenInteractiveTransition?
public var interactivePushGestureRecognizer: UIScreenEdgePanGestureRecognizer?
public var pushableViewControllers: [UIViewController] = []
/* View controllers we can push onto the navigation stack by pulling in from the right screen edge. */ // Extra state used to implement completion blocks on pushViewController:
public var pushCompletion: SWNavigationControllerPushCompletion?
private var pushedViewController: UIViewController?
public var fullWidthBackGestureRecognizer = UIPanGestureRecognizer()
var pushAnimatedTransitioningClass: SwipeForwardAnimatedTransitioning?
override var prefersHomeIndicatorAutoHidden: Bool {
return true
}
override var childForHomeIndicatorAutoHidden: UIViewController? {
return nil
}
override init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?) {
super.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
setup()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setup()
}
func setup() {
pushableViewControllers = [UIViewController]()
delegate = self
pushAnimatedTransitioningClass = SwipeForwardAnimatedTransitioning()
}
override func viewDidLoad() {
super.viewDidLoad()
interactivePushGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleRightSwipe(_:)))
interactivePushGestureRecognizer?.edges = UIRectEdge.right
interactivePushGestureRecognizer?.delegate = self
view.addGestureRecognizer(interactivePushGestureRecognizer!)
// To ensure swipe-back is still recognized
interactivePopGestureRecognizer?.delegate = self
if let interactivePopGestureRecognizer = interactivePopGestureRecognizer, let targets = interactivePopGestureRecognizer.value(forKey: "targets") {
fullWidthBackGestureRecognizer.setValue(targets, forKey: "targets")
fullWidthBackGestureRecognizer.delegate = self
fullWidthBackGestureRecognizer.require(toFail: interactivePushGestureRecognizer!)
view.addGestureRecognizer(fullWidthBackGestureRecognizer)
if #available(iOS 13.4, *) {
fullWidthBackGestureRecognizer.allowedScrollTypesMask = .continuous
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.splitViewController?.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
if let first = pushableViewControllers.first as? SplitMainViewController {
pushableViewControllers.removeAll()
pushableViewControllers.append(first)
} else {
pushableViewControllers.removeAll()
}
}
@objc func handleRightSwipe(_ swipeGestureRecognizer: UIScreenEdgePanGestureRecognizer?) {
let view = self.view!
let progress = abs(-(swipeGestureRecognizer?.translation(in: view).x ?? 0.0) / view.frame.size.width) // 1.0 When the pushable vc has been pulled into place
// Start, update, or finish the interactive push transition
switch swipeGestureRecognizer?.state {
case .began:
pushNextViewControllerFromRight(nil)
case .changed:
percentDrivenInteractiveTransition?.update(progress)
case .ended:
// Figure out if we should finish the transition or not
handleEdgeSwipeEnded(withProgress: progress, velocity: swipeGestureRecognizer?.velocity(in: view).x ?? 0)
case .failed:
percentDrivenInteractiveTransition?.cancel()
case .cancelled, .possible:
fallthrough
default:
break
}
}
@objc func handleRightSwipeFull(_ swipeGestureRecognizer: UIPanGestureRecognizer?) {
let view = self.view!
let progress = abs(-(swipeGestureRecognizer?.translation(in: view).x ?? 0.0) / view.frame.size.width) // 1.0 When the pushable vc has been pulled into place
// Start, update, or finish the interactive push transition
switch swipeGestureRecognizer?.state {
case .began:
pushNextViewControllerFromRight(nil)
case .changed:
percentDrivenInteractiveTransition?.update(progress)
case .ended:
// Figure out if we should finish the transition or not
handleEdgeSwipeEnded(withProgress: progress, velocity: swipeGestureRecognizer?.velocity(in: view).x ?? 0)
case .failed:
percentDrivenInteractiveTransition?.cancel()
case .cancelled, .possible:
fallthrough
default:
break
}
}
func handleEdgeSwipeEnded(withProgress progress: CGFloat, velocity: CGFloat) {
// kSWGestureVelocityThreshold threshold indicates how hard the finger has to flick left to finish the push transition
if velocity < 0 && (progress > 0.5 || velocity < -500) {
percentDrivenInteractiveTransition?.finish()
} else {
percentDrivenInteractiveTransition?.cancel()
}
}
}
extension SwipeForwardNavigationController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
var shouldBegin = false
if gestureRecognizer == interactivePushGestureRecognizer || gestureRecognizer == NavigationHomeViewController.edgeGesture {
shouldBegin = pushableViewControllers.count > 0 && !((pushableViewControllers.last) == topViewController)
} else {
shouldBegin = viewControllers.count > 1
}
return shouldBegin
}
}
extension SwipeForwardNavigationController {
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
pushableViewControllers.removeAll()
super.pushViewController(viewController, animated: animated)
}
override func popViewController(animated: Bool) -> UIViewController? {
// Dismiss the current view controllers keyboard (if it is displaying one), to avoid first responder problems when pushing back onto the stack
topViewController?.view.endEditing(true)
let poppedViewController = super.popViewController(animated: animated)
if let poppedViewController = poppedViewController {
pushableViewControllers.append(poppedViewController)
}
return poppedViewController
}
override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
let poppedViewControllers = super.popToViewController(viewController, animated: animated)
self.pushableViewControllers = poppedViewControllers?.backwards() ?? []
return poppedViewControllers ?? []
}
override func popToRootViewController(animated: Bool) -> [UIViewController]? {
let poppedViewControllers = super.popToRootViewController(animated: true)
if let all = poppedViewControllers?.backwards() {
pushableViewControllers = all
}
return poppedViewControllers
}
override func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) {
super.setViewControllers(viewControllers, animated: animated)
self.pushableViewControllers.removeAll()
}
func push(_ viewController: UIViewController?, animated: Bool, completion: @escaping SWNavigationControllerPushCompletion) {
pushedViewController = viewController
pushCompletion = completion
if let viewController = viewController {
super.pushViewController(viewController, animated: animated)
}
}
override func collapseSecondaryViewController(_ secondaryViewController: UIViewController, for splitViewController: UISplitViewController) {
if let secondaryAsNav = secondaryViewController as? UINavigationController, (UIDevice.current.userInterfaceIdiom == .phone) {
viewControllers += secondaryAsNav.viewControllers
}
}
func pushNextViewControllerFromRight(_ callback: (() -> Void)?) {
let pushedViewController = pushableViewControllers.last
if pushedViewController != nil && visibleViewController != nil && visibleViewController?.isBeingPresented == false && visibleViewController?.isBeingDismissed == false {
push(pushedViewController, animated: UIApplication.shared.isSplitOrSlideOver ? false : true) {
if !self.pushableViewControllers.isEmpty {
self.pushableViewControllers.removeLast()
callback?()
}
}
}
}
}
extension SwipeForwardNavigationController: UISplitViewControllerDelegate {
func splitViewController(_ splitViewController: UISplitViewController, separateSecondaryFrom primaryViewController: UIViewController) -> UIViewController? {
if UIDevice.current.userInterfaceIdiom == .phone {
var main: UIViewController?
for viewController in viewControllers {
if viewController is MainViewController {
main = viewController
}
}
for viewController in pushableViewControllers {
if viewController is MainViewController {
main = viewController
}
}
if let main = main {
return SwipeForwardNavigationController(rootViewController: main)
}
}
return nil
}
}
extension SwipeForwardNavigationController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == .push && (((navigationController as? SwipeForwardNavigationController)?.interactivePushGestureRecognizer)?.state == .began || NavigationHomeViewController.edgeGesture?.state == .began) {
return self.pushAnimatedTransitioningClass
}
return nil
}
func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
let navController = navigationController as? SwipeForwardNavigationController
if navController?.interactivePushGestureRecognizer?.state == .began || NavigationHomeViewController.edgeGesture?.state == .began {
navController?.percentDrivenInteractiveTransition = UIPercentDrivenInteractiveTransition()
navController?.percentDrivenInteractiveTransition?.completionCurve = .easeOut
} else {
navController?.percentDrivenInteractiveTransition = nil
}
return navController?.percentDrivenInteractiveTransition
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if pushedViewController != viewController {
pushedViewController = nil
pushCompletion = nil
}
}
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
if (pushCompletion != nil) && pushedViewController == viewController {
pushCompletion?()
}
pushCompletion = nil
pushedViewController = nil
}
}
| apache-2.0 | 8a99c7c93c28015e3b5ecf547c09f2c6 | 41.196667 | 247 | 0.69887 | 6.631221 | false | false | false | false |
ja-mes/experiments | iOS/Animations/Animations/AppDelegate.swift | 1 | 6096 | //
// AppDelegate.swift
// Animations
//
// Created by James Brown on 8/7/16.
// Copyright © 2016 James Brown. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.example.Animations" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Animations", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 42e10cd49423fa92959bb55ae07a05e2 | 53.90991 | 291 | 0.719606 | 5.923226 | false | false | false | false |
box/box-ios-sdk | Sources/Network/ArrayInputStream.swift | 1 | 4676 | // swiftlint:disable all
/// Notes:
/// The purpose of this class (ArrayInputStream) is to "merge" multiple InputStreams into a single InputStream.
/// This merging can be implemented by sequentially reading from an array of input streams with an interface that is the same as InputStream.
/// This is done here by creating a subclass of InputStream that takes in an array of streams and has a custom read method that reads sequentially from its array of InputStreams.
// Copyright 2019 Soroush Khanlou
//
// 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
class ArrayInputStream: InputStream {
private let inputStreams: [InputStream]
private var currentIndex: Int
private var _streamStatus: Stream.Status
private var _streamError: Error?
private var _delegate: StreamDelegate?
init(inputStreams: [InputStream]) {
self.inputStreams = inputStreams
currentIndex = 0
_streamStatus = .notOpen
_streamError = nil
super.init(data: Data()) // required because `init()` is not marked as a designated initializer
}
// Methods in the InputStream class that must be implemented
override func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength: Int) -> Int {
if _streamStatus == .closed {
return 0
}
var totalNumberOfBytesRead = 0
while totalNumberOfBytesRead < maxLength {
if currentIndex == inputStreams.count {
close()
break
}
let currentInputStream = inputStreams[currentIndex]
if currentInputStream.streamStatus != .open {
currentInputStream.open()
}
if !currentInputStream.hasBytesAvailable {
currentIndex += 1
continue
}
let remainingLength = maxLength - totalNumberOfBytesRead
let numberOfBytesRead = currentInputStream.read(&buffer[totalNumberOfBytesRead], maxLength: remainingLength)
if numberOfBytesRead == 0 {
currentIndex += 1
continue
}
if numberOfBytesRead == -1 {
_streamError = currentInputStream.streamError
_streamStatus = .error
return -1
}
totalNumberOfBytesRead += numberOfBytesRead
}
return totalNumberOfBytesRead
}
override func getBuffer(_: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>, length _: UnsafeMutablePointer<Int>) -> Bool {
return false
}
override var hasBytesAvailable: Bool {
return true
}
// Methods and variables in the Stream class that must be implemented
override func open() {
guard _streamStatus == .open else {
return
}
_streamStatus = .open
}
override func close() {
_streamStatus = .closed
for stream in inputStreams {
stream.close()
}
}
override func property(forKey _: Stream.PropertyKey) -> Any? {
return nil
}
override func setProperty(_: Any?, forKey _: Stream.PropertyKey) -> Bool {
return false
}
override var streamStatus: Stream.Status {
return _streamStatus
}
override var streamError: Error? {
return _streamError
}
override var delegate: StreamDelegate? {
get {
return _delegate
}
set {
_delegate = newValue
}
}
override func schedule(in _: RunLoop, forMode _: RunLoop.Mode) {}
override func remove(from _: RunLoop, forMode _: RunLoop.Mode) {}
}
| apache-2.0 | be6debc9120f656b54bb1bb3a003f73b | 33.637037 | 178 | 0.651839 | 5.430894 | false | false | false | false |
caopengxu/scw | scw/scw/AppDelegate.swift | 1 | 2787 | //
// AppDelegate.swift
// scw
//
// Created by cpx on 2017/6/19.
// Copyright © 2017年 scw. All rights reserved.
//
import UIKit
import QorumLogs
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// 打印log设置
QorumLogs.enabled = true
window = UIWindow()
if UserDefaults.standard.bool(forKey: "JudgeSign")
{
let storyboard = UIStoryboard.init(name: "MainTabBar", bundle: nil)
let main = storyboard.instantiateInitialViewController()
window?.rootViewController = main
}
else
{
let storyboard = UIStoryboard.init(name: "SignController", bundle: nil)
let main = storyboard.instantiateInitialViewController()
window?.rootViewController = main
}
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | e47fd280ebe579ddcce376c1585e978c | 39.823529 | 285 | 0.70317 | 5.688525 | false | false | false | false |
halo/biosphere | Biosphere/Controllers/Components/GitController.swift | 1 | 1054 | import Cocoa
class GitController: NSViewController {
public var satisfied: Bool {
if FileManager.default.fileExists(atPath: Paths.gitExecutable) {
Log.debug("\(Paths.gitExecutable) exists")
return true
} else {
Log.debug("\(Paths.gitExecutable) not found")
return false
}
}
@IBAction func installCommandLineTools(sender: NSButton) {
let task = Process()
task.executableURL = URL(fileURLWithPath: "/usr/bin/xcode-select")
task.arguments = ["--install"]
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.terminationHandler = { (process) in
Log.debug("xcode-select exitet with status: \(process.terminationStatus)")
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: String.Encoding.utf8) {
Log.debug(output)
}
}
do {
try task.run()
} catch {
Log.debug("Failed to execute xcode-select. Does the executable exist?")
}
}
}
| mit | d2da67947f06695f65451b2dde82207c | 26.025641 | 80 | 0.644213 | 4.319672 | false | false | false | false |
benlangmuir/swift | test/Concurrency/actor_isolation_swift6.swift | 5 | 2590 | // RUN: %target-typecheck-verify-swift -disable-availability-checking -warn-concurrency -swift-version 6
// REQUIRES: concurrency
// REQUIRES: asserts
final class ImmutablePoint: Sendable {
let x : Int = 0
let y : Int = 0
}
actor SomeActor { }
@globalActor
struct SomeGlobalActor {
static let shared = SomeActor()
}
/// ------------------------------------------------------------------
/// -- Value types do not need isolation on their stored properties --
protocol MainCounter {
@MainActor var counter: Int { get set }
@MainActor var ticker: Int { get set }
}
struct InferredFromConformance: MainCounter {
var counter = 0
var ticker: Int {
get { 1 }
set {}
}
}
@MainActor
struct InferredFromContext {
var point = ImmutablePoint()
var polygon: [ImmutablePoint] {
get { [] }
}
nonisolated let flag: Bool = false // expected-error {{'nonisolated' is redundant on struct's stored properties}}{{3-15=}}
subscript(_ i: Int) -> Int { return i }
static var stuff: [Int] = []
}
func checkIsolationValueType(_ formance: InferredFromConformance,
_ ext: InferredFromContext,
_ anno: NoGlobalActorValueType) async {
// these do not need an await, since it's a value type
_ = ext.point
_ = formance.counter
_ = anno.point
_ = anno.counter
// make sure it's just a warning if someone was awaiting on it previously
_ = await ext.point // expected-warning {{no 'async' operations occur within 'await' expression}}
_ = await formance.counter // expected-warning {{no 'async' operations occur within 'await' expression}}
_ = await anno.point // expected-warning {{no 'async' operations occur within 'await' expression}}
_ = await anno.counter // expected-warning {{no 'async' operations occur within 'await' expression}}
// these do need await, regardless of reference or value type
_ = await (formance as any MainCounter).counter
_ = await ext[1]
_ = await formance.ticker
_ = await ext.polygon
_ = await InferredFromContext.stuff
_ = await NoGlobalActorValueType.polygon
}
// check for instance members that do not need global-actor protection
struct NoGlobalActorValueType {
@SomeGlobalActor var point: ImmutablePoint // expected-error {{stored property 'point' within struct cannot have a global actor}}
@MainActor let counter: Int // expected-error {{stored property 'counter' within struct cannot have a global actor}}
@MainActor static var polygon: [ImmutablePoint] = []
}
/// -----------------------------------------------------------------
| apache-2.0 | ad119091498e7826b13377b0ac78f88b | 31.78481 | 131 | 0.654826 | 4.338358 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Site Creation/Final Assembly/LandInTheEditorHelper.swift | 1 | 2241 | typealias HomepageEditorCompletion = () -> Void
class LandInTheEditorHelper {
/// Land in the editor, or continue as usual - Used to branch on the feature flag for landing in the editor from the site creation flow
/// - Parameter blog: Blog (which was just created) for which to show the home page editor
/// - Parameter navigationController: UINavigationController used to present the home page editor
/// - Parameter completion: HomepageEditorCompletion callback to be invoked after the user finishes editing the home page, or immediately iwhen the feature flag is disabled
static func landInTheEditorOrContinue(for blog: Blog, navigationController: UINavigationController, completion: @escaping HomepageEditorCompletion) {
// branch here for feature flag
if FeatureFlag.landInTheEditor.enabled {
landInTheEditor(for: blog, navigationController: navigationController, completion: completion)
} else {
completion()
}
}
private static func landInTheEditor(for blog: Blog, navigationController: UINavigationController, completion: @escaping HomepageEditorCompletion) {
fetchAllPages(for: blog, success: { _ in
DispatchQueue.main.async {
if let homepage = blog.homepage {
let editorViewController = EditPageViewController(homepage: homepage, completion: completion)
navigationController.present(editorViewController, animated: false)
WPAnalytics.track(.landingEditorShown)
}
}
}, failure: { _ in
NSLog("Fetching all pages failed after site creation!")
})
}
// This seems to be necessary before casting `AbstractPost` to `Page`.
private static func fetchAllPages(for blog: Blog, success: @escaping PostServiceSyncSuccess, failure: @escaping PostServiceSyncFailure) {
let options = PostServiceSyncOptions()
options.number = 20
let context = ContextManager.sharedInstance().mainContext
let postService = PostService(managedObjectContext: context)
postService.syncPosts(ofType: .page, with: options, for: blog, success: success, failure: failure)
}
}
| gpl-2.0 | 7272418a1870454783117df21e151827 | 56.461538 | 176 | 0.698349 | 5.43932 | false | false | false | false |
frootloops/swift | test/IRGen/class_resilience.swift | 1 | 14835 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -enable-class-resilience %s | %FileCheck %s
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -enable-class-resilience -O %s
// CHECK: %swift.type = type { [[INT:i32|i64]] }
// CHECK: @_T016class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvpWvd = {{(protected )?}}global [[INT]] 0
// CHECK: @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd = {{(protected )?}}global [[INT]] 0
// CHECK: @_T016class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvpWvd = {{(protected )?}}global [[INT]] 0
// CHECK: @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd = {{(protected )?}}global [[INT]] 0
// CHECK: @_T016class_resilience14ResilientChildC5fields5Int32VvpWvd = {{(protected )?}}global [[INT]] {{8|16}}
// CHECK: @_T016class_resilience21ResilientGenericChildC5fields5Int32VvpWvi = {{(protected )?}}global [[INT]] {{56|88}}
// CHECK: @_T016class_resilience28ClassWithMyResilientPropertyC1rAA0eF6StructVvpWvd = {{(protected )?}}constant [[INT]] {{8|16}}
// CHECK: @_T016class_resilience28ClassWithMyResilientPropertyC5colors5Int32VvpWvd = {{(protected )?}}constant [[INT]] {{12|20}}
// CHECK: @_T016class_resilience30ClassWithIndirectResilientEnumC1s14resilient_enum10FunnyShapeOvpWvd = {{(protected )?}}constant [[INT]] {{8|16}}
// CHECK: @_T016class_resilience30ClassWithIndirectResilientEnumC5colors5Int32VvpWvd = {{(protected )?}}constant [[INT]] {{12|24}}
import resilient_class
import resilient_struct
import resilient_enum
// Concrete class with resilient stored property
public class ClassWithResilientProperty {
public let p: Point
public let s: Size
public let color: Int32
public init(p: Point, s: Size, color: Int32) {
self.p = p
self.s = s
self.color = color
}
}
// Concrete class with non-fixed size stored property
public class ClassWithResilientlySizedProperty {
public let r: Rectangle
public let color: Int32
public init(r: Rectangle, color: Int32) {
self.r = r
self.color = color
}
}
// Concrete class with resilient stored property that
// is fixed-layout inside this resilience domain
public struct MyResilientStruct {
public let x: Int32
}
public class ClassWithMyResilientProperty {
public let r: MyResilientStruct
public let color: Int32
public init(r: MyResilientStruct, color: Int32) {
self.r = r
self.color = color
}
}
// Enums with indirect payloads are fixed-size
public class ClassWithIndirectResilientEnum {
public let s: FunnyShape
public let color: Int32
public init(s: FunnyShape, color: Int32) {
self.s = s
self.color = color
}
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientChild : ResilientOutsideParent {
public let field: Int32 = 0
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientGenericChild<T> : ResilientGenericOutsideParent<T> {
public let field: Int32 = 0
}
// Superclass is resilient and has a resilient value type payload,
// but everything is in one module
public class MyResilientParent {
public let s: MyResilientStruct = MyResilientStruct(x: 0)
}
public class MyResilientChild : MyResilientParent {
public let field: Int32 = 0
}
// ClassWithResilientProperty.color getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32Vvg(%T16class_resilience26ClassWithResilientPropertyC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience26ClassWithResilientPropertyC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[FIELD_VALUE]]
// ClassWithResilientProperty metadata accessor
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_T016class_resilience26ClassWithResilientPropertyCMa()
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience26ClassWithResilientPropertyCML
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: call void @swift_once([[INT]]* @_T016class_resilience26ClassWithResilientPropertyCMa.once_token, i8* bitcast (void (i8*)* @initialize_metadata_ClassWithResilientProperty to i8*), i8* undef)
// CHECK-NEXT: [[METADATA:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience26ClassWithResilientPropertyCML
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: ret %swift.type* [[RESULT]]
// ClassWithResilientlySizedProperty.color getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32Vvg(%T16class_resilience33ClassWithResilientlySizedPropertyC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience33ClassWithResilientlySizedPropertyC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[FIELD_VALUE]]
// ClassWithResilientlySizedProperty metadata accessor
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_T016class_resilience33ClassWithResilientlySizedPropertyCMa()
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience33ClassWithResilientlySizedPropertyCML
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: call void @swift_once([[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyCMa.once_token, i8* bitcast (void (i8*)* @initialize_metadata_ClassWithResilientlySizedProperty to i8*), i8* undef)
// CHECK-NEXT: [[METADATA:%.*]] = load %swift.type*, %swift.type** @_T016class_resilience33ClassWithResilientlySizedPropertyCML
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: ret %swift.type* [[RESULT]]
// ClassWithIndirectResilientEnum.color getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience30ClassWithIndirectResilientEnumC5colors5Int32Vvg(%T16class_resilience30ClassWithIndirectResilientEnumC* swiftself)
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T16class_resilience30ClassWithIndirectResilientEnumC, %T16class_resilience30ClassWithIndirectResilientEnumC* %0, i32 0, i32 2
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[FIELD_VALUE]]
// ResilientChild.field getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience14ResilientChildC5fields5Int32Vvg(%T16class_resilience14ResilientChildC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience14ResilientChildC5fields5Int32VvpWvd
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience14ResilientChildC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[FIELD_VALUE]]
// ResilientGenericChild.field getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience21ResilientGenericChildC5fields5Int32Vvg(%T16class_resilience21ResilientGenericChildC* swiftself)
// FIXME: we could eliminate the unnecessary isa load by lazily emitting
// metadata sources in EmitPolymorphicParameters
// CHECK: load %swift.type*
// CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds %T16class_resilience21ResilientGenericChildC, %T16class_resilience21ResilientGenericChildC* %0, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ADDR]]
// CHECK-NEXT: [[INDIRECT_OFFSET:%.*]] = load [[INT]], [[INT]]* @_T016class_resilience21ResilientGenericChildC5fields5Int32VvpWvi
// CHECK-NEXT: [[ISA_ADDR:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[FIELD_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_ADDR]], [[INT]] [[INDIRECT_OFFSET]]
// CHECK-NEXT: [[FIELD_OFFSET_ADDR:%.*]] = bitcast i8* [[FIELD_OFFSET_TMP]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_ADDR:%.*]]
// CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T16class_resilience21ResilientGenericChildC* %0 to i8*
// CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Ts5Int32V*
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[RESULT]]
// MyResilientChild.field getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @_T016class_resilience16MyResilientChildC5fields5Int32Vvg(%T16class_resilience16MyResilientChildC* swiftself)
// CHECK: [[FIELD_ADDR:%.*]] = getelementptr inbounds %T16class_resilience16MyResilientChildC, %T16class_resilience16MyResilientChildC* %0, i32 0, i32 2
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[RESULT]]
// ClassWithResilientProperty metadata initialization function
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_ClassWithResilientProperty
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, [[INT]] {{60|96}}, [[INT]] 4)
// CHECK: [[SIZE_METADATA:%.*]] = call %swift.type* @_T016resilient_struct4SizeVMa()
// CHECK: call void @swift_initClassMetadata_UniversalStrategy(%swift.type* [[METADATA]], [[INT]] 3, {{.*}})
// CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvWvd
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{13|16}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience26ClassWithResilientPropertyC5colors5Int32VvWvd
// CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @_T016class_resilience26ClassWithResilientPropertyCML release,
// CHECK: ret void
// ClassWithResilientlySizedProperty metadata initialization function
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_ClassWithResilientlySizedProperty
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, [[INT]] {{60|96}}, [[INT]] 3)
// CHECK: [[RECTANGLE_METADATA:%.*]] = call %swift.type* @_T016resilient_struct9RectangleVMa()
// CHECK: call void @swift_initClassMetadata_UniversalStrategy(%swift.type* [[METADATA]], [[INT]] 2, {{.*}})
// CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{11|14}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvWvd
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @_T016class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvWvd
// CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @_T016class_resilience33ClassWithResilientlySizedPropertyCML release,
// CHECK: ret void
| apache-2.0 | 62576597ce9e2935cece407c59686972 | 53.340659 | 218 | 0.703134 | 3.770971 | false | false | false | false |
themonki/onebusaway-iphone | OneBusAway/ui/MapTable/EmbeddedCollectionViewCell.swift | 1 | 1308 | /**
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 EmbeddedCollectionViewCell: UICollectionViewCell {
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
view.backgroundColor = .white
view.alwaysBounceVertical = false
view.alwaysBounceHorizontal = true
self.contentView.addSubview(view)
return view
}()
override func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = contentView.frame
}
}
| apache-2.0 | bf5c5eb86631871e67d9ed701286ff4b | 35.333333 | 80 | 0.74159 | 5.317073 | false | false | false | false |
joerocca/GitHawk | Classes/Bookmark v2/Bookmark.swift | 1 | 1697 | //
// Bookmark.swift
// Freetime
//
// Created by Hesham Salman on 11/5/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
struct Bookmark: Codable {
let type: NotificationType
let name: String
let owner: String
let number: Int
let title: String
let hasIssueEnabled: Bool
let defaultBranch: String
init(type: NotificationType,
name: String,
owner: String,
number: Int = 0,
title: String = "",
hasIssueEnabled: Bool = false,
defaultBranch: String = "master"
) {
self.type = type
self.name = name
self.owner = owner
self.number = number
self.title = title
self.hasIssueEnabled = hasIssueEnabled
self.defaultBranch = defaultBranch
}
}
extension Bookmark: Equatable {
static func ==(lhs: Bookmark, rhs: Bookmark) -> Bool {
return lhs.type == rhs.type &&
lhs.name == rhs.name &&
lhs.owner == rhs.owner &&
lhs.number == rhs.number &&
lhs.title == rhs.title &&
lhs.hasIssueEnabled == rhs.hasIssueEnabled &&
lhs.defaultBranch == rhs.defaultBranch
}
}
extension Bookmark: Filterable {
func match(query: String) -> Bool {
let lowerQuery = query.lowercased()
if type.rawValue.contains(lowerQuery) { return true }
if String(number).contains(lowerQuery) { return true }
if title.lowercased().contains(lowerQuery) { return true }
if owner.lowercased().contains(lowerQuery) { return true }
if name.lowercased().contains(lowerQuery) { return true }
return false
}
}
| mit | 3e3b5813d3632d8d733c9db38b94485a | 26.354839 | 66 | 0.599057 | 4.416667 | false | false | false | false |
eridbardhaj/Weather | Pods/ObjectMapper/ObjectMapper/Core/Operators.swift | 1 | 11928 | //
// Operators.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
// Copyright (c) 2014 hearst. All rights reserved.
//
/**
* This file defines a new operator which is used to create a mapping between an object and a JSON key value.
* There is an overloaded operator definition for each type of object that is supported in ObjectMapper.
* This provides a way to add custom logic to handle specific types of objects
*/
infix operator <- {}
// MARK:- Objects with Basic types
/**
* Object of Basic type
*/
public func <- <T>(inout left: T, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.basicType(&left, object: right.value())
} else {
ToJSON.basicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/**
* Optional object of basic type
*/
public func <- <T>(inout left: T?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalBasicType(&left, object: right.value())
} else {
ToJSON.optionalBasicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/**
* Implicitly unwrapped optional object of basic type
*/
public func <- <T>(inout left: T!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalBasicType(&left, object: right.value())
} else {
ToJSON.optionalBasicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
// MARK:- Raw Representable types
/**
* Object of Raw Representable type
*/
public func <- <T: RawRepresentable>(inout left: T, right: Map) {
left <- (right, EnumTransform())
}
/**
* Optional Object of Raw Representable type
*/
public func <- <T: RawRepresentable>(inout left: T?, right: Map) {
left <- (right, EnumTransform())
}
/**
* Implicitly Unwrapped Optional Object of Raw Representable type
*/
public func <- <T: RawRepresentable>(inout left: T!, right: Map) {
left <- (right, EnumTransform())
}
// MARK:- Arrays of Raw Representable type
/**
* Array of Raw Representable object
*/
public func <- <T: RawRepresentable>(inout left: [T], right: Map) {
left <- (right, EnumTransform())
}
/**
* Array of Raw Representable object
*/
public func <- <T: RawRepresentable>(inout left: [T]?, right: Map) {
left <- (right, EnumTransform())
}
/**
* Array of Raw Representable object
*/
public func <- <T: RawRepresentable>(inout left: [T]!, right: Map) {
left <- (right, EnumTransform())
}
// MARK:- Dictionaries of Raw Representable type
/**
* Dictionary of Raw Representable object
*/
public func <- <T: RawRepresentable>(inout left: [String: T], right: Map) {
left <- (right, EnumTransform())
}
/**
* Dictionary of Raw Representable object
*/
public func <- <T: RawRepresentable>(inout left: [String: T]?, right: Map) {
left <- (right, EnumTransform())
}
/**
* Dictionary of Raw Representable object
*/
public func <- <T: RawRepresentable>(inout left: [String: T]!, right: Map) {
left <- (right, EnumTransform())
}
// MARK:- Transforms
/**
* Object of Basic type with Transform
*/
public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T, right: (Map, Transform)) {
if right.0.mappingType == MappingType.FromJSON {
var value: T? = right.1.transformFromJSON(right.0.currentValue)
FromJSON.basicType(&left, object: value)
} else {
var value: Transform.JSON? = right.1.transformToJSON(left)
ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary)
}
}
/**
* Optional object of basic type with Transform
*/
public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T?, right: (Map, Transform)) {
if right.0.mappingType == MappingType.FromJSON {
var value: T? = right.1.transformFromJSON(right.0.currentValue)
FromJSON.optionalBasicType(&left, object: value)
} else {
var value: Transform.JSON? = right.1.transformToJSON(left)
ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary)
}
}
/**
* Implicitly unwrapped optional object of basic type with Transform
*/
public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T!, right: (Map, Transform)) {
if right.0.mappingType == MappingType.FromJSON {
var value: T? = right.1.transformFromJSON(right.0.currentValue)
FromJSON.optionalBasicType(&left, object: value)
} else {
var value: Transform.JSON? = right.1.transformToJSON(left)
ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary)
}
}
/// Array of Basic type with Transform
public func <- <T: TransformType>(inout left: [T.Object], right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONArrayWithTransform(map.currentValue, transform)
FromJSON.basicType(&left, object: values)
} else {
let values = toJSONArrayWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Optional array of Basic type with Transform
public func <- <T: TransformType>(inout left: [T.Object]?, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONArrayWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONArrayWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Implicitly unwrapped optional array of Basic type with Transform
public func <- <T: TransformType>(inout left: [T.Object]!, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONArrayWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONArrayWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Dictionary of Basic type with Transform
public func <- <T: TransformType>(inout left: [String: T.Object], right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONDictionaryWithTransform(map.currentValue, transform)
FromJSON.basicType(&left, object: values)
} else {
let values = toJSONDictionaryWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Optional dictionary of Basic type with Transform
public func <- <T: TransformType>(inout left: [String: T.Object]?, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONDictionaryWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONDictionaryWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Implicitly unwrapped optional dictionary of Basic type with Transform
public func <- <T: TransformType>(inout left: [String: T.Object]!, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONDictionaryWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONDictionaryWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
private func fromJSONArrayWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [T.Object] {
if let values = input as? [AnyObject] {
return values.filterMap { value in
return transform.transformFromJSON(value)
}
} else {
return []
}
}
private func fromJSONDictionaryWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [String: T.Object] {
if let values = input as? [String: AnyObject] {
return values.filterMap { value in
return transform.transformFromJSON(value)
}
} else {
return [:]
}
}
private func toJSONArrayWithTransform<T: TransformType>(input: [T.Object]?, transform: T) -> [T.JSON]? {
return input?.filterMap { value in
return transform.transformToJSON(value)
}
}
private func toJSONDictionaryWithTransform<T: TransformType>(input: [String: T.Object]?, transform: T) -> [String: T.JSON]? {
return input?.filterMap { value in
return transform.transformToJSON(value)
}
}
// MARK:- Mappable Objects - <T: Mappable>
/**
* Object conforming to Mappable
*/
public func <- <T: Mappable>(inout left: T, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.object(&left, object: right.currentValue)
} else {
ToJSON.object(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/**
* Optional Mappable objects
*/
public func <- <T: Mappable>(inout left: T?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObject(&left, object: right.currentValue)
} else {
ToJSON.optionalObject(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/**
* Implicitly unwrapped optional Mappable objects
*/
public func <- <T: Mappable>(inout left: T!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObject(&left, object: right.currentValue)
} else {
ToJSON.optionalObject(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
// MARK:- Dictionary of Mappable objects - Dictionary<String, T: Mappable>
/**
* Dictionary of Mappable objects <String, T: Mappable>
*/
public func <- <T: Mappable>(inout left: Dictionary<String, T>, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.objectDictionary(&left, object: right.currentValue)
} else {
ToJSON.objectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/**
* Optional Dictionary of Mappable object <String, T: Mappable>
*/
public func <- <T: Mappable>(inout left: Dictionary<String, T>?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectDictionary(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/**
* Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable>
*/
public func <- <T: Mappable>(inout left: Dictionary<String, T>!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectDictionary(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
// MARK:- Array of Mappable objects - Array<T: Mappable>
/**
* Array of Mappable objects
*/
public func <- <T: Mappable>(inout left: Array<T>, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.objectArray(&left, object: right.currentValue)
} else {
ToJSON.objectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/**
* Optional array of Mappable objects
*/
public func <- <T: Mappable>(inout left: Array<T>?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectArray(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/**
* Implicitly unwrapped Optional array of Mappable objects
*/
public func <- <T: Mappable>(inout left: Array<T>!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectArray(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
} | mit | 53f084d8116a6cdec1f763f117968886 | 31.862259 | 125 | 0.708836 | 3.919816 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/instantPageWebEmbedView.swift | 1 | 4423 | //
// instantPageWebEmbedView.swift
// Telegram
//
// Created by keepcoder on 10/08/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TelegramCore
import TGUIKit
import WebKit
private final class InstantPageWebView : WKWebView {
var enableScrolling: Bool = true
override func scrollWheel(with event: NSEvent) {
if enableScrolling {
super.scrollWheel(with: event)
} else {
if event.scrollingDeltaX != 0 {
super.scrollWheel(with: event)
} else {
super.enclosingScrollView?.scrollWheel(with: event)
}
}
}
}
private class WeakInstantPageWebEmbedNodeMessageHandler: NSObject, WKScriptMessageHandler {
private let f: (WKScriptMessage) -> ()
init(_ f: @escaping (WKScriptMessage) -> ()) {
self.f = f
super.init()
}
func userContentController(_ controller: WKUserContentController, didReceive scriptMessage: WKScriptMessage) {
self.f(scriptMessage)
}
}
final class InstantPageWebEmbedView: View, InstantPageView {
let url: String?
let html: String?
private var webView: InstantPageWebView!
let updateWebEmbedHeight: (CGFloat) -> Void
init(frame: CGRect, url: String?, html: String?, enableScrolling: Bool, updateWebEmbedHeight: @escaping(CGFloat) -> Void) {
self.url = url
self.html = html
self.updateWebEmbedHeight = updateWebEmbedHeight
super.init()
let js = "var TelegramWebviewProxyProto = function() {}; " +
"TelegramWebviewProxyProto.prototype.postEvent = function(eventName, eventData) { " +
"window.webkit.messageHandlers.performAction.postMessage({'eventName': eventName, 'eventData': eventData}); " +
"}; " +
"var TelegramWebviewProxy = new TelegramWebviewProxyProto();"
let configuration = WKWebViewConfiguration()
let userController = WKUserContentController()
let userScript = WKUserScript(source: js, injectionTime: .atDocumentStart, forMainFrameOnly: false)
userController.addUserScript(userScript)
userController.add(WeakInstantPageWebEmbedNodeMessageHandler { [weak self] message in
if let strongSelf = self {
strongSelf.handleScriptMessage(message)
}
}, name: "performAction")
configuration.userContentController = userController
let webView = InstantPageWebView(frame: CGRect(origin: CGPoint(), size: frame.size), configuration: configuration)
if let html = html {
webView.loadHTMLString(html, baseURL: nil)
} else if let url = url, let parsedUrl = URL(string: url) {
var request = URLRequest(url: parsedUrl)
if let scheme = parsedUrl.scheme, let host = parsedUrl.host {
let referrer = "\(scheme)://\(host)"
request.setValue(referrer, forHTTPHeaderField: "Referer")
}
webView.load(request)
}
self.webView = webView
webView.enableScrolling = enableScrolling
addSubview(webView)
}
private func handleScriptMessage(_ message: WKScriptMessage) {
guard let body = message.body as? [String: Any] else {
return
}
guard let eventName = body["eventName"] as? String, let eventString = body["eventData"] as? String else {
return
}
guard let eventData = eventString.data(using: .utf8) else {
return
}
guard let dict = (try? JSONSerialization.jsonObject(with: eventData, options: [])) as? [String: Any] else {
return
}
if eventName == "resize_frame", let height = dict["height"] as? Int {
self.updateWebEmbedHeight(CGFloat(height))
}
}
deinit {
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
override func layout() {
super.layout()
self.webView.frame = self.bounds
}
func updateIsVisible(_ isVisible: Bool) {
}
}
| gpl-2.0 | 26c2c92a7013f06d870ebc20658a9fca | 30.140845 | 127 | 0.602895 | 5.065292 | false | false | false | false |
acalvomartinez/ironhack | Week 6/Day 3/MyPlayground.playground/Pages/Closures.xcplaygroundpage/Sources/Person.swift | 1 | 474 | import Foundation
public class Coordinate {
public var latitude: Float?
public var longitude: Float?
public init(latitude: Float, longitude: Float) {
self.latitude = latitude
self.longitude = longitude
}
}
public class Person {
public var name: String = "John Doe"
public var address: String = "C/ María Martillo"
public var homeCoordinate: Coordinate?
public init(name: String) {
self.name = name
}
} | mit | b9d90bf842dfb1cf6e0c0589dc1bc968 | 21.571429 | 52 | 0.64482 | 4.3 | false | false | false | false |
iadmir/Signal-iOS | Signal/src/Profiles/ProfileFetcherJob.swift | 2 | 7439 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
@objc
class ProfileFetcherJob: NSObject {
let TAG = "[ProfileFetcherJob]"
let networkManager: TSNetworkManager
let storageManager: TSStorageManager
// This property is only accessed on the main queue.
static var fetchDateMap = [String: Date]()
let ignoreThrottling: Bool
public class func run(thread: TSThread, networkManager: TSNetworkManager) {
ProfileFetcherJob(networkManager: networkManager).run(recipientIds: thread.recipientIdentifiers)
}
public class func run(recipientId: String, networkManager: TSNetworkManager, ignoreThrottling: Bool) {
ProfileFetcherJob(networkManager: networkManager, ignoreThrottling:ignoreThrottling).run(recipientIds: [recipientId])
}
init(networkManager: TSNetworkManager, ignoreThrottling: Bool = false) {
self.networkManager = networkManager
self.storageManager = TSStorageManager.shared()
self.ignoreThrottling = ignoreThrottling
}
public func run(recipientIds: [String]) {
AssertIsOnMainThread()
DispatchQueue.main.async {
for recipientId in recipientIds {
self.updateProfile(recipientId: recipientId)
}
}
}
enum ProfileFetcherJobError: Error {
case throttled(lastTimeInterval: TimeInterval),
unknownNetworkError
}
public func updateProfile(recipientId: String, remainingRetries: Int = 3) {
self.getProfile(recipientId: recipientId).then { profile in
self.updateProfile(signalServiceProfile: profile)
}.catch { error in
switch error {
case ProfileFetcherJobError.throttled(let lastTimeInterval):
Logger.info("\(self.TAG) skipping updateProfile: \(recipientId), lastTimeInterval: \(lastTimeInterval)")
case let error as SignalServiceProfile.ValidationError:
Logger.warn("\(self.TAG) skipping updateProfile retry. Invalid profile for: \(recipientId) error: \(error)")
default:
if remainingRetries > 0 {
self.updateProfile(recipientId: recipientId, remainingRetries: remainingRetries - 1)
} else {
Logger.error("\(self.TAG) in \(#function) failed to get profile with error: \(error)")
}
}
}.retainUntilComplete()
}
public func getProfile(recipientId: String) -> Promise<SignalServiceProfile> {
AssertIsOnMainThread()
if !ignoreThrottling {
if let lastDate = ProfileFetcherJob.fetchDateMap[recipientId] {
let lastTimeInterval = fabs(lastDate.timeIntervalSinceNow)
// Don't check a profile more often than every N minutes.
//
// Only throttle profile fetch in production builds in order to
// facilitate debugging.
let kGetProfileMaxFrequencySeconds = _isDebugAssertConfiguration() ? 0 : 60.0 * 5.0
guard lastTimeInterval > kGetProfileMaxFrequencySeconds else {
return Promise(error: ProfileFetcherJobError.throttled(lastTimeInterval: lastTimeInterval))
}
}
}
ProfileFetcherJob.fetchDateMap[recipientId] = Date()
Logger.error("\(self.TAG) getProfile: \(recipientId)")
let request = OWSGetProfileRequest(recipientId: recipientId)
let (promise, fulfill, reject) = Promise<SignalServiceProfile>.pending()
self.networkManager.makeRequest(
request,
success: { (_: URLSessionDataTask?, responseObject: Any?) -> Void in
do {
let profile = try SignalServiceProfile(recipientId: recipientId, rawResponse: responseObject)
fulfill(profile)
} catch {
reject(error)
}
},
failure: { (_: URLSessionDataTask?, error: Error?) in
if let error = error {
reject(error)
}
reject(ProfileFetcherJobError.unknownNetworkError)
})
return promise
}
private func updateProfile(signalServiceProfile: SignalServiceProfile) {
verifyIdentityUpToDateAsync(recipientId: signalServiceProfile.recipientId, latestIdentityKey: signalServiceProfile.identityKey)
OWSProfileManager.shared().updateProfile(forRecipientId: signalServiceProfile.recipientId,
profileNameEncrypted: signalServiceProfile.profileNameEncrypted,
avatarUrlPath: signalServiceProfile.avatarUrlPath)
}
private func verifyIdentityUpToDateAsync(recipientId: String, latestIdentityKey: Data) {
OWSDispatch.sessionStoreQueue().async {
if OWSIdentityManager.shared().saveRemoteIdentity(latestIdentityKey, recipientId: recipientId) {
Logger.info("\(self.TAG) updated identity key with fetched profile for recipient: \(recipientId)")
self.storageManager.archiveAllSessions(forContact: recipientId)
} else {
// no change in identity.
}
}
}
}
struct SignalServiceProfile {
let TAG = "[SignalServiceProfile]"
enum ValidationError: Error {
case invalid(description: String)
case invalidIdentityKey(description: String)
case invalidProfileName(description: String)
}
public let recipientId: String
public let identityKey: Data
public let profileNameEncrypted: Data?
public let avatarUrlPath: String?
init(recipientId: String, rawResponse: Any?) throws {
self.recipientId = recipientId
guard let responseDict = rawResponse as? [String: Any?] else {
throw ValidationError.invalid(description: "\(TAG) unexpected type: \(String(describing: rawResponse))")
}
guard let identityKeyString = responseDict["identityKey"] as? String else {
throw ValidationError.invalidIdentityKey(description: "\(TAG) missing identity key: \(String(describing: rawResponse))")
}
guard let identityKeyWithType = Data(base64Encoded: identityKeyString) else {
throw ValidationError.invalidIdentityKey(description: "\(TAG) unable to parse identity key: \(identityKeyString)")
}
let kIdentityKeyLength = 33
guard identityKeyWithType.count == kIdentityKeyLength else {
throw ValidationError.invalidIdentityKey(description: "\(TAG) malformed key \(identityKeyString) with decoded length: \(identityKeyWithType.count)")
}
if let profileNameString = responseDict["name"] as? String {
guard let data = Data(base64Encoded: profileNameString) else {
throw ValidationError.invalidProfileName(description: "\(TAG) unable to parse profile name: \(profileNameString)")
}
self.profileNameEncrypted = data
} else {
self.profileNameEncrypted = nil
}
self.avatarUrlPath = responseDict["avatar"] as? String
// `removeKeyType` is an objc category method only on NSData, so temporarily cast.
self.identityKey = (identityKeyWithType as NSData).removeKeyType() as Data
}
}
| gpl-3.0 | 30b18fb3e1cae212fdcce0996f68d773 | 40.327778 | 160 | 0.647264 | 5.84827 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/elongation-preview-master/ElongationPreview/Source/ElongationConfig.swift | 2 | 3530 | //
// ElongationConfig.swift
// ElongationPreview
//
// Created by Abdurahim Jauzee on 09/02/2017.
// Copyright © 2017 Ramotion. All rights reserved.
//
import UIKit
/// Whole module views configuration
public struct ElongationConfig {
/// Empty public initializer.
public init() {}
/// Shared instance. Override this property to apply changes.
public static var shared = ElongationConfig()
// MARK: Behaviour 🔧
/// :nodoc:
public enum CellTouchAction {
case collapseOnTopExpandOnBottom, collapseOnBottomExpandOnTop, collapseOnBoth, expandOnBoth, expandOnTop, expandOnBottom
}
/// What `elongationCell` should do on touch
public var cellTouchAction = CellTouchAction.collapseOnTopExpandOnBottom
/// :nodoc:
public enum HeaderTouchAction {
case collpaseOnBoth, collapseOnTop, collapseOnBottom, noAction
}
/// What `elongationHeader` should do on touch
public var headerTouchAction = HeaderTouchAction.collapseOnTop
/// Enable gestures on `ElongationCell` & `ElongationHeader`.
/// These gestures will give ability to expand/dismiss the cell and detail view controller.
/// Default value: `true`
public var isSwipeGesturesEnabled = true
/// Enable `UIPreviewIntearction` on `ElongationCell`.
/// Default value: `true`
public var forceTouchPreviewInteractionEnabled = true
/// Enable `UILongPressGesture` on `ElongationCell`.
/// This gesture will allow to `expand` `ElongationCell` on long tap. By default, this option will be used on devices without 3D Touch technology.
/// Default value: `true`
public var longPressGestureEnabled = true
// MARK: Appearance 🎨
/// Actual height of `topView`.
/// Default value: `200`
public var topViewHeight: CGFloat = 200
/// `topView` scale value which will be used for making CGAffineTransform
/// to `expanded` state
/// Default value: `0.9`
public var scaleViewScaleFactor: CGFloat = 0.9
/// Parallax effect factor.
/// Default value: `nil`
public var parallaxFactor: CGFloat?
/// Should we enable parallax effect on ElongationCell (read-only).
/// Will be `true` if `separator` not `nil` && greater than zero
public var isParallaxEnabled: Bool {
switch parallaxFactor {
case .none: return false
case let .some(value): return value > 0
}
}
/// Offset of `bottomView` against `topView`
/// Default value: `20`
public var bottomViewOffset: CGFloat = 20
/// `bottomView` height value
/// Default value: `180`
public var bottomViewHeight: CGFloat = 180
/// Height of custom separator line between cells in tableView
/// Default value: `nil`
public var separatorHeight: CGFloat?
/// Color of custom separator
/// Default value: `.white`
public var separatorColor: UIColor = .white
/// Should we create custom separator view (read-only).
/// Will be `true` if `separator` not `nil` && greater than zero.
public var customSeparatorEnabled: Bool {
switch separatorHeight {
case .none: return false
case let .some(value): return value > 0
}
}
/// Duration of `detail` view controller presentation animation
/// Default value: `0.3`
public var detailPresentingDuration: TimeInterval = 0.3
/// Duration of `detail` view controller dismissing animation
/// Default value: `0.4`
public var detailDismissingDuration: TimeInterval = 0.4
}
| mit | 0baf31cb5dc97bb6ef8af070df07b819 | 31.62037 | 150 | 0.680386 | 4.660053 | false | false | false | false |
embryoconcepts/TIY-Assignments | 00 -- This-is-Heavy/Counter (conversion errors)/Counter/ViewController.swift | 1 | 4401 | //
// ViewController.swift
// Swift-Counter
//
// Created by Ben Gohlke on 8/17/15.
// Copyright (c) 2015 The Iron Yard. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
// The following variables and constants are called properties; they hold values that can be accessed from any method in this class
// This allows the app to set its current count when the app first loads.
// The line below simply generates a random number and then makes sure it falls within the bounds 1-100.
var currentCount: Int = Int(arc4random() % 100)
// These are called IBOutlets and are a kind of property; they connect elements in the storyboard with the code so you can update the UI elements from code.
@IBOutlet weak var countTextField: UITextField!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var stepper: UIStepper!
override func viewDidLoad()
{
super.viewDidLoad()
//
// 1. Once the currentCount variable is set, each of the UI elements on the screen need to be updated to match the currentCount.
// There is a method below that performs these steps. All you need to do perform a method call in the line below.
//
updateViewsWithCurrentCount()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateViewsWithCurrentCount()
{
// Here we are updating the different subviews in our main view with the current count.
//
// 2. The textfield needs to always show the current count. Fill in the blank below to set the text value of the textfield.
//
countTextField.text = "\(currentCount)"
//
// 3. Here we are setting the value property of the UISlider in the view. This causes the slider to set its handle to the
// appropriate position. Fill in the blank below.
//
slider.value = Float(currentCount)
//
// 4. We also need to update the value of the UIStepper. The user will not see any change to the stepper, but it needs to have a
// current value nonetheless, so when + or - is tapped, it will know what value to increment. Fill in the blanks below.
//
stepper.value = Double(currentCount)
}
// MARK: - Gesture recognizers
@IBAction func viewTapped(sender: UITapGestureRecognizer)
{
// This method is run whenever the user taps on the blank, white view (meaning they haven't tapped any of the controls on the
// view). It hides the keyboard if the user has edited the count textfield, and also updates the currentCount variable.
if countTextField.isFirstResponder()
{
countTextField.resignFirstResponder()
//
// 8. Hopefully you're seeing a pattern here. After we update the currentCount variable, what do we need to do next? Fill in
// the blank below.
//
updateViewsWithCurrentCount()
}
}
// MARK: - Action handlers
@IBAction func sliderValueChanged(sender: UISlider)
{
//
// 5. This method will run whenever the value of the slider is changed by the user. The "sender" object passed in as an argument
// to this method represents the slider from the view. We need to take the value of the slider and use it to update the
// value of our "currentCount" instance variable. Fill in the blank below.
//
currentCount = Int(sender.value)
//
// 6. Once we update the value of currentCount, we need to make sure all the UI elements on the screen are updated to keep
// everything in sync. We have previously done this (look in viewDidLoad). Fill in the blank below.
//
updateViewsWithCurrentCount()
}
@IBAction func stepperValueChanged(sender: UIStepper)
{
//
// 7. This method is run when the value of the stepper is changed by the user. If you've done steps 5 and 6 already, these steps
// should look pretty familiar, hint, hint. ;) Fill in the blanks below.
//
currentCount = Int(sender.value)
updateViewsWithCurrentCount()
}
} | cc0-1.0 | 71810132ad428ed7c96ffcebc21a90ff | 40.140187 | 160 | 0.646217 | 4.939394 | false | false | false | false |
linhaosunny/smallGifts | 小礼品/小礼品/Classes/Module/Me/Chat/ChatCells/VoiceChatCell.swift | 1 | 5684 | //
// VoiceChatCell.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/28.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
import SnapKit
class VoiceChatCell: BaseChatCell {
//MARK: 属性
weak var delegate:VoiceChatCellDelegate?
var viewModel:VoiceChatCellViewModel?{
didSet{
super.baseViewModel = viewModel
backView.image = viewModel?.voicebackImage
backView.highlightedImage = viewModel?.voicebackHightLightImage
voiceTimeLabel.text = viewModel?.voiceTimeLabelText
voiceTimeLabel.font = viewModel?.voiceTimeLabelFont
guard let viewFrame = viewModel?.viewFrame else {
return
}
layoutVoiceChatCell(viewFrame)
}
}
private var isRecordigAnimation:Bool = false
private var isPlayingAnimation:Bool = false
private var backViewAlpha:CGFloat = 1.0
//MARK: 懒加载
lazy var voiceImage:VoiceView = { () -> VoiceView in
let image = VoiceView(frame: CGRect.zero)
image.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(voiceImageViewDidTap))
image.addGestureRecognizer(tap)
return image
}()
lazy var voiceTimeLabel:UILabel = { () -> UILabel in
let label = UILabel()
label.textColor = UIColor.gray
return label
}()
//MARK: 构造方法
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupVoiceChatCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: 私有方法
private func setupVoiceChatCell() {
addSubview(voiceImage)
addSubview(voiceTimeLabel)
}
private func layoutVoiceChatCell(_ viewFrame:ViewFrame) {
voiceImage.viewLocation = self.viewModel?.viewLocation
if self.viewModel?.viewLocation == .right {
voiceTimeLabel.snp.remakeConstraints({ (make) in
make.centerY.equalTo(backView.snp.centerY)
make.right.equalTo(voiceImage.snp.left).offset(-margin)
})
voiceImage.snp.remakeConstraints({ (make) in
make.right.equalTo(backView).offset(-margin*2.0)
make.width.height.equalTo(20)
})
backView.snp.remakeConstraints { (make) in
make.left.equalTo(voiceTimeLabel).offset(-margin*2.0)
make.bottom.equalTo(voiceImage).offset(margin*2.0)
make.right.equalTo(avatarButton.snp.left).offset(-margin*0.5)
make.top.equalTo(nameLabel.snp.bottom).offset(-margin*0.1)
}
}
else {
voiceTimeLabel.snp.remakeConstraints({ (make) in
make.left.equalTo(voiceImage.snp.right).offset(margin)
make.centerY.equalTo(backView.snp.centerY)
})
voiceImage.snp.remakeConstraints({ (make) in
make.left.equalTo(backView).offset(margin*2.0)
make.width.height.equalTo(20)
})
backView.snp.remakeConstraints { (make) in
make.right.equalTo(voiceTimeLabel).offset(margin*2.0)
make.bottom.equalTo(voiceImage).offset(margin*2.0)
make.top.equalTo(nameLabel.snp.bottom).offset(-margin*0.1)
make.left.equalTo(avatarButton.snp.right).offset(margin*0.5)
}
}
if viewModel?.voiceStatus == .recording {
voiceTimeLabel.isHidden = true
voiceImage.isHidden = true
startRecordingAnimation()
}
else{
voiceTimeLabel.isHidden = false
voiceImage.isHidden = false
stopRecordingAnimation()
}
if viewModel?.voiceStatus == .playing {
voiceImage.startPlaying()
}
else {
voiceImage.stopPlaying()
}
}
private func startRecordingAnimation() {
isRecordigAnimation = true
backViewAlpha = 0.4
recordingAnimation()
}
private func stopRecordingAnimation() {
isRecordigAnimation = false
backViewAlpha = 1.0
backView.alpha = backViewAlpha
}
private func recordingAnimation() {
UIView.animate(withDuration: 1.0, animations: {
self.backView.alpha = self.backViewAlpha
}) { (finished) in
self.backViewAlpha = self.backViewAlpha > 0.9 ? 0.4:1.0
if finished && self.isRecordigAnimation {
self.recordingAnimation()
}
else{
self.backView.alpha = 1.0
}
}
}
private func voicePlayingAnimation() {
if isPlayingAnimation {
voiceImage.startPlaying()
}
else{
voiceImage.stopPlaying()
}
}
//MARK: 内部响应
@objc private func voiceImageViewDidTap() {
isPlayingAnimation = !isPlayingAnimation
//: 播放
voicePlayingAnimation()
delegate?.didTapVoiceChatCell(cell: self ,isStart: isPlayingAnimation)
}
}
//MARK: 协议
protocol VoiceChatCellDelegate:NSObjectProtocol {
func didTapVoiceChatCell(cell:VoiceChatCell, isStart:Bool)
}
| mit | e5d557b65742335d475d643ed81ea3a4 | 29.058824 | 95 | 0.573563 | 5.01875 | false | false | false | false |
jamy0801/LGWeChatKit | LGWeChatKit/LGChatKit/utilities/LGAudioRecorder.swift | 1 | 3991 | //
// LGAudioRecorder.swift
// LGChatViewController
//
// Created by jamy on 10/13/15.
// Copyright © 2015 jamy. All rights reserved.
//
import UIKit
import AVFoundation
protocol LGAudioRecorderDelegate {
func audioRecorderUpdateMetra(metra: Float)
}
let soundPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
let audioSettings: [String: AnyObject] = [AVLinearPCMIsFloatKey: NSNumber(bool: false),
AVLinearPCMIsBigEndianKey: NSNumber(bool: false),
AVLinearPCMBitDepthKey: NSNumber(int: 16),
AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatLinearPCM),
AVNumberOfChannelsKey: NSNumber(int: 1), AVSampleRateKey: NSNumber(int: 16000),
AVEncoderAudioQualityKey: NSNumber(integer: AVAudioQuality.Medium.rawValue)]
class LGAudioRecorder: NSObject, AVAudioRecorderDelegate {
var audioData: NSData!
var operationQueue: NSOperationQueue!
var recorder: AVAudioRecorder!
var startTime: Double!
var endTimer: Double!
var timeInterval: NSNumber!
var delegate: LGAudioRecorderDelegate?
convenience init(fileName: String) {
self.init()
let filePath = NSURL(fileURLWithPath: (soundPath as NSString).stringByAppendingPathComponent(fileName))
recorder = try! AVAudioRecorder(URL: filePath, settings: audioSettings)
recorder.delegate = self
recorder.meteringEnabled = true
}
override init() {
operationQueue = NSOperationQueue()
super.init()
}
func startRecord() {
startTime = NSDate().timeIntervalSince1970
performSelector("readyStartRecord", withObject: self, afterDelay: 0.5)
}
func readyStartRecord() {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryRecord)
} catch {
NSLog("setCategory fail")
return
}
do {
try audioSession.setActive(true)
} catch {
NSLog("setActive fail")
return
}
recorder.record()
let operation = NSBlockOperation()
operation.addExecutionBlock(updateMeters)
operationQueue.addOperation(operation)
}
func stopRecord() {
endTimer = NSDate().timeIntervalSince1970
timeInterval = nil
if (endTimer - startTime) < 0.5 {
NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: "readyStartRecord", object: self)
} else {
timeInterval = NSNumber(int: NSNumber(double: recorder.currentTime).intValue)
if timeInterval.intValue < 1 {
performSelector("readyStopRecord", withObject: self, afterDelay: 0.4)
} else {
readyStopRecord()
}
}
operationQueue.cancelAllOperations()
}
func readyStopRecord() {
recorder.stop()
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(false, withOptions: .NotifyOthersOnDeactivation)
} catch {
// no-op
}
audioData = NSData(contentsOfURL: recorder.url)
}
func updateMeters() {
repeat {
recorder.updateMeters()
timeInterval = NSNumber(float: NSNumber(double: recorder.currentTime).floatValue)
let averagePower = recorder.averagePowerForChannel(0)
// let pearPower = recorder.peakPowerForChannel(0)
// NSLog("%@ %f %f", timeInterval, averagePower, pearPower)
delegate?.audioRecorderUpdateMetra(averagePower)
NSThread.sleepForTimeInterval(0.2)
} while(recorder.recording)
}
// MARK: audio delegate
func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder, error: NSError?) {
NSLog("%@", (error?.localizedDescription)!)
}
}
| mit | 536e2b91adad44dab140ae6b0a916a8f | 30.417323 | 111 | 0.639599 | 5.377358 | false | false | false | false |
happyeverydayzhh/WWDC | WWDC/VideosViewController.swift | 1 | 13898 | //
// ViewController.swift
// WWDC
//
// Created by Guilherme Rambo on 18/04/15.
// Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
import ViewUtils
class VideosViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
@IBOutlet weak var scrollView: NSScrollView!
@IBOutlet weak var tableView: NSTableView!
var splitManager: SplitManager?
var indexOfLastSelectedRow = -1
let savedSearchTerm = Preferences.SharedPreferences().searchTerm
var finishedInitialSetup = false
var restoredSelection = false
var loadedStoryboard = false
lazy var headerController: VideosHeaderViewController! = VideosHeaderViewController.loadDefaultController()
override func awakeFromNib() {
super.awakeFromNib()
if splitManager == nil && loadedStoryboard {
if let splitViewController = parentViewController as? NSSplitViewController {
splitManager = SplitManager(splitView: splitViewController.splitView)
// this caused a crash when running on 10.11...
// splitViewController.splitView.delegate = self.splitManager
}
}
loadedStoryboard = true
}
override func awakeAfterUsingCoder(aDecoder: NSCoder) -> AnyObject? {
return super.awakeAfterUsingCoder(aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
setupSearching()
setupScrollView()
tableView.gridColor = Theme.WWDCTheme.separatorColor
loadSessions(refresh: false, quiet: false)
let nc = NSNotificationCenter.defaultCenter()
nc.addObserverForName(SessionProgressDidChangeNotification, object: nil, queue: nil) { _ in
self.reloadTablePreservingSelection()
}
nc.addObserverForName(SessionFavoriteStatusDidChangeNotification, object: nil, queue: nil) { _ in
self.reloadTablePreservingSelection()
}
nc.addObserverForName(VideoStoreNotificationDownloadStarted, object: nil, queue: NSOperationQueue.mainQueue()) { _ in
self.reloadTablePreservingSelection()
}
nc.addObserverForName(VideoStoreNotificationDownloadFinished, object: nil, queue: NSOperationQueue.mainQueue()) { _ in
self.reloadTablePreservingSelection()
}
nc.addObserverForName(VideoStoreDownloadedFilesChangedNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in
self.reloadTablePreservingSelection()
}
nc.addObserverForName(AutomaticRefreshPreferenceChangedNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in
self.setupAutomaticSessionRefresh()
}
}
override func viewDidAppear() {
super.viewDidAppear()
if finishedInitialSetup {
return
}
GRLoadingView.showInWindow(self.view.window!)
finishedInitialSetup = true
}
func setupScrollView() {
let insetHeight = NSHeight(headerController.view.frame)
scrollView.automaticallyAdjustsContentInsets = false
scrollView.contentInsets = NSEdgeInsets(top: insetHeight, left: 0, bottom: 0, right: 0)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateScrollInsets:", name: LiveEventBannerVisibilityChangedNotification, object: nil)
setupViewHeader(insetHeight)
}
func updateScrollInsets(note: NSNotification?) {
if let bannerController = LiveEventBannerViewController.DefaultController {
scrollView.contentInsets = NSEdgeInsets(top: scrollView.contentInsets.top, left: 0, bottom: bannerController.barHeight, right: 0)
}
}
func setupViewHeader(insetHeight: CGFloat) {
if let superview = scrollView.superview {
superview.addSubview(headerController.view)
headerController.view.frame = CGRectMake(0, NSHeight(superview.frame)-insetHeight, NSWidth(superview.frame), insetHeight)
headerController.view.autoresizingMask = [NSAutoresizingMaskOptions.ViewWidthSizable, NSAutoresizingMaskOptions.ViewMinYMargin]
headerController.performSearch = search
}
// show search term from previous launch in search bar
headerController.searchBar.stringValue = savedSearchTerm
}
var sessions: [Session]! {
didSet {
if sessions != nil {
// run transcript indexing service if needed
TranscriptStore.SharedStore.runIndexerIfNeeded(sessions)
headerController.enable()
// restore search from previous launch
if savedSearchTerm != "" {
search(savedSearchTerm)
indexOfLastSelectedRow = Preferences.SharedPreferences().selectedSession
}
searchController.sessions = sessions
}
if savedSearchTerm == "" {
reloadTablePreservingSelection()
}
}
}
// MARK: Session loading
func loadSessions(refresh refresh: Bool, quiet: Bool) {
if !quiet {
if let window = view.window {
GRLoadingView.showInWindow(window)
}
}
let completionHandler: DataStore.fetchSessionsCompletionHandler = { success, sessions in
dispatch_async(dispatch_get_main_queue()) {
self.sessions = sessions
self.splitManager?.restoreDividerPosition()
self.splitManager?.startSavingDividerPosition()
if !quiet {
GRLoadingView.dismissAllAfterDelay(0.3)
}
self.setupAutomaticSessionRefresh()
}
}
DataStore.SharedStore.fetchSessions(completionHandler, disableCache: refresh)
}
@IBAction func refresh(sender: AnyObject?) {
loadSessions(refresh: true, quiet: false)
}
var sessionListRefreshTimer: NSTimer?
func setupAutomaticSessionRefresh() {
if Preferences.SharedPreferences().automaticRefreshEnabled {
if sessionListRefreshTimer == nil {
sessionListRefreshTimer = NSTimer.scheduledTimerWithTimeInterval(Preferences.SharedPreferences().automaticRefreshInterval, target: self, selector: "sessionListRefreshFromTimer", userInfo: nil, repeats: true)
}
} else {
sessionListRefreshTimer?.invalidate()
sessionListRefreshTimer = nil
}
}
func sessionListRefreshFromTimer() {
loadSessions(refresh: true, quiet: true)
}
// MARK: TableView
func reloadTablePreservingSelection() {
tableView.reloadData()
if !restoredSelection {
indexOfLastSelectedRow = Preferences.SharedPreferences().selectedSession
restoredSelection = true
}
if indexOfLastSelectedRow > -1 {
tableView.selectRowIndexes(NSIndexSet(index: indexOfLastSelectedRow), byExtendingSelection: false)
}
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if let count = displayedSessions?.count {
return count
} else {
return 0
}
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeViewWithIdentifier("video", owner: tableView) as! VideoTableCellView
if row > displayedSessions.count {
return cell
}
cell.session = displayedSessions[row]
return cell
}
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 40.0
}
func tableView(tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
return tableView.makeViewWithIdentifier("row", owner: tableView) as? NSTableRowView
}
// MARK: Table Menu
@IBAction func markAsWatchedMenuAction(sender: NSMenuItem) {
// if there is only one row selected, change the status of the clicked row instead of using the selection
if tableView.selectedRowIndexes.count < 2 {
var session = displayedSessions[tableView.clickedRow]
session.progress = 100
} else {
doMassiveSessionPropertyUpdate(.Progress(100))
}
}
@IBAction func markAsUnwatchedMenuAction(sender: NSMenuItem) {
// if there is only one row selected, change the status of the clicked row instead of using the selection
if tableView.selectedRowIndexes.count < 2 {
var session = displayedSessions[tableView.clickedRow]
session.progress = 0
} else {
doMassiveSessionPropertyUpdate(.Progress(0))
}
}
@IBAction func addToFavoritesMenuAction(sender: NSMenuItem) {
// if there is only one row selected, change the status of the clicked row instead of using the selection
if tableView.selectedRowIndexes.count < 2 {
var session = displayedSessions[tableView.clickedRow]
session.favorite = true
} else {
doMassiveSessionPropertyUpdate(.Favorite(true))
}
}
@IBAction func removeFromFavoritesMenuAction(sender: NSMenuItem) {
// if there is only one row selected, change the status of the clicked row instead of using the selection
if tableView.selectedRowIndexes.count < 2 {
var session = displayedSessions[tableView.clickedRow]
session.favorite = false
} else {
doMassiveSessionPropertyUpdate(.Favorite(false))
}
}
private let userInitiatedQ = dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)
private enum MassiveUpdateProperty {
case Progress(Double)
case Favorite(Bool)
}
// changes the property of all selected sessions on a background queue
private func doMassiveSessionPropertyUpdate(property: MassiveUpdateProperty) {
dispatch_async(userInitiatedQ) {
self.tableView.selectedRowIndexes.enumerateIndexesUsingBlock { idx, _ in
let session = self.displayedSessions[idx]
switch property {
case .Progress(let progress):
session.setProgressWithoutSendingNotification(progress)
case .Favorite(let favorite):
session.setFavoriteWithoutSendingNotification(favorite)
}
}
dispatch_async(dispatch_get_main_queue()) {
self.reloadTablePreservingSelection()
}
}
}
@IBAction func copyURL(sender: NSMenuItem) {
var stringToCopy:String?
if tableView.selectedRowIndexes.count < 2 && tableView.clickedRow >= 0 {
let session = displayedSessions[tableView.clickedRow]
stringToCopy = session.shareURL
} else {
stringToCopy = ""
for idx in tableView.selectedRowIndexes {
let session = self.displayedSessions[idx]
stringToCopy? += session.shareURL
if tableView.selectedRowIndexes.lastIndex != idx {
stringToCopy? += "\n"
}
}
}
if let string = stringToCopy {
let pb = NSPasteboard.generalPasteboard()
pb.clearContents()
pb.writeObjects([string])
}
}
@IBAction func copy(sender: NSMenuItem) {
copyURL(sender)
}
// MARK: Navigation
var detailsViewController: VideoDetailsViewController? {
get {
if let splitViewController = parentViewController as? NSSplitViewController {
return splitViewController.childViewControllers[1] as? VideoDetailsViewController
} else {
return nil
}
}
}
func tableViewSelectionDidChange(notification: NSNotification) {
if let detailsVC = detailsViewController {
detailsVC.selectedCount = tableView.selectedRowIndexes.count
}
if tableView.selectedRow >= 0 {
Preferences.SharedPreferences().selectedSession = tableView.selectedRow
indexOfLastSelectedRow = tableView.selectedRow
let session = displayedSessions[tableView.selectedRow]
if let detailsVC = detailsViewController {
detailsVC.session = session
}
} else {
if let detailsVC = detailsViewController {
detailsVC.session = nil
}
}
}
// MARK: Search
var searchController = SearchController()
private func setupSearching() {
searchController.searchDidFinishCallback = {
dispatch_async(dispatch_get_main_queue()) {
self.reloadTablePreservingSelection()
}
}
}
var currentSearchTerm: String? {
didSet {
if currentSearchTerm != nil {
Preferences.SharedPreferences().searchTerm = currentSearchTerm!
} else {
Preferences.SharedPreferences().searchTerm = ""
}
}
}
func search(term: String) {
currentSearchTerm = term
searchController.searchFor(currentSearchTerm)
}
var displayedSessions: [Session]! {
get {
return searchController.displayedSessions
}
}
}
| bsd-2-clause | 13309e4bb7fe78d6067877472f055e23 | 34.363868 | 223 | 0.620305 | 5.969931 | false | false | false | false |
gank0326/meituan_ipad | Tuan/Kingfisher/String+MD5.swift | 8 | 8376 | //
// String+MD5.swift
// WebImageDemo
//
// Created by Wei Wang on 15/4/6.
// Copyright (c) 2015年 Wei Wang. All rights reserved.
//
// This file is stolen from HanekeSwift: https://github.com/Haneke/HanekeSwift/blob/master/Haneke/CryptoSwiftMD5.swift
// which is a modified version of CryptoSwift:
//
// To date, adding CommonCrypto to a Swift framework is problematic. See:
// http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework
// We're using a subset of CryptoSwift as a (temporary?) alternative.
// The following is an altered source version that only includes MD5. The original software can be found at:
// https://github.com/krzyzanowskim/CryptoSwift
// This is the original copyright notice:
/*
Copyright (C) 2014 Marcin Krzyżanowski <[email protected]>
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:
- 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 is required.
- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
- This notice may not be removed or altered from any source or binary distribution.
*/
import Foundation
extension String {
func kf_MD5() -> String {
if let data = self.dataUsingEncoding(NSUTF8StringEncoding) {
let MD5Calculator = MD5(data)
let MD5Data = MD5Calculator.calculate()
let resultBytes = UnsafeMutablePointer<CUnsignedChar>(MD5Data.bytes)
let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.length)
var MD5String = ""
for c in resultEnumerator {
MD5String += String(format: "%02x", c)
}
return MD5String
} else {
return self
}
}
}
/** array of bytes, little-endian representation */
func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] {
let totalBytes = length ?? (sizeofValue(value) * 8)
var v = value
var valuePointer = UnsafeMutablePointer<T>.alloc(1)
valuePointer.memory = value
var bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer)
var bytes = [UInt8](count: totalBytes, repeatedValue: 0)
for j in 0..<min(sizeof(T),totalBytes) {
bytes[totalBytes - 1 - j] = (bytesPointer + j).memory
}
valuePointer.destroy()
valuePointer.dealloc(1)
return bytes
}
extension Int {
/** Array of bytes with optional padding (little-endian) */
func bytes(_ totalBytes: Int = sizeof(Int)) -> [UInt8] {
return arrayOfBytes(self, length: totalBytes)
}
}
extension NSMutableData {
/** Convenient way to append bytes */
func appendBytes(arrayOfBytes: [UInt8]) {
self.appendBytes(arrayOfBytes, length: arrayOfBytes.count)
}
}
class HashBase {
var message: NSData
init(_ message: NSData) {
self.message = message
}
/** Common part for hash calculation. Prepare header data. */
func prepare(_ len:Int = 64) -> NSMutableData {
var tmpMessage: NSMutableData = NSMutableData(data: self.message)
// Step 1. Append Padding Bits
tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
var msgLength = tmpMessage.length;
var counter = 0;
while msgLength % len != (len - 8) {
counter++
msgLength++
}
var bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8)))
tmpMessage.appendBytes(bufZeros, length: counter)
return tmpMessage
}
}
func rotateLeft(v:UInt32, n:UInt32) -> UInt32 {
return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
}
class MD5 : HashBase {
/** specifies the per-round shift amounts */
private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let k: [UInt32] = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,
0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,
0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,
0x6b901122,0xfd987193,0xa679438e,0x49b40821,
0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,
0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8,
0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,
0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,
0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,
0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,
0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05,
0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,
0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,
0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,
0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,
0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391]
private let h:[UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
func calculate() -> NSData {
var tmpMessage = prepare()
// hash values
var hh = h
// Step 2. Append Length a 64-bit representation of lengthInBits
var lengthInBits = (message.length * 8)
var lengthBytes = lengthInBits.bytes(64 / 8)
tmpMessage.appendBytes(reverse(lengthBytes));
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
var leftMessageBytes = tmpMessage.length
for (var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes) {
let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
let bytes = tmpMessage.bytes;
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0)
let range = NSRange(location:0, length: M.count * sizeof(UInt32))
chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range)
// Initialize hash value for this chunk:
var A:UInt32 = hh[0]
var B:UInt32 = hh[1]
var C:UInt32 = hh[2]
var D:UInt32 = hh[3]
var dTemp:UInt32 = 0
// Main loop
for j in 0..<k.count {
var g = 0
var F:UInt32 = 0
switch (j) {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), s[j])
A = dTemp
}
hh[0] = hh[0] &+ A
hh[1] = hh[1] &+ B
hh[2] = hh[2] &+ C
hh[3] = hh[3] &+ D
}
var buf: NSMutableData = NSMutableData();
hh.map({ (item) -> () in
var i:UInt32 = item.littleEndian
buf.appendBytes(&i, length: sizeofValue(i))
})
return buf.copy() as! NSData;
}
} | mit | 859a0e879aa08335c7427f1a25e243ff | 36.524664 | 213 | 0.582885 | 3.668128 | false | false | false | false |
KanChen2015/DRCRegistrationKit | DRCRegistrationKit/DRCRegistrationKit/DRRSignUpViewModel.swift | 1 | 4480 | //
// DRRSignUpViewModel.swift
// DRCRegistrationKit
//
// Created by Kan Chen on 6/8/16.
// Copyright © 2016 drchrono. All rights reserved.
//
import Foundation
internal let kDRRSignupFullNameKey = "name"
internal let kDRRSignupFirstNameKey = "firstName"
internal let kDRRSignupLastNameKey = "lastName"
internal let kDRRSignupEmailKey = "email"
internal let kDRRSignupPhoneKey = "office_phone"
internal let kDRRSignupSessionKey = "signup_session"
//step 2
internal let kDRRSignupStateKey = "state"
internal let kDRRSignupSpecialtyKey = "specialty"
internal let kDRRSignupJobTitleKey = "job_title"
//step 3
internal let kDRRSignupUsernameKey = "username"
internal let kDRRSignupPasswordKey = "password"
internal let kDRRSignupPasswordConfirmKey = "password_confirm"
internal let kDRRSignupTermsConfirmedKey = "terms_of_service_agreement"
//#define kDRCSignupBillingKey @"billing"
//#define kDRCSignupProvidersKey @"providers"
//#define kDRCSignupTermsKey @""
//#define kPracticeSizeDisplays @[@"Just Me", @"2 to 5", @"6 to 10", @"10+"]
//#define kBillingTypeDisplays @[@"Insurance", @"Cash-based"]
final class DRRSignUpViewModel {
typealias signupStepComplete = (success: Bool, errorMsg: String?) -> Void
var delegate: DRCRegistrationNetworkingDelegate? = DelegateProvider.shared.networkingDelegate
var stateChoices: [String] = []
var jobTitleChoices: [String] = []
var specialtyChoices: [String] = []
private var signupSession: String = ""
var registeredUsername: String = ""
var registeredPassword: String = ""
func signupStep1WithInfo(info: [String: AnyObject], complete: signupStepComplete) {
delegate?.attemptSignupStep1RequestWithInfo(info, complete: { (json, error) in
if let error = error {
complete(success: false, errorMsg: error.localizedDescription)
return
}
if let success = json["success"] as? Bool where success {
self.signupSession = json[kDRRSignupSessionKey] as? String ?? ""
self.stateChoices = json["state_choices"] as? [String] ?? []
self.jobTitleChoices = json["job_title_choices"] as? [String] ?? []
self.specialtyChoices = json["specialty_choices"] as? [String] ?? []
complete(success: true, errorMsg: nil)
} else {
complete(success: false, errorMsg: json["errors"] as? String)
}
})
}
func signupStep2WithInfo(info: [String: AnyObject], complete: signupStepComplete) {
var finalInfo = info
finalInfo[kDRRSignupSessionKey] = signupSession
delegate?.attemptSignupStep2RequestWithInfo(finalInfo, complete: { (json, error) in
if let error = error {
complete(success: false, errorMsg: error.localizedDescription)
return
}
if let success = json["success"] as? Bool where success {
complete(success: true, errorMsg: nil)
} else {
complete(success: false, errorMsg: json["errors"] as? String)
}
})
}
func signupStep3WithInfo(info: [String: AnyObject], complete: signupStepComplete) {
var finalInfo = info
finalInfo[kDRRSignupSessionKey] = signupSession
//TODO: does this is required by our backend?
finalInfo[kDRRSignupTermsConfirmedKey] = true
delegate?.attemptSignupStep3RequestWithInfo(finalInfo, complete: { (json, error) in
if let error = error {
complete(success: false, errorMsg: error.localizedDescription)
return
}
if let success = json["success"] as? Bool where success {
guard let
registeredUsername = json["username"] as? String,
registeredPassword = json["password"] as? String
where !registeredUsername.isEmpty && !registeredPassword.isEmpty else {
complete(success: false, errorMsg: "An unknown error happened, please try again later")
return
}
self.registeredUsername = registeredUsername
self.registeredPassword = registeredPassword
//TODO: PIN Manager
complete(success: true, errorMsg: nil)
} else {
complete(success: false, errorMsg: json["errors"] as? String)
}
})
}
}
| mit | f93cf6565c4a62bb7199fc59fe79ec34 | 42.485437 | 107 | 0.636973 | 4.729673 | false | false | false | false |
february29/Learning | swift/Fch_Contact/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift | 15 | 3526 | //
// RxCollectionViewReactiveArrayDataSource.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
// objc monkey business
class _RxCollectionViewReactiveArrayDataSource
: NSObject
, UICollectionViewDataSource {
@objc(numberOfSectionsInCollectionView:)
func numberOfSections(in: UICollectionView) -> Int {
return 1
}
func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 0
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return _collectionView(collectionView, numberOfItemsInSection: section)
}
fileprivate func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
rxAbstractMethod()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return _collectionView(collectionView, cellForItemAt: indexPath)
}
}
class RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S: Sequence>
: RxCollectionViewReactiveArrayDataSource<S.Iterator.Element>
, RxCollectionViewDataSourceType {
typealias Element = S
override init(cellFactory: @escaping CellFactory) {
super.init(cellFactory: cellFactory)
}
func collectionView(_ collectionView: UICollectionView, observedEvent: Event<S>) {
Binder(self) { collectionViewDataSource, sectionModels in
let sections = Array(sectionModels)
collectionViewDataSource.collectionView(collectionView, observedElements: sections)
}.on(observedEvent)
}
}
// Please take a look at `DelegateProxyType.swift`
class RxCollectionViewReactiveArrayDataSource<Element>
: _RxCollectionViewReactiveArrayDataSource
, SectionedViewDataSourceType {
typealias CellFactory = (UICollectionView, Int, Element) -> UICollectionViewCell
var itemModels: [Element]? = nil
func modelAtIndex(_ index: Int) -> Element? {
return itemModels?[index]
}
func model(at indexPath: IndexPath) throws -> Any {
precondition(indexPath.section == 0)
guard let item = itemModels?[indexPath.item] else {
throw RxCocoaError.itemsNotYetBound(object: self)
}
return item
}
var cellFactory: CellFactory
init(cellFactory: @escaping CellFactory) {
self.cellFactory = cellFactory
}
// data source
override func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemModels?.count ?? 0
}
override func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return cellFactory(collectionView, indexPath.item, itemModels![indexPath.item])
}
// reactive
func collectionView(_ collectionView: UICollectionView, observedElements: [Element]) {
self.itemModels = observedElements
collectionView.reloadData()
// workaround for http://stackoverflow.com/questions/39867325/ios-10-bug-uicollectionview-received-layout-attributes-for-a-cell-with-an-index
collectionView.collectionViewLayout.invalidateLayout()
}
}
#endif
| mit | 8d488bfe0e72b30e6c3c754c05451a5d | 31.045455 | 149 | 0.708652 | 5.64 | false | false | false | false |
alvaromb/EventBlankApp | EventBlank/EventBlank/ViewControllers/Feed/News/NewsViewController.swift | 1 | 5773 | //
// ViewController.swift
// Twitter_test
//
// Created by Marin Todorov on 6/18/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import UIKit
import Social
import Accounts
import SQLite
import XLPagerTabStrip
class NewsViewController: TweetListViewController {
let newsCtr = NewsController()
let userCtr = UserController()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
observeNotification(kTabItemSelectedNotification, selector: "didTapTabItem:")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
observeNotification(kTabItemSelectedNotification, selector: nil)
}
func didTapTabItem(notification: NSNotification) {
if let index = notification.userInfo?["object"] as? Int where index == EventBlankTabIndex.Feed.rawValue {
mainQueue({
if self.tweets.count > 0 {
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true)
}
})
}
}
// MARK: table view methods
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("TweetCell") as! TweetCell
let row = indexPath.row
let tweet = self.tweets[indexPath.row]
let usersTable = database[UserConfig.tableName]
let user = usersTable.filter(User.idColumn == tweet[Chat.idUser]).first
cell.message.text = tweet[News.news]
cell.timeLabel.text = NSDate(timeIntervalSince1970: Double(tweet[News.created])).relativeTimeToString()
cell.message.selectedRange = NSRange(location: 0, length: 0)
if let attachmentUrlString = tweet[News.imageUrl], let attachmentUrl = NSURL(string: attachmentUrlString) {
cell.attachmentImage.hnk_setImageFromURL(attachmentUrl, placeholder: nil, format: nil, failure: nil, success: {image in
image.asyncToSize(.Fill(cell.attachmentImage.bounds.width, 150), cornerRadius: 5.0, completion: {result in
cell.attachmentImage.image = result
})
})
cell.didTapAttachment = {
PhotoPopupView.showImageWithUrl(attachmentUrl, inView: self.view)
}
cell.attachmentHeight.constant = 148.0
}
if let user = user {
cell.nameLabel.text = user[User.name]
if let imageUrlString = user[User.photoUrl], let imageUrl = NSURL(string: imageUrlString) {
cell.userImage.hnk_setImageFromURL(imageUrl, placeholder: UIImage(named: "feed-item"), format: nil, failure: nil, success: {image in
image.asyncToSize(.FillSize(cell.userImage.bounds.size), cornerRadius: 5.0, completion: {result in
cell.userImage.image = result
})
})
}
}
cell.didTapURL = {tappedUrl in
if tappedUrl.absoluteString!.hasPrefix("http") {
let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController
webVC.initialURL = tappedUrl
self.navigationController!.pushViewController(webVC, animated: true)
} else {
UIApplication.sharedApplication().openURL(tappedUrl)
}
}
return cell
}
// MARK: load/fetch data
override func loadTweets() {
//fetch latest tweets from db
let latestText = tweets.first?[News.news]
tweets = self.newsCtr.allNews()
lastRefresh = NSDate().timeIntervalSince1970
if latestText == tweets.first?[News.news] {
//latest tweet is the same, bail
return;
}
//reload table
mainQueue {
self.tableView.reloadData()
if self.tweets.count == 0 {
self.tableView.addSubview(MessageView(text: "No tweets found at this time, try again later"))
} else {
MessageView.removeViewFrom(self.tableView)
}
}
}
override func fetchTweets() {
twitter.authorize({success in
MessageView.removeViewFrom(self.tableView)
if success {
self.twitter.getTimeLineForUsername(Event.event[Event.twitterAdmin]!, completion: {tweetList, user in
if let user = user where tweetList.count > 0 {
self.userCtr.persistUsers([user])
self.newsCtr.persistNews(tweetList)
self.loadTweets()
}
})
} else {
delay(seconds: 0.5, {
self.tableView.addSubview(
//show a message + button to settings
MessageView(text: "You don't have Twitter accounts set up. Open Settings app, select Twitter and connect an account. \n\nThen pull this view down to refresh the feed."
//TODO: add the special iOS9 settings links later
// ,buttonTitle: "Open Settings App",
// buttonTap: {
// UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
// }
))
})
}
mainQueue { self.refreshView.endRefreshing() }
})
}
}
| mit | b38dcae1c8fd8f9052e978807471c5b6 | 38.006757 | 191 | 0.587563 | 5.281793 | false | false | false | false |
prolificinteractive/simcoe | Simcoe/mParticle/MPProduct+Simcoe.swift | 1 | 1806 | //
// MPProduct+Simcoe.swift
// Simcoe
//
// Created by Michael Campbell on 10/25/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
import mParticle_Apple_SDK
extension MPProduct {
/// A convenience initializer.
///
/// - Parameter product: A SimcoeProductConvertible instance.
internal convenience init(product: SimcoeProductConvertible) {
let simcoeProduct = product.toSimcoeProduct()
self.init(name: simcoeProduct.productName,
// INTENTIONAL: In MPProduct: SKU of a product. This is the product id
sku: simcoeProduct.productId,
quantity: NSNumber(value: simcoeProduct.quantity),
price: NSNumber(value: simcoeProduct.price ?? 0))
guard let properties = simcoeProduct.properties else {
return
}
if let brand = properties[MPProductKeys.brand.rawValue] as? String {
self.brand = brand
}
if let category = properties[MPProductKeys.category.rawValue] as? String {
self.category = category
}
if let couponCode = properties[MPProductKeys.couponCode.rawValue] as? String {
self.couponCode = couponCode
}
if let sku = properties[MPProductKeys.sku.rawValue] as? String {
// INTENTIONAL: In MPProduct: The variant of the product
self.variant = sku
}
if let position = properties[MPProductKeys.position.rawValue] as? UInt {
self.position = position
}
let remaining = MPProductKeys.remaining(properties: properties)
for (key, value) in remaining {
if let value = value as? String {
self[key] = value
}
}
}
}
| mit | fb76c973217ab53c1cea6ed41a9cad8b | 30.12069 | 88 | 0.603324 | 4.813333 | false | false | false | false |
gouyz/GYZBaking | baking/Classes/Home/View/GYZHomeCell.swift | 1 | 9238 | //
// GYZHomeCell.swift
// baking
//
// Created by gouyz on 2017/3/24.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
protocol HomeCellDelegate : NSObjectProtocol {
func didSelectIndex(index : Int)
}
class GYZHomeCell: UITableViewCell {
var delegate: HomeCellDelegate?
/// 填充数据
var dataModel : GYZHomeModel?{
didSet{
if let model = dataModel {
//设置数据
for item in model.img! {
if item.id == "1" {
hotLab.text = item.title
hotdesLab.text = item.sub_title
hotImgView.kf.setImage(with: URL.init(string: item.img!), placeholder: UIImage.init(named: "icon_hot_default"), options: nil, progressBlock: nil, completionHandler: nil)
}else if item.id == "2" {
newLab.text = item.title
newDesLab.text = item.sub_title
topImgView.kf.setImage(with: URL.init(string: item.img!), placeholder: UIImage.init(named: "icon_home_default"), options: nil, progressBlock: nil, completionHandler: nil)
}else if item.id == "3" {
goodLab.text = item.title
goodDesLab.text = item.sub_title
bottomImgView.kf.setImage(with: URL.init(string: item.img!), placeholder: UIImage.init(named: "icon_home_default"), options: nil, progressBlock: nil, completionHandler: nil)
}
}
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?){
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI(){
contentView.addSubview(leftView)
leftView.addSubview(hotLab)
leftView.addSubview(hotTagImgView)
leftView.addSubview(hotdesLab)
leftView.addSubview(hotImgView)
contentView.addSubview(lineView1)
contentView.addSubview(rightTopView)
rightTopView.addSubview(newLab)
rightTopView.addSubview(newDesLab)
rightTopView.addSubview(topImgView)
contentView.addSubview(lineView2)
contentView.addSubview(rightBottomView)
rightBottomView.addSubview(goodLab)
rightBottomView.addSubview(goodDesLab)
rightBottomView.addSubview(bottomImgView)
leftView.snp.makeConstraints { (make) in
make.top.bottom.left.equalTo(contentView)
make.width.equalTo(rightTopView)
make.right.equalTo(lineView1.snp.left)
}
hotLab.snp.makeConstraints { (make) in
make.top.equalTo(leftView).offset(kMargin)
make.left.equalTo(leftView).offset(kMargin)
make.size.equalTo(CGSize.init(width: 70, height: 20))
}
hotTagImgView.snp.makeConstraints { (make) in
make.top.equalTo(hotLab)
make.left.equalTo(hotLab.snp.right)
make.size.equalTo(CGSize.init(width: 28, height: 15))
}
hotdesLab.snp.makeConstraints { (make) in
make.left.equalTo(hotLab)
make.right.equalTo(leftView).offset(-kMargin)
make.top.equalTo(hotLab.snp.bottom)
make.height.equalTo(20)
}
hotImgView.snp.makeConstraints { (make) in
make.left.right.equalTo(hotdesLab)
make.top.equalTo(hotdesLab.snp.bottom).offset(5)
make.bottom.equalTo(leftView).offset(-5)
}
lineView1.snp.makeConstraints { (make) in
make.top.bottom.equalTo(contentView)
make.left.equalTo(leftView.snp.right)
make.width.equalTo(klineWidth)
}
rightTopView.snp.makeConstraints { (make) in
make.top.right.equalTo(contentView)
make.left.equalTo(lineView1.snp.right)
make.bottom.equalTo(lineView2.snp.top)
make.height.equalTo(rightBottomView)
make.width.equalTo(leftView)
}
newLab.snp.makeConstraints { (make) in
make.left.equalTo(rightTopView).offset(kMargin)
make.top.equalTo(rightTopView).offset(15)
make.right.equalTo(topImgView.snp.left).offset(-5)
make.height.equalTo(20)
}
newDesLab.snp.makeConstraints { (make) in
make.left.right.equalTo(newLab)
make.top.equalTo(newLab.snp.bottom)
make.height.equalTo(20)
}
topImgView.snp.makeConstraints { (make) in
make.right.equalTo(rightTopView).offset(-kMargin)
make.centerY.equalTo(rightTopView)
make.size.equalTo(CGSize.init(width: 50, height: 50))
}
lineView2.snp.makeConstraints { (make) in
make.left.right.equalTo(rightTopView)
make.top.equalTo(rightTopView.snp.bottom)
make.height.equalTo(klineWidth)
}
rightBottomView.snp.makeConstraints { (make) in
make.bottom.right.equalTo(contentView)
make.left.equalTo(rightTopView)
make.top.equalTo(lineView2.snp.bottom)
make.height.equalTo(rightTopView)
}
goodLab.snp.makeConstraints { (make) in
make.left.equalTo(rightBottomView).offset(kMargin)
make.top.equalTo(rightBottomView).offset(15)
make.right.equalTo(bottomImgView.snp.left).offset(-5)
make.height.equalTo(20)
}
goodDesLab.snp.makeConstraints { (make) in
make.left.right.equalTo(goodLab)
make.top.equalTo(goodLab.snp.bottom)
make.height.equalTo(20)
}
bottomImgView.snp.makeConstraints { (make) in
make.right.equalTo(rightBottomView).offset(-kMargin)
make.centerY.equalTo(rightBottomView)
make.size.equalTo(CGSize.init(width: 50, height: 50))
}
}
fileprivate lazy var leftView: UIView = {
let view = UIView()
view.tag = 101
view.addOnClickListener(target: self, action: #selector(menuViewClick(sender : )))
return view
}()
fileprivate lazy var rightTopView: UIView = {
let view = UIView()
view.tag = 102
view.addOnClickListener(target: self, action: #selector(menuViewClick(sender : )))
return view
}()
fileprivate lazy var rightBottomView: UIView = {
let view = UIView()
view.tag = 103
view.addOnClickListener(target: self, action: #selector(menuViewClick(sender : )))
return view
}()
///热门标题
lazy var hotLab: UILabel = {
let lab = UILabel()
lab.font = k15Font
lab.textColor = kBlackFontColor
return lab
}()
///热门hot图片标志
lazy var hotTagImgView: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_hot_tag"))
///热门描述
lazy var hotdesLab: UILabel = {
let lab = UILabel()
lab.font = k12Font
lab.textColor = kRedFontColor
return lab
}()
///热门hot图片
lazy var hotImgView: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_hot_default"))
fileprivate lazy var lineView1 : UIView = {
let line = UIView()
line.backgroundColor = kGrayLineColor
return line
}()
///新店推荐标题
lazy var newLab: UILabel = {
let lab = UILabel()
lab.font = k15Font
lab.textColor = kBlackFontColor
return lab
}()
///新店推荐图片
lazy var topImgView: UIImageView = {
let imgView = UIImageView.init(image: UIImage.init(named: "icon_home_business"))
imgView.cornerRadius = 25
return imgView
}()
///新店推荐描述
lazy var newDesLab: UILabel = {
let lab = UILabel()
lab.font = k12Font
lab.textColor = kGaryFontColor
return lab
}()
fileprivate lazy var lineView2 : UIView = {
let line = UIView()
line.backgroundColor = kGrayLineColor
return line
}()
///每日好店标题
lazy var goodLab: UILabel = {
let lab = UILabel()
lab.font = k15Font
lab.textColor = kBlackFontColor
return lab
}()
///每日好店图片
lazy var bottomImgView: UIImageView = {
let imgView = UIImageView.init(image: UIImage.init(named: "icon_home_business"))
imgView.cornerRadius = 25
return imgView
}()
///新店推荐描述
lazy var goodDesLab: UILabel = {
let lab = UILabel()
lab.font = k12Font
lab.textColor = kGaryFontColor
return lab
}()
///点击事件
func menuViewClick(sender : UITapGestureRecognizer){
let tag = sender.view?.tag
delegate?.didSelectIndex(index: tag! - 100)
}
}
| mit | c265365ee7f208cb5325fd9e2580de7e | 32.466912 | 197 | 0.580248 | 4.519861 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/Demo/Modules/Common/Utils/UIImage+Effects.swift | 1 | 8516 | //
// UIImage+Effects.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/13.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
import Accelerate
extension UIImage {
func applyLightEffect() -> UIImage? {
return applyBlurWithRadius(30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8)
}
func applyExtraLightEffect() -> UIImage? {
return applyBlurWithRadius(20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8)
}
func applyDarkEffect() -> UIImage? {
return applyBlurWithRadius(20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8)
}
func applyTintEffectWithColor(_ tintColor: UIColor) -> UIImage? {
let effectColorAlpha: CGFloat = 0.6
var effectColor = tintColor
let componentCount = tintColor.cgColor.numberOfComponents
if componentCount == 2 {
var b: CGFloat = 0
if tintColor.getWhite(&b, alpha: nil) {
effectColor = UIColor(white: b, alpha: effectColorAlpha)
}
} else {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) {
effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha)
}
}
return applyBlurWithRadius(10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil)
}
func applyBlurWithRadius(_ blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? {
// Check pre-conditions.
if (size.width < 1 || size.height < 1) {
print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)")
return nil
}
if self.cgImage == nil {
print("*** error: image must be backed by a CGImage: \(self)")
return nil
}
if maskImage != nil && maskImage!.cgImage == nil {
print("*** error: maskImage must be backed by a CGImage: \(String(describing: maskImage))")
return nil
}
let __FLT_EPSILON__ = CGFloat(Float.ulpOfOne)
let screenScale = UIScreen.main.scale
let imageRect = CGRect(origin: CGPoint.zero, size: size)
var effectImage = self
let hasBlur = blurRadius > __FLT_EPSILON__
let hasSaturationChange = abs(saturationDeltaFactor - 1.0) > __FLT_EPSILON__
if hasBlur || hasSaturationChange {
func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
let data = context.data
let width = UInt(context.width)
let height = UInt(context.height)
let rowBytes = context.bytesPerRow
return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
}
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let effectInContext = UIGraphicsGetCurrentContext()
effectInContext?.scaleBy(x: 1.0, y: -1.0)
effectInContext?.translateBy(x: 0, y: -size.height)
effectInContext?.draw(self.cgImage!, in: imageRect)
var effectInBuffer = createEffectBuffer(effectInContext!)
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let effectOutContext = UIGraphicsGetCurrentContext()
var effectOutBuffer = createEffectBuffer(effectOutContext!)
if hasBlur {
// A description of how to compute the box kernel width from the Gaussian
// radius (aka standard deviation) appears in the SVG spec:
// http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
//
// For larger values of 's' (s >= 2.0), an approximation can be used: Three
// successive box-blurs build a piece-wise quadratic convolution kernel, which
// approximates the Gaussian kernel to within roughly 3%.
//
// let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
//
// ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
//
let inputRadius = blurRadius * screenScale
let tmp = inputRadius * 3.0 * CGFloat(sqrt(2 * Double.pi)) / 4 + 0.5
var radius = UInt32(floor(tmp))
if radius % 2 != 1 {
radius += 1 // force radius to be odd so that the three box-blur methodology works.
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s: CGFloat = saturationDeltaFactor
let floatingPointSaturationMatrix: [CGFloat] = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
]
let divisor: CGFloat = 256
let matrixSize = floatingPointSaturationMatrix.count
var saturationMatrix = [Int16](repeating: 0, count: matrixSize)
for i: Int in 0 ..< matrixSize {
saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor))
}
if hasBlur {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
effectImageBuffersAreSwapped = true
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
}
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
if effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
}
// Set up output context.
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let outputContext = UIGraphicsGetCurrentContext()
outputContext?.scaleBy(x: 1.0, y: -1.0)
outputContext?.translateBy(x: 0, y: -size.height)
// Draw base image.
outputContext?.draw(self.cgImage!, in: imageRect)
// Draw effect image.
if hasBlur {
outputContext?.saveGState()
if let image = maskImage {
outputContext?.clip(to: imageRect, mask: image.cgImage!);
}
outputContext?.draw(effectImage.cgImage!, in: imageRect)
outputContext?.restoreGState()
}
// Add in color tint.
if let color = tintColor {
outputContext?.saveGState()
outputContext?.setFillColor(color.cgColor)
outputContext?.fill(imageRect)
outputContext?.restoreGState()
}
// Output image is ready.
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
}
| mit | d6e55a693b7aa7e31dcf7730ddf8c3cd | 41.748744 | 158 | 0.55519 | 5.274024 | false | false | false | false |
AdAdaptive/adadaptive-ios-pod | AdAdaptive/Classes/AdAdaptiveDeviceData.swift | 1 | 18944 | //
// AdAdaptiveDeviceData.swift
// AdAdaptiveFramework
//
/**************************************************************************************************************************
*
* SystemicsCode Nordic AB
*
**************************************************************************************************************************/
import Foundation
import CoreLocation
import AdSupport
import CoreTelephony
import SystemConfiguration
import UIKit
class AdAdaptiveDeviceData {
// device[geo]
fileprivate var lat: CLLocationDegrees! // Latitude from -90.0 to +90.0, where negative is south.
fileprivate var lon: CLLocationDegrees! // Longitude from -180.0 to +180.0, where negative is west.
fileprivate var ttype: Int = 1 // Source of location data; recommended when passing lat/lon
// 1 = GPS/Location Services
// 2 = IP Address
// 3 = User provided (e.g., registration data)
// 4 = Cell-ID Location Service (e.g Combain) - not standard(added for skylab)
// 5 = Indoor positioning system - not standard(added for skylab)
fileprivate var country: String? = nil // Country code using ISO-3166-1-alpha-3.
fileprivate var region: String? = nil // Region code using ISO-3166-2; 2-letter state code if USA
fileprivate var city: String? = nil // City Name
fileprivate var zip: String? = nil // Zip or postal code
fileprivate var street: String? = nil // Street name
fileprivate var streetno: String? = nil // Sub Adress or street number: eg. 94-102
// device
fileprivate var lmt: Int = 0 // Limit Ad Tracking” signal commercially endorsed (e.g., iOS, Android), where
// 0 = tracking is unrestricted, 1 = tracking must be limited per commercial guidelines.
fileprivate var idfa: String? = nil // Unique device identifier Advertiser ID
fileprivate var devicetype: Int? = nil // Device type (e.g. 1=Mobile/Tablet, 2=Personal computer, 3=Connected TV, 4=Phone, 5=Tablet, 6=Connected Device, 7=Set Top Box
fileprivate let make: String = "Apple" // Device make
fileprivate var model: String? = nil // Device model (e.g., “iPhone”)
fileprivate var os: String? = "iPhone OS" // Device operating system (e.g., “iOS”)
fileprivate var osv: String? = nil // Device operating system version (e.g., “9.3.2”).
fileprivate var hwv: String? = nil // Hardware version of the device (e.g., “5S” for iPhone 5S, "qcom" for Android).
fileprivate var h: CGFloat = 0.0 // Physical height of the screen in pixels
fileprivate var w: CGFloat = 0.0 // Physical width of the screen in pixels.
fileprivate var ppi: CGFloat? = nil // Screen size as pixels per linear inch.
fileprivate var pxratio: CGFloat? = nil // The ratio of physical pixels to device independent pixels. For all devices that do not have Retina Displays this will return a 1.0f,
// while Retina Display devices will give a 2.0f and the iPhone 6 Plus (Retina HD) will give a 3.0f.
fileprivate var language: String? = nil // Display Language ISO-639-1-alpha-2
fileprivate var carrier: String? = nil // Carrier or ISP (e.g., “VERIZON”)
fileprivate var connectiontype: Int = 0 // Network connection type:
//0=Unknown; 1=Ethernet; 2=WIFI; 3=Cellular Network – Unknown Generation; 4=Cellular Network – 2G; 5=Cellular Network – 3G; 6=Cellular Network – 4G
fileprivate var publisher_id: String? = nil
fileprivate var app_id: String? = nil
// micello
// Mocello Indoor Map related data
fileprivate var level_id: Int? = nil // The Micello map level id
// user
// user data is stored persistently using the NSUserDaults
fileprivate let userData = UserDefaults.standard
fileprivate let DEFAULT_TIMER: UInt64 = 10 // 10 sec default time for timed ad delivery
//***********************************************************************************************************************************/
// Init functions
//***********************************************************************************************************************************/
init(){
let screenBounds: CGRect = UIScreen.main.bounds
h = screenBounds.height
w = screenBounds.width
let pxratio: CGFloat = UIScreen.main.scale
ppi = pxratio * 160
// country = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String
// print("Country = \(country)")
// Check if Advertising Tracking is Enabled
if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
lmt = 0
//debugPrint("IDFA = \(idfa)")
} else {
lmt = 1
idfa = nil
}
model = UIDevice.current.model
if (model == "iPad") {
devicetype = 5
}
if (model == "iPhone"){
devicetype = 4
}
os = UIDevice.current.systemName
osv = UIDevice.current.systemVersion
hwv = getDeviceHardwareVersion()
language = Locale.preferredLanguages[0]
carrier = CTTelephonyNetworkInfo().subscriberCellularProvider?.carrierName
if (!isConnectedToNetwork()){
debugPrint("AdADaptive Info: Not Connected to the Network")
}
}
//***********************************************************************************************************************************/
// User Data Set functions
//***********************************************************************************************************************************/
func setUserDataYob(_ yob: Int){ // Year of birth as a 4-digit integer
userData.set(yob, forKey: "yob")
userData.synchronize()
}
func setUserDataGender(_ gender: String){ // Gender, where “M” = male, “F” = female, “O” = known to be other
userData.setValue(gender, forKey: "gender")
userData.synchronize()
}
func setADTimer(_ time: UInt64){
// Wrap the UInt64 in an NSNumber as store the NSNumber in NSUserDefaults
// NSNumber.init(unsignedLongLong: time)
userData.set(NSNumber(value: time as UInt64), forKey: "adtimer")
userData.synchronize()
}
func getADTimer() -> UInt64{
if userData.object(forKey: "adtimer") != nil {
let time_sec: NSNumber! = userData.value(forKey: "adtimer") as! NSNumber
//cast the returned value to an UInt64
guard let return_time = time_sec else {
return DEFAULT_TIMER // deafualt 60.0 sec
}
return return_time.uint64Value
}
else{
return DEFAULT_TIMER // default 60.0 sec
}
}
func setIndoorMapLevelID(_ level_id: Int){
self.level_id = level_id
}
func setPublisherID(publisherID: String){
self.publisher_id = publisherID
}
func setAppID(appID: String){
self.app_id = appID
}
//***********************************************************************************************************************************/
// Utility functions
//***********************************************************************************************************************************/
fileprivate func getDeviceHardwareVersion() -> String {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8 , value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
switch identifier {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return "iPad Pro"
case "AppleTV5,3": return "Apple TV"
case "i386", "x86_64": return "Simulator"
default: return identifier
}
}//String
return modelName
}
//----------------------------------------------------------------------------------------------------------------------------------//
fileprivate func isConnectedToNetwork() -> Bool {
// Network connection type: 0=Unknown; 1=Ethernet; 2=WIFI; 3=Cellular Network – Unknown Generation; 4=Cellular Network – 2G; 5=Cellular Network – 3G; 6=Cellular Network – 4G
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}) else {
return false
}
var flags : SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
let isNetworkReachable = (isReachable && !needsConnection)
if (isNetworkReachable) {
if (flags.contains(SCNetworkReachabilityFlags.isWWAN)) {
let carrierType = CTTelephonyNetworkInfo().currentRadioAccessTechnology
switch carrierType{
case CTRadioAccessTechnologyGPRS?,CTRadioAccessTechnologyEdge?,CTRadioAccessTechnologyCDMA1x?:
debugPrint("AdADaptive Info: Connection Type: = 2G")
connectiontype = 4
case CTRadioAccessTechnologyWCDMA?,CTRadioAccessTechnologyHSDPA?,CTRadioAccessTechnologyHSUPA?,CTRadioAccessTechnologyCDMAEVDORev0?,CTRadioAccessTechnologyCDMAEVDORevA?,CTRadioAccessTechnologyCDMAEVDORevB?,CTRadioAccessTechnologyeHRPD?:
debugPrint("AdADaptive Info: Connection Type: = 3G")
connectiontype = 5
case CTRadioAccessTechnologyLTE?:
debugPrint("AdADaptive Info: Connection Type: = 4G")
connectiontype = 6
default:
debugPrint("AdADaptive Info: Connection Type: = Unknown Generation")
connectiontype = 3
}//switch
} else {
debugPrint("AdADaptive Info: Connection Type: WIFI")
connectiontype = 2
}
}//if
return isNetworkReachable
}//connectedToNetwork()
//***********************************************************************************************************************************/
// Get functions
//***********************************************************************************************************************************/
func getDeviceParameters(_ location: CLLocation, completion:@escaping (_ result: [String: AnyObject])->Void){
var device_parameters: [String: AnyObject] = [:]
lat = location.coordinate.latitude
lon = location.coordinate.longitude
//finding the user adress by using reverse geocodding
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location, completionHandler: {(placemarks, error)->Void in
var placemark:CLPlacemark!
if error == nil && placemarks!.count > 0 {
placemark = placemarks![0] as CLPlacemark
self.streetno = placemark.subThoroughfare
self.street = placemark.thoroughfare
self.zip = placemark.postalCode
self.city = placemark.locality
self.region = placemark.administrativeArea
self.country = placemark.country
} //if
device_parameters = self.getDeviceParametersFormat()
completion(device_parameters)
}) // geocoder.reverseGeocodeLocation
}
//----------------------------------------------------------------------------------------------------------------------------------//
func getDeviceParameters(completion:@escaping (_ result: [String: AnyObject])->Void){
var device_parameters: [String: AnyObject] = [:]
device_parameters = self.getDeviceParametersFormat()
completion(device_parameters)
}
//----------------------------------------------------------------------------------------------------------------------------------//
func getDeviceWidth()->CGFloat{
return w
}
//----------------------------------------------------------------------------------------------------------------------------------//
// format the device parametrs that it can be passed as parameter to an Alamofire call
func getDeviceParametersFormat()->[String: AnyObject]{
var parameters: [String: AnyObject] = [:]
if self.publisher_id != nil { parameters["publisher[pid]"] = self.publisher_id as AnyObject? }
if self.app_id != nil { parameters["publisher[appid]"] = self.app_id as AnyObject? }
if self.lat != nil { parameters["device[geo][lat]"] = self.lat as AnyObject? }
if self.lon != nil { parameters["device[geo][lon]"] = self.lon as AnyObject? }
if self.country != nil { parameters["device[geo][country]"] = self.country as AnyObject? }
if self.region != nil { parameters["device[geo][region]"] = self.region as AnyObject? }
if self.city != nil { parameters["device[geo][city]"] = self.city as AnyObject? }
if self.zip != nil { parameters["device[geo][zip]"] = self.zip as AnyObject? }
if self.streetno != nil { parameters["device[geo][streetno]"] = self.streetno as AnyObject? }
if self.street != nil { parameters["device[geo][street]"] = self.street as AnyObject? }
parameters["device[lmt]"] = self.lmt as AnyObject?
if lmt == 0 {
if self.idfa != nil { parameters["device[idfa]"] = self.idfa as AnyObject? }
}
if self.model != nil { parameters["device[model]"] = self.model as AnyObject? }
if self.os != nil { parameters["device[os]"] = self.os as AnyObject? }
if self.osv != nil { parameters["device[osv]"] = self.osv as AnyObject? }
if self.hwv != nil { parameters["device[hwv]"] = self.hwv as AnyObject? }
parameters["device[h]"] = self.h as AnyObject?
parameters["device[w]"] = self.w as AnyObject?
if self.ppi != nil { parameters["device[ppi]"] = self.ppi as AnyObject? }
if self.pxratio != nil { parameters["device[pxratio]"] = self.pxratio as AnyObject? }
if self.language != nil { parameters["device[language]"] = self.language as AnyObject? }
if self.carrier != nil { parameters["device[carrier]"] = self.carrier as AnyObject? }
parameters["device[connectiontype]"] = self.connectiontype as AnyObject?
if userData.object(forKey: "yob") != nil {
parameters["user[yob]"] = userData.integer(forKey: "yob") as AnyObject?
}
if userData.object(forKey: "gender") != nil {
parameters["user[gender]"] = userData.string(forKey: "gender") as AnyObject?
}
if self.level_id != nil {
parameters["micello[level_id]"] = self.level_id as AnyObject?
level_id = nil
}
return parameters
}
}
| mit | 63d2f4fe50b2d0318def2872efb85b32 | 53.606936 | 252 | 0.491267 | 5.239601 | false | false | false | false |
hooman/swift | stdlib/public/core/StringUTF16View.swift | 3 | 22451 | //===--- StringUTF16.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to
// allow performance optimizations of linear traversals.
extension String {
/// A view of a string's contents as a collection of UTF-16 code units.
///
/// You can access a string's view of UTF-16 code units by using its `utf16`
/// property. A string's UTF-16 view encodes the string's Unicode scalar
/// values as 16-bit integers.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.utf16 {
/// print(v)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 55357
/// // 56464
///
/// Unicode scalar values that make up a string's contents can be up to 21
/// bits long. The longer scalar values may need two `UInt16` values for
/// storage. Those "pairs" of code units are called *surrogate pairs*.
///
/// let flowermoji = "💐"
/// for v in flowermoji.unicodeScalars {
/// print(v, v.value)
/// }
/// // 💐 128144
///
/// for v in flowermoji.utf16 {
/// print(v)
/// }
/// // 55357
/// // 56464
///
/// To convert a `String.UTF16View` instance back into a string, use the
/// `String` type's `init(_:)` initializer.
///
/// let favemoji = "My favorite emoji is 🎉"
/// if let i = favemoji.utf16.firstIndex(where: { $0 >= 128 }) {
/// let asciiPrefix = String(favemoji.utf16[..<i])!
/// print(asciiPrefix)
/// }
/// // Prints "My favorite emoji is "
///
/// UTF16View Elements Match NSString Characters
/// ============================================
///
/// The UTF-16 code units of a string's `utf16` view match the elements
/// accessed through indexed `NSString` APIs.
///
/// print(flowers.utf16.count)
/// // Prints "10"
///
/// let nsflowers = flowers as NSString
/// print(nsflowers.length)
/// // Prints "10"
///
/// Unlike `NSString`, however, `String.UTF16View` does not use integer
/// indices. If you need to access a specific position in a UTF-16 view, use
/// Swift's index manipulation methods. The following example accesses the
/// fourth code unit in both the `flowers` and `nsflowers` strings:
///
/// print(nsflowers.character(at: 3))
/// // Prints "119"
///
/// let i = flowers.utf16.index(flowers.utf16.startIndex, offsetBy: 3)
/// print(flowers.utf16[i])
/// // Prints "119"
///
/// Although the Swift overlay updates many Objective-C methods to return
/// native Swift indices and index ranges, some still return instances of
/// `NSRange`. To convert an `NSRange` instance to a range of
/// `String.Index`, use the `Range(_:in:)` initializer, which takes an
/// `NSRange` and a string as arguments.
///
/// let snowy = "❄️ Let it snow! ☃️"
/// let nsrange = NSRange(location: 3, length: 12)
/// if let range = Range(nsrange, in: snowy) {
/// print(snowy[range])
/// }
/// // Prints "Let it snow!"
@frozen
public struct UTF16View: Sendable {
@usableFromInline
internal var _guts: _StringGuts
@inlinable
internal init(_ guts: _StringGuts) {
self._guts = guts
_invariantCheck()
}
}
}
extension String.UTF16View {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
_internalInvariant(
startIndex.transcodedOffset == 0 && endIndex.transcodedOffset == 0)
}
#endif // INTERNAL_CHECKS_ENABLED
}
extension String.UTF16View: BidirectionalCollection {
public typealias Index = String.Index
/// The position of the first code unit if the `String` is
/// nonempty; identical to `endIndex` otherwise.
@inlinable @inline(__always)
public var startIndex: Index { return _guts.startIndex }
/// The "past the end" position---that is, the position one greater than
/// the last valid subscript argument.
///
/// In an empty UTF-16 view, `endIndex` is equal to `startIndex`.
@inlinable @inline(__always)
public var endIndex: Index { return _guts.endIndex }
@inlinable @inline(__always)
public func index(after idx: Index) -> Index {
if _slowPath(_guts.isForeign) { return _foreignIndex(after: idx) }
if _guts.isASCII { return idx.nextEncoded }
// For a BMP scalar (1-3 UTF-8 code units), advance past it. For a non-BMP
// scalar, use a transcoded offset first.
// TODO: If transcoded is 1, can we just skip ahead 4?
let idx = _utf16AlignNativeIndex(idx)
let len = _guts.fastUTF8ScalarLength(startingAt: idx._encodedOffset)
if len == 4 && idx.transcodedOffset == 0 {
return idx.nextTranscoded
}
return idx.strippingTranscoding.encoded(offsetBy: len)._scalarAligned
}
@inlinable @inline(__always)
public func index(before idx: Index) -> Index {
precondition(!idx.isZeroPosition)
if _slowPath(_guts.isForeign) { return _foreignIndex(before: idx) }
if _guts.isASCII { return idx.priorEncoded }
if idx.transcodedOffset != 0 {
_internalInvariant(idx.transcodedOffset == 1)
return idx.strippingTranscoding
}
let idx = _utf16AlignNativeIndex(idx)
let len = _guts.fastUTF8ScalarLength(endingAt: idx._encodedOffset)
if len == 4 {
// 2 UTF-16 code units comprise this scalar; advance to the beginning and
// start mid-scalar transcoding
return idx.encoded(offsetBy: -len).nextTranscoded
}
// Single UTF-16 code unit
_internalInvariant((1...3) ~= len)
return idx.encoded(offsetBy: -len)._scalarAligned
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
if _slowPath(_guts.isForeign) {
return _foreignIndex(i, offsetBy: n)
}
let lowerOffset = _nativeGetOffset(for: i)
let result = _nativeGetIndex(for: lowerOffset + n)
return result
}
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
if _slowPath(_guts.isForeign) {
return _foreignIndex(i, offsetBy: n, limitedBy: limit)
}
let iOffset = _nativeGetOffset(for: i)
let limitOffset = _nativeGetOffset(for: limit)
// If distance < 0, limit has no effect if it is greater than i.
if _slowPath(n < 0 && limit <= i && limitOffset > iOffset + n) {
return nil
}
// If distance > 0, limit has no effect if it is less than i.
if _slowPath(n >= 0 && limit >= i && limitOffset < iOffset + n) {
return nil
}
let result = _nativeGetIndex(for: iOffset + n)
return result
}
public func distance(from start: Index, to end: Index) -> Int {
if _slowPath(_guts.isForeign) {
return _foreignDistance(from: start, to: end)
}
let lower = _nativeGetOffset(for: start)
let upper = _nativeGetOffset(for: end)
return upper &- lower
}
@inlinable
public var count: Int {
if _slowPath(_guts.isForeign) {
return _foreignCount()
}
return _nativeGetOffset(for: endIndex)
}
/// Accesses the code unit at the given position.
///
/// The following example uses the subscript to print the value of a
/// string's first UTF-16 code unit.
///
/// let greeting = "Hello, friend!"
/// let i = greeting.utf16.startIndex
/// print("First character's UTF-16 code unit: \(greeting.utf16[i])")
/// // Prints "First character's UTF-16 code unit: 72"
///
/// - Parameter position: A valid index of the view. `position` must be
/// less than the view's end index.
@inlinable @inline(__always)
public subscript(idx: Index) -> UTF16.CodeUnit {
String(_guts)._boundsCheck(idx)
if _fastPath(_guts.isFastUTF8) {
let scalar = _guts.fastUTF8Scalar(
startingAt: _guts.scalarAlign(idx)._encodedOffset)
return scalar.utf16[idx.transcodedOffset]
}
return _foreignSubscript(position: idx)
}
}
extension String.UTF16View {
@frozen
public struct Iterator: IteratorProtocol, Sendable {
@usableFromInline
internal var _guts: _StringGuts
@usableFromInline
internal var _position: Int = 0
@usableFromInline
internal var _end: Int
// If non-nil, return this value for `next()` (and set it to nil).
//
// This is set when visiting a non-BMP scalar: the leading surrogate is
// returned, this field is set with the value of the trailing surrogate, and
// `_position` is advanced to the start of the next scalar.
@usableFromInline
internal var _nextIsTrailingSurrogate: UInt16? = nil
@inlinable
internal init(_ guts: _StringGuts) {
self._end = guts.count
self._guts = guts
}
@inlinable
public mutating func next() -> UInt16? {
if _slowPath(_nextIsTrailingSurrogate != nil) {
let trailing = self._nextIsTrailingSurrogate._unsafelyUnwrappedUnchecked
self._nextIsTrailingSurrogate = nil
return trailing
}
guard _fastPath(_position < _end) else { return nil }
let (scalar, len) = _guts.errorCorrectedScalar(startingAt: _position)
_position &+= len
if _slowPath(scalar.value > UInt16.max) {
self._nextIsTrailingSurrogate = scalar.utf16[1]
return scalar.utf16[0]
}
return UInt16(truncatingIfNeeded: scalar.value)
}
}
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_guts)
}
}
extension String.UTF16View: CustomStringConvertible {
@inlinable @inline(__always)
public var description: String { return String(_guts) }
}
extension String.UTF16View: CustomDebugStringConvertible {
public var debugDescription: String {
return "StringUTF16(\(self.description.debugDescription))"
}
}
extension String {
/// A UTF-16 encoding of `self`.
@inlinable
public var utf16: UTF16View {
@inline(__always) get { return UTF16View(_guts) }
@inline(__always) set { self = String(newValue._guts) }
}
/// Creates a string corresponding to the given sequence of UTF-16 code units.
@inlinable @inline(__always)
@available(swift, introduced: 4.0)
public init(_ utf16: UTF16View) {
self.init(utf16._guts)
}
}
// Index conversions
extension String.UTF16View.Index {
/// Creates an index in the given UTF-16 view that corresponds exactly to the
/// specified string position.
///
/// If the index passed as `sourcePosition` represents either the start of a
/// Unicode scalar value or the position of a UTF-16 trailing surrogate,
/// then the initializer succeeds. If `sourcePosition` does not have an
/// exact corresponding position in `target`, then the result is `nil`. For
/// example, an attempt to convert the position of a UTF-8 continuation byte
/// results in `nil`.
///
/// The following example finds the position of a space in a string and then
/// converts that position to an index in the string's `utf16` view.
///
/// let cafe = "Café 🍵"
///
/// let stringIndex = cafe.firstIndex(of: "é")!
/// let utf16Index = String.Index(stringIndex, within: cafe.utf16)!
///
/// print(String(cafe.utf16[...utf16Index])!)
/// // Prints "Café"
///
/// - Parameters:
/// - sourcePosition: A position in at least one of the views of the string
/// shared by `target`.
/// - target: The `UTF16View` in which to find the new position.
public init?(
_ idx: String.Index, within target: String.UTF16View
) {
if _slowPath(target._guts.isForeign) {
guard idx._foreignIsWithin(target) else { return nil }
} else {
guard target._guts.isOnUnicodeScalarBoundary(idx) else { return nil }
}
self = idx
}
/// Returns the position in the given view of Unicode scalars that
/// corresponds exactly to this index.
///
/// This index must be a valid index of `String(unicodeScalars).utf16`.
///
/// This example first finds the position of a space (UTF-16 code point `32`)
/// in a string's `utf16` view and then uses this method to find the same
/// position in the string's `unicodeScalars` view.
///
/// let cafe = "Café 🍵"
/// let i = cafe.utf16.firstIndex(of: 32)!
/// let j = i.samePosition(in: cafe.unicodeScalars)!
/// print(String(cafe.unicodeScalars[..<j]))
/// // Prints "Café"
///
/// - Parameter unicodeScalars: The view to use for the index conversion.
/// This index must be a valid index of at least one view of the string
/// shared by `unicodeScalars`.
/// - Returns: The position in `unicodeScalars` that corresponds exactly to
/// this index. If this index does not have an exact corresponding
/// position in `unicodeScalars`, this method returns `nil`. For example,
/// an attempt to convert the position of a UTF-16 trailing surrogate
/// returns `nil`.
public func samePosition(
in unicodeScalars: String.UnicodeScalarView
) -> String.UnicodeScalarIndex? {
return String.UnicodeScalarIndex(self, within: unicodeScalars)
}
}
// Reflection
extension String.UTF16View: CustomReflectable {
/// Returns a mirror that reflects the UTF-16 view of a string.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
// Slicing
extension String.UTF16View {
public typealias SubSequence = Substring.UTF16View
public subscript(r: Range<Index>) -> Substring.UTF16View {
return Substring.UTF16View(self, _bounds: r)
}
}
// Foreign string support
extension String.UTF16View {
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(after i: Index) -> Index {
_internalInvariant(_guts.isForeign)
return i.strippingTranscoding.nextEncoded
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(before i: Index) -> Index {
_internalInvariant(_guts.isForeign)
return i.strippingTranscoding.priorEncoded
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignSubscript(position i: Index) -> UTF16.CodeUnit {
_internalInvariant(_guts.isForeign)
return _guts.foreignErrorCorrectedUTF16CodeUnit(at: i.strippingTranscoding)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignDistance(from start: Index, to end: Index) -> Int {
_internalInvariant(_guts.isForeign)
// Ignore transcoded offsets, i.e. scalar align if-and-only-if from a
// transcoded view
return end._encodedOffset - start._encodedOffset
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
_internalInvariant(_guts.isForeign)
let l = limit._encodedOffset - i._encodedOffset
if n > 0 ? l >= 0 && l < n : l <= 0 && n < l {
return nil
}
return i.strippingTranscoding.encoded(offsetBy: n)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(_ i: Index, offsetBy n: Int) -> Index {
_internalInvariant(_guts.isForeign)
return i.strippingTranscoding.encoded(offsetBy: n)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignCount() -> Int {
_internalInvariant(_guts.isForeign)
return endIndex._encodedOffset - startIndex._encodedOffset
}
// Align a native UTF-8 index to a valid UTF-16 position. If there is a
// transcoded offset already, this is already a valid UTF-16 position
// (referring to the second surrogate) and returns `idx`. Otherwise, this will
// scalar-align the index. This is needed because we may be passed a
// non-scalar-aligned index from the UTF8View.
@_alwaysEmitIntoClient // Swift 5.1
@inline(__always)
internal func _utf16AlignNativeIndex(_ idx: String.Index) -> String.Index {
_internalInvariant(!_guts.isForeign)
guard idx.transcodedOffset == 0 else { return idx }
return _guts.scalarAlign(idx)
}
}
extension String.Index {
@usableFromInline @inline(never) // opaque slow-path
@_effects(releasenone)
internal func _foreignIsWithin(_ target: String.UTF16View) -> Bool {
_internalInvariant(target._guts.isForeign)
// If we're transcoding, we're a UTF-8 view index, not UTF-16.
return self.transcodedOffset == 0
}
}
// Breadcrumb-aware acceleration
extension _StringGuts {
@inline(__always)
fileprivate func _useBreadcrumbs(forEncodedOffset offset: Int) -> Bool {
return hasBreadcrumbs && offset >= _StringBreadcrumbs.breadcrumbStride
}
}
extension String.UTF16View {
@usableFromInline
@_effects(releasenone)
internal func _nativeGetOffset(for idx: Index) -> Int {
// Trivial and common: start
if idx == startIndex { return 0 }
if _guts.isASCII {
_internalInvariant(idx.transcodedOffset == 0)
return idx._encodedOffset
}
let idx = _utf16AlignNativeIndex(idx)
guard _guts._useBreadcrumbs(forEncodedOffset: idx._encodedOffset) else {
// TODO: Generic _distance is still very slow. We should be able to
// skip over ASCII substrings quickly
return _distance(from: startIndex, to: idx)
}
// Simple and common: endIndex aka `length`.
let breadcrumbsPtr = _guts.getBreadcrumbsPtr()
if idx == endIndex { return breadcrumbsPtr.pointee.utf16Length }
// Otherwise, find the nearest lower-bound breadcrumb and count from there
let (crumb, crumbOffset) = breadcrumbsPtr.pointee.getBreadcrumb(
forIndex: idx)
return crumbOffset + _distance(from: crumb, to: idx)
}
@usableFromInline
@_effects(releasenone)
internal func _nativeGetIndex(for offset: Int) -> Index {
// Trivial and common: start
if offset == 0 { return startIndex }
if _guts.isASCII { return Index(_encodedOffset: offset) }
guard _guts._useBreadcrumbs(forEncodedOffset: offset) else {
return _index(startIndex, offsetBy: offset)
}
// Simple and common: endIndex aka `length`.
let breadcrumbsPtr = _guts.getBreadcrumbsPtr()
if offset == breadcrumbsPtr.pointee.utf16Length { return endIndex }
// Otherwise, find the nearest lower-bound breadcrumb and advance that
let (crumb, remaining) = breadcrumbsPtr.pointee.getBreadcrumb(
forOffset: offset)
if remaining == 0 { return crumb }
return _guts.withFastUTF8 { utf8 in
var readIdx = crumb._encodedOffset
let readEnd = utf8.count
_internalInvariant(readIdx < readEnd)
var utf16I = 0
let utf16End: Int = remaining
// Adjust for sub-scalar initial transcoding: If we're starting the scan
// at a trailing surrogate, then we set our starting count to be -1 so as
// offset counting the leading surrogate.
if crumb.transcodedOffset != 0 {
utf16I = -1
}
while true {
let len = _utf8ScalarLength(utf8[_unchecked: readIdx])
let utf16Len = len == 4 ? 2 : 1
utf16I &+= utf16Len
if utf16I >= utf16End {
// Uncommon: final sub-scalar transcoded offset
if _slowPath(utf16I > utf16End) {
_internalInvariant(utf16Len == 2)
return Index(encodedOffset: readIdx, transcodedOffset: 1)
}
return Index(_encodedOffset: readIdx &+ len)._scalarAligned
}
readIdx &+= len
}
}
}
// Copy (i.e. transcode to UTF-16) our contents into a buffer. `alignedRange`
// means that the indices are part of the UTF16View.indices -- they are either
// scalar-aligned or transcoded (e.g. derived from the UTF-16 view). They do
// not need to go through an alignment check.
internal func _nativeCopy(
into buffer: UnsafeMutableBufferPointer<UInt16>,
alignedRange range: Range<String.Index>
) {
_internalInvariant(_guts.isFastUTF8)
_internalInvariant(
range.lowerBound == _utf16AlignNativeIndex(range.lowerBound))
_internalInvariant(
range.upperBound == _utf16AlignNativeIndex(range.upperBound))
if _slowPath(range.isEmpty) { return }
let isASCII = _guts.isASCII
return _guts.withFastUTF8 { utf8 in
var writeIdx = 0
let writeEnd = buffer.count
var readIdx = range.lowerBound._encodedOffset
let readEnd = range.upperBound._encodedOffset
if isASCII {
_internalInvariant(range.lowerBound.transcodedOffset == 0)
_internalInvariant(range.upperBound.transcodedOffset == 0)
while readIdx < readEnd {
_internalInvariant(utf8[readIdx] < 0x80)
buffer[_unchecked: writeIdx] = UInt16(
truncatingIfNeeded: utf8[_unchecked: readIdx])
readIdx &+= 1
writeIdx &+= 1
}
return
}
// Handle mid-transcoded-scalar initial index
if _slowPath(range.lowerBound.transcodedOffset != 0) {
_internalInvariant(range.lowerBound.transcodedOffset == 1)
let (scalar, len) = _decodeScalar(utf8, startingAt: readIdx)
buffer[writeIdx] = scalar.utf16[1]
readIdx &+= len
writeIdx &+= 1
}
// Transcode middle
while readIdx < readEnd {
let (scalar, len) = _decodeScalar(utf8, startingAt: readIdx)
buffer[writeIdx] = scalar.utf16[0]
readIdx &+= len
writeIdx &+= 1
if _slowPath(scalar.utf16.count == 2) {
buffer[writeIdx] = scalar.utf16[1]
writeIdx &+= 1
}
}
// Handle mid-transcoded-scalar final index
if _slowPath(range.upperBound.transcodedOffset == 1) {
_internalInvariant(writeIdx < writeEnd)
let (scalar, _) = _decodeScalar(utf8, startingAt: readIdx)
_internalInvariant(scalar.utf16.count == 2)
buffer[writeIdx] = scalar.utf16[0]
writeIdx &+= 1
}
_internalInvariant(writeIdx <= writeEnd)
}
}
}
| apache-2.0 | 473c1053073e85520bab5e36fbd33bbb | 32.363095 | 80 | 0.649019 | 4.165738 | false | false | false | false |
lorentey/swift | test/Sema/clang_types_in_ast.swift | 3 | 2173 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -DNOCRASH1
// RUN: %target-swift-frontend %s -typecheck -DNOCRASH1 -use-clang-function-types
// RUN: %target-swift-frontend %s -typecheck -DNOCRASH2 -sdk %clang-importer-sdk
// RUN: %target-swift-frontend %s -typecheck -DNOCRASH2 -sdk %clang-importer-sdk -use-clang-function-types
// RUN: %target-swift-frontend %s -DAUXMODULE -module-name Foo -emit-module -o %t
// rdar://problem/57644243 : We shouldn't crash if -use-clang-function-types is not enabled.
// RUN: %target-swift-frontend %s -typecheck -DNOCRASH3 -I %t
// FIXME: [clang-function-type-serialization] This should stop crashing once we
// start serializing clang function types.
// RUN: not --crash %target-swift-frontend %s -typecheck -DCRASH -I %t -use-clang-function-types
#if NOCRASH1
public func my_signal() -> Optional<@convention(c) (Int32) -> Void> {
let s : Optional<@convention(c) (Int32) -> Void> = .none;
var s2 : Optional<@convention(c) (Int32) -> Void> = s;
return s2;
}
#endif
#if NOCRASH2
import ctypes
func f() {
_ = getFunctionPointer() as (@convention(c) (CInt) -> CInt)?
}
#endif
#if AUXMODULE
public var DUMMY_SIGNAL1 : Optional<@convention(c) (Int32) -> ()> = .none
public var DUMMY_SIGNAL2 : Optional<@convention(c) (Int32) -> Void> = .none
#endif
#if NOCRASH3
import Foo
public func my_signal1() -> Optional<@convention(c) (Int32) -> ()> {
return Foo.DUMMY_SIGNAL1
}
public func my_signal2() -> Optional<@convention(c) (Int32) -> Void> {
return Foo.DUMMY_SIGNAL1
}
public func my_signal3() -> Optional<@convention(c) (Int32) -> ()> {
return Foo.DUMMY_SIGNAL2
}
public func my_signal4() -> Optional<@convention(c) (Int32) -> Void> {
return Foo.DUMMY_SIGNAL2
}
#endif
#if CRASH
import Foo
public func my_signal1() -> Optional<@convention(c) (Int32) -> ()> {
return Foo.DUMMY_SIGNAL1
}
public func my_signal2() -> Optional<@convention(c) (Int32) -> Void> {
return Foo.DUMMY_SIGNAL1
}
public func my_signal3() -> Optional<@convention(c) (Int32) -> ()> {
return Foo.DUMMY_SIGNAL2
}
public func my_signal4() -> Optional<@convention(c) (Int32) -> Void> {
return Foo.DUMMY_SIGNAL2
}
#endif
| apache-2.0 | b46ed407d63a444401244b11bc362492 | 32.430769 | 106 | 0.68983 | 3.056259 | false | false | false | false |
phimage/AboutWindow | Sources/AboutWindowController.swift | 1 | 8583 | //
// AboutWindowController.swift
// AboutWindow
/*
The MIT License (MIT)
Copyright (c) 2015-2016 Perceval Faramaz
Copyright (c) 2016 Eric Marchand (phimage)
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 Cocoa
open class AboutWindowController : NSWindowController {
open var appName: String?
open var appVersion: String?
open var appCopyright: NSAttributedString?
/** The string to hold the credits if we're showing them in same window. */
open var appCredits: NSAttributedString?
open var appEULA: NSAttributedString?
open var appURL: URL?
open var appStoreURL: URL?
open var logClosure: (String) -> Void = { message in print(message) }
open var font: NSFont = NSFont(name: "HelveticaNeue", size: 11.0)!
/** Select a background color (defaults to white). */
open var backgroundColor: NSColor = NSColor.white
/** Select the title (app name & version) color (defaults to black). */
open var titleColor: NSColor = NSColor.black
/** Select the text (Acknowledgments & EULA) color (defaults to light grey). */
open var textColor: NSColor = (floor(NSAppKitVersionNumber) <= Double(NSAppKitVersionNumber10_9)) ? NSColor.lightGray : NSColor.tertiaryLabelColor
open var windowShouldHaveShadow: Bool = true
open var windowState: Int = 0
open var amountToIncreaseHeight:CGFloat = 100
/** The info view. */
@IBOutlet var infoView: NSView!
/** The main text view. */
@IBOutlet var textField: NSTextView!
/** The app version's text view. */
@IBOutlet var versionField: NSTextField!
/** The button that opens the app's website. */
@IBOutlet var visitWebsiteButton: NSButton!
/** The button that opens the EULA. */
@IBOutlet var EULAButton: NSButton!
/** The button that opens the credits. */
@IBOutlet var creditsButton: NSButton!
/** The button that opens the appstore's website. */
@IBOutlet var ratingButton: NSButton!
@IBOutlet var EULAConstraint: NSLayoutConstraint!
@IBOutlet var creditsConstraint: NSLayoutConstraint!
@IBOutlet var ratingConstraint: NSLayoutConstraint!
// MARK: override
override open var windowNibName : String! {
return "PFAboutWindow"
}
override open func windowDidLoad() {
super.windowDidLoad()
assert (self.window != nil)
self.window?.backgroundColor = backgroundColor
self.window?.hasShadow = self.windowShouldHaveShadow
self.windowState = 0
self.infoView.wantsLayer = true
self.infoView.layer?.cornerRadius = 10.0
self.infoView.layer?.backgroundColor = NSColor.white.cgColor
(self.visitWebsiteButton.cell as? NSButtonCell)?.highlightsBy = NSCellStyleMask()
if self.appName == nil {
self.appName = valueFromInfoDict("CFBundleName")
}
if self.appVersion == nil {
let version = valueFromInfoDict("CFBundleVersion")
let shortVersion = valueFromInfoDict("CFBundleShortVersionString")
self.appVersion = String(format: NSLocalizedString("Version %@ (Build %@)", comment:"Version %@ (Build %@), displayed in the about window"), shortVersion, version)
}
versionField.stringValue = self.appVersion ?? ""
versionField.textColor = self.titleColor
if self.appCopyright == nil {
let attribs: [String:AnyObject] = [NSForegroundColorAttributeName: textColor, NSFontAttributeName: font]
self.appCopyright = NSAttributedString(string: valueFromInfoDict("NSHumanReadableCopyright"), attributes:attribs)
}
if let copyright = self.appCopyright {
self.textField.textStorage?.setAttributedString(copyright)
self.textField.textColor = self.textColor
}
self.creditsButton.title = NSLocalizedString("Credits", comment: "Caption of the 'Credits' button in the about window")
if self.appCredits == nil {
if let creditsRTF = Bundle.main.url(forResource: "Credits", withExtension: "rtf"),
let str = try? NSAttributedString(url: creditsRTF, options: [:], documentAttributes : nil) {
self.appCredits = str
}
else {
hideButton(self.creditsButton, self.creditsConstraint)
logClosure("Credits not found in bundle. Hiding Credits Button.")
}
}
self.EULAButton.title = NSLocalizedString("License Agreement", comment: "Caption of the 'License Agreement' button in the about window")
if self.appEULA == nil {
if let eulaRTF = Bundle.main.url(forResource: "EULA", withExtension: "rtf"),
let str = try? NSAttributedString(url: eulaRTF, options: [:], documentAttributes: nil) {
self.appEULA = str
}
else {
hideButton(self.EULAButton, self.EULAConstraint)
logClosure("EULA not found in bundle. Hiding EULA Button.")
}
}
self.ratingButton.title = NSLocalizedString("★Rate on the app store", comment: "Caption of the 'Rate on the app store'")
if appStoreURL == nil {
hideButton(self.ratingButton, self.ratingConstraint)
}
}
open func windowShouldClose(_ sender: AnyObject) -> Bool {
self.showCopyright(sender)
return true
}
// MARK: IBAction
@IBAction open func visitWebsite(_ sender: AnyObject) {
if let URL = appURL {
NSWorkspace.shared().open(URL)
}
}
@IBAction open func visitAppStore(_ sender: AnyObject) {
if let URL = appStoreURL {
NSWorkspace.shared().open(URL)
}
}
@IBAction open func showCredits(_ sender: AnyObject) {
changeWindowState(1, amountToIncreaseHeight)
self.textField.textStorage?.setAttributedString(self.appCredits ?? NSAttributedString())
self.textField.textColor = self.textColor
}
@IBAction open func showEULA(_ sender: AnyObject) {
changeWindowState(1, amountToIncreaseHeight)
self.textField.textStorage?.setAttributedString(self.appEULA ?? NSAttributedString())
self.textField.textColor = self.textColor
}
@IBAction open func showCopyright(_ sender: AnyObject) {
changeWindowState(0, -amountToIncreaseHeight)
self.textField.textStorage?.setAttributedString(self.appCopyright ?? NSAttributedString())
self.textField.textColor = self.textColor
}
// MARK: Private
fileprivate func valueFromInfoDict(_ string: String) -> String {
let dictionary = Bundle.main.infoDictionary!
return dictionary[string] as! String
}
fileprivate func changeWindowState(_ state: Int,_ amountToIncreaseHeight: CGFloat) {
if let window = self.window , self.windowState != state {
var oldFrame = window.frame
oldFrame.size.height += amountToIncreaseHeight
oldFrame.origin.y -= amountToIncreaseHeight
window.setFrame(oldFrame, display: true, animate: true)
self.windowState = state
}
}
fileprivate func hideButton(_ button: NSButton,_ constraint: NSLayoutConstraint) {
button.isHidden = true
button.setFrameSize(NSSize(width: 0, height: self.creditsButton.frame.height))
button.title = ""
button.isBordered = false
constraint.constant = 0
print("\(button.frame)")
}
}
| mit | 11464a70d5b05a51d3c786b20b8fb011 | 40.254808 | 175 | 0.665191 | 5.003499 | false | false | false | false |
jdommes/inquire | Sources/TextField.swift | 1 | 3522 | //
// TextField.swift
// Inquire
//
// Created by Wesley Cope on 1/13/16.
// Copyright © 2016 Wess Cope. All rights reserved.
//
import Foundation
import UIKit
/// UITextField with name, validators, and errors for usage with Form.
open class TextField : UITextField, Field {
/// Form containing field.
open var form:Form?
/// Previous Field in form
open var previousField: Field?
/// Next field
open var nextField:Field?
/// Block called when the field isn't valid.
open var onError:FieldErrorHandler?
/// Name of field, default to property name in form.
open var name:String = ""
/// Title of field, usually the same as Placeholder
open var title:String = ""
/// meta data for field
open var meta:[String:Any] = [:]
/// Input toolbar
fileprivate lazy var toolbar:UIToolbar = {
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44)
let _toolbar = UIToolbar(frame: frame)
return _toolbar
}()
/// Items for field toolbar.
open var toolbarItems:[FieldToolbarButtonItem]? {
didSet {
inputAccessoryView = nil
if let items = toolbarItems , items.count > 0 {
toolbar.items = items
inputAccessoryView = toolbar
}
}
}
/// Validators used against value of field.
open var validators:[ValidationRule] = []
/// Field errors.
open var errors:[(ValidationType, String)] = []
/// Field's value.
open var value:String? {
get {
return self.text
}
set {
self.text = String(describing: newValue)
}
}
open var setupBlock:((TextField) -> Void)? = nil
public convenience init(placeholder:String?) {
self.init(validators:[], setup:nil)
self.placeholder = placeholder
}
public convenience init(placeholder:String?, setup:((TextField) -> Void)?) {
self.init(validators:[], setup:setup)
self.placeholder = placeholder
}
public convenience init(placeholder:String?, validators:[ValidationRule]?) {
self.init(validators:validators ?? [], setup:nil)
self.placeholder = placeholder
}
public convenience init(placeholder:String?, validators:[ValidationRule]?, setup:((TextField) -> Void)?) {
self.init(validators:validators ?? [], setup:setup)
self.placeholder = placeholder
}
public convenience init() {
self.init(validators:[], setup:nil)
}
public convenience init(setup:((TextField) -> Void)?) {
self.init(validators:[], setup:setup)
}
public convenience init(validators:[ValidationRule] = []) {
self.init(validators:validators, setup:nil)
}
public required init(validators:[ValidationRule] = [], setup:((TextField) -> Void)?) {
super.init(frame: .zero)
self.validators = validators
self.setupBlock = setup
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func move(_ to:Field) {
resignFirstResponder()
if let field = to as? TextField {
field.becomeFirstResponder()
}
if let field = to as? TextView {
field.becomeFirstResponder()
}
}
}
| mit | b84c05897271e7056dfccdb8c5879601 | 24.15 | 110 | 0.581085 | 4.790476 | false | false | false | false |
FuckBoilerplate/RxCache | watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/Range.swift | 6 | 1674 | //
// Range.swift
// Rx
//
// Created by Krunoslav Zaher on 9/13/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class RangeProducer<E: SignedInteger> : Producer<E> {
fileprivate let _start: E
fileprivate let _count: E
fileprivate let _scheduler: ImmediateSchedulerType
init(start: E, count: E, scheduler: ImmediateSchedulerType) {
if count < 0 {
rxFatalError("count can't be negative")
}
if start &+ (count - 1) < start {
rxFatalError("overflow of count")
}
_start = start
_count = count
_scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
let sink = RangeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
class RangeSink<O: ObserverType> : Sink<O> where O.E: SignedInteger {
typealias Parent = RangeProducer<O.E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return _parent._scheduler.scheduleRecursive(0 as O.E) { i, recurse in
if i < self._parent._count {
self.forwardOn(.next(self._parent._start + i))
recurse(i + 1)
}
else {
self.forwardOn(.completed)
self.dispose()
}
}
}
}
| mit | 26f0b61c606b2e1f8b5bc6c2393ff93f | 27.355932 | 139 | 0.579199 | 4.267857 | false | false | false | false |
shahmishal/swift | test/Driver/options-repl.swift | 4 | 2188 | // RUN: not %swift -repl %s 2>&1 | %FileCheck -check-prefix=REPL_NO_FILES %s
// RUN: not %swift_driver -sdk "" -repl %s 2>&1 | %FileCheck -check-prefix=REPL_NO_FILES %s
// RUN: not %swift_driver -sdk "" -lldb-repl %s 2>&1 | %FileCheck -check-prefix=REPL_NO_FILES %s
// RUN: not %swift_driver -sdk "" -deprecated-integrated-repl %s 2>&1 | %FileCheck -check-prefix=REPL_NO_FILES %s
// REPL_NO_FILES: REPL mode requires no input files
// RUN: %empty-directory(%t)
// RUN: mkdir -p %t/usr/bin
// RUN: %hardlink-or-copy(from: %swift_driver_plain, to: %t/usr/bin/swift)
// RUN: %t/usr/bin/swift -sdk "" -deprecated-integrated-repl -### | %FileCheck -check-prefix=INTEGRATED %s
// INTEGRATED: swift{{c?(\.EXE)?"?}} -frontend -repl
// INTEGRATED: -module-name REPL
// RUN: %swift_driver -sdk "" -lldb-repl -### | %FileCheck -check-prefix=LLDB %s
// RUN: %swift_driver -sdk "" -lldb-repl -D A -DB -D C -DD -L /path/to/libraries -L /path/to/more/libraries -F /path/to/frameworks -lsomelib -framework SomeFramework -sdk / -I "this folder" -module-name Test -target %target-triple -### | %FileCheck -check-prefix=LLDB-OPTS %s
// LLDB: lldb{{(\.exe)?"?}} {{"?}}--repl=
// LLDB-NOT: -module-name
// LLDB-NOT: -target
// LLDB-OPTS: lldb{{(\.exe)?"?}} "--repl=
// LLDB-OPTS-DAG: -target {{[^ ]+}}
// LLDB-OPTS-DAG: -D A -D B -D C -D D
// LLDB-OPTS-DAG: -sdk /
// LLDB-OPTS-DAG: -L /path/to/libraries
// LLDB-OPTS-DAG: -L /path/to/more/libraries
// LLDB-OPTS-DAG: -F /path/to/frameworks
// LLDB-OPTS-DAG: -lsomelib
// LLDB-OPTS-DAG: -framework SomeFramework
// LLDB-OPTS-DAG: -I \"this folder\"
// LLDB-OPTS: "
// Test LLDB detection, first in a clean environment, then in one that looks
// like the Xcode installation environment. We use hard links to make sure
// the Swift driver really thinks it's been moved.
// RUN: %t/usr/bin/swift -sdk "" -repl -### | %FileCheck -check-prefix=INTEGRATED %s
// RUN: %t/usr/bin/swift -sdk "" -### | %FileCheck -check-prefix=INTEGRATED %s
// RUN: touch %t/usr/bin/lldb
// RUN: chmod +x %t/usr/bin/lldb
// RUN: %t/usr/bin/swift -sdk "" -repl -### | %FileCheck -check-prefix=LLDB %s
// RUN: %t/usr/bin/swift -sdk "" -### | %FileCheck -check-prefix=LLDB %s
| apache-2.0 | 2800161458876cfd726505ca411a0521 | 44.583333 | 275 | 0.645795 | 2.845254 | false | false | true | false |
pawel-sp/AppFlowController | AppFlowController/AppFlowController.swift | 1 | 24184 | //
// AppFlowController.swift
// AppFlowController
//
// Created by Paweł Sporysz on 22.09.2016.
// Copyright (c) 2017 Paweł Sporysz
// https://github.com/pawel-sp/AppFlowController
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
open class AppFlowController {
// MARK: - Properties
public static let shared = AppFlowController()
public var rootNavigationController: UINavigationController?
private(set) var rootPathStep: PathStep?
let tracker: Tracker
// MARK: - Init
init(trackerClass: Tracker.Type) {
tracker = trackerClass.init()
}
public convenience init() {
self.init(trackerClass: Tracker.self)
}
// MARK: - Setup
/**
You need to use that method before you gonna start use AppFlowController to present pages.
- Parameter window: Current app's window.
- Parameter rootNavigationController: AppFlowController requires that root navigation controller is kind of UINavigationController.
*/
public func prepare(for window: UIWindow, rootNavigationController: UINavigationController = UINavigationController()) {
self.rootNavigationController = rootNavigationController
window.rootViewController = rootNavigationController
}
public func register(pathComponent: FlowPathComponent) throws {
try register(pathComponents: [pathComponent])
}
public func register(pathComponents: [FlowPathComponent]) throws {
if let lastPathComponent = pathComponents.last, !lastPathComponent.supportVariants, rootPathStep?.search(pathComponent: lastPathComponent) != nil {
throw AFCError.pathAlreadyRegistered(identifier: lastPathComponent.identifier)
}
var previousStep: PathStep?
for var element in pathComponents {
if let found = rootPathStep?.search(pathComponent: element) {
previousStep = found
continue
} else {
if let previous = previousStep {
if element.supportVariants {
element.variantName = previous.pathComponent.identifier
}
if element.forwardTransition == nil || element.backwardTransition == nil {
throw AFCError.missingPathStepTransition(identifier: element.identifier)
}
previousStep = previous.add(pathComponent: element)
} else {
rootPathStep = PathStep(pathComponent: element)
previousStep = rootPathStep
}
}
}
}
/**
Before presenting any page you need to register it using path components.
- Parameter pathComponents: Sequences of pages which represent all possible paths inside the app. The best way to register pages is to use => and =>> operators which assign transitions directly to pages.
- Throws:
AFCError.missingPathStepTransition if forward or backward transition of any page is nil
AFCError.pathAlreadyRegistered if that page was registered before (all pages need to have unique name). If you want to use the same page few times in different places it's necessary to set supportVariants property to true.
*/
public func register(pathComponents: [[FlowPathComponent]]) throws {
for subPathComponents in pathComponents {
try register(pathComponents: subPathComponents)
}
}
// MARK: - Navigation
/**
Display view controller configured inside the path.
- Parameter pathComponent: Page to present.
- Parameter variant: If page supports variants you need to pass the correct variant (previous page). Default = nil.
- Parameter parameters: For every page you can set single string value as it's parameter. It works also for pages with variants. Default = nil.
- Parameter animated: Determines if presenting page should be animated or not. Default = true.
- Parameter skipDismissTransitions: Use that property to skip all dismiss transitions. Use that with conscience since it can break whole view's stack (it's helpfull for example when app has side menu).
- Parameter skipPages: Pages to skip.
- Throws:
AFCError.missingConfiguration if prepare(UIWindow, UINavigationController) wasn't invoked before.
AFCError.showingSkippedPage if page was previously skipped (for example when you're trying go back to page which before was skipped and it's not present inside the navigation controller).
AFCError.missingVariant if page's property supportVariants == true you need to pass variant property, otherwise it's not possible to set which page should be presenter.
AFCError.variantNotSupported if page's property supportVariants == false you cannot pass variant property, because there is only one variant of that page.
AFCError.unregisteredPathIdentifier page need to be registered before showing it.
*/
open func show(
_ pathComponent: FlowPathComponent,
variant: FlowPathComponent? = nil,
parameters: [TransitionParameter]? = nil,
animated: Bool = true,
skipDismissTransitions: Bool = false,
skipPathComponents: [FlowPathComponent]? = nil) throws {
guard let rootNavigationController = rootNavigationController else {
throw AFCError.missingConfiguration
}
let foundStep = try pathStep(from: pathComponent, variant: variant)
let newPathComponents = rootPathStep?.allParentPathComponents(from: foundStep) ?? []
let currentStep = visibleStep
let currentPathComponents = currentStep == nil ? [] : (rootPathStep?.allParentPathComponents(from: currentStep!) ?? [])
let keysToClearSkip = newPathComponents.filter({ !currentPathComponents.contains($0) }).map({ $0.identifier })
if let currentStep = currentStep {
let distance = PathStep.distanceBetween(step: currentStep, and: foundStep)
let dismissCounter = distance.up
let _ = distance.down
let dismissRange: Range<Int> = dismissCounter == 0 ? 0..<0 : (currentPathComponents.count - dismissCounter) ..< currentPathComponents.count
let displayRange: Range<Int> = 0 ..< newPathComponents.count
try verify(pathComponents: currentPathComponents, distance: distance)
dismiss(pathComponents: currentPathComponents, fromIndexRange: dismissRange, animated: animated, skipTransition: skipDismissTransitions) {
self.register(parameters: parameters, for: newPathComponents, skippedPathComponents: skipPathComponents)
self.tracker.disableSkip(for: keysToClearSkip)
self.display(pathComponents: newPathComponents, fromIndexRange: displayRange, animated: animated, skipPathComponents: skipPathComponents, completion: nil)
}
} else {
rootNavigationController.viewControllers.removeAll()
tracker.reset()
register(parameters: parameters, for: newPathComponents, skippedPathComponents: skipPathComponents)
tracker.disableSkip(for: keysToClearSkip)
display(pathComponents: newPathComponents, fromIndexRange: 0..<newPathComponents.count, animated: animated, skipPathComponents: skipPathComponents, completion: nil)
}
}
/**
Displays previous page.
- Parameter animated: Determines if presenting page should be animated or not. Default = true.
*/
public func goBack(animated: Bool = true) {
guard let visible = visibleStep else { return }
guard let pathComponent = visible.firstParentPathComponent(where: { tracker.viewController(for: $0.identifier) != nil }) else { return }
guard let viewController = tracker.viewController(for: pathComponent.identifier) else { return }
visible.pathComponent.backwardTransition?.performBackwardTransition(animated: animated){}(viewController)
}
/**
Pops navigation controller to specified path. It always current view controller's navigation controller. If page isn't not present in current navigation controller nothing would happen.
- Parameter pathComponent: Path component to pop.
- Parameter animated: Determines if transition should be animated or not.
*/
public func pop(to pathComponent: FlowPathComponent, animated: Bool = true) throws {
guard let rootNavigationController = rootNavigationController else {
throw AFCError.missingConfiguration
}
guard let foundStep = rootPathStep?.search(pathComponent: pathComponent) else {
throw AFCError.unregisteredPathIdentifier(identifier: pathComponent.identifier)
}
guard let targetViewController = tracker.viewController(for: foundStep.pathComponent.identifier) else {
throw AFCError.popToSkippedPath(identifier: foundStep.pathComponent.identifier)
}
rootNavigationController.visible.navigationController?.popToViewController(targetViewController, animated: animated)
}
/**
If you presented view controller without AppFlowController you need to update current path. Use that method inside the viewDidLoad method of presented view controller to make sure that whole step tree still works.
- Parameter viewController: Presented view controller.
- Parameter name: Name of path associated with that view controller. That page need to be registered.
- Throws:
AFCError.unregisteredPathIdentifier if page wasn't registered before.
*/
public func updateCurrentPath(with viewController: UIViewController, for name:String) throws {
if let _ = rootPathStep?.search(identifier: name) {
self.tracker.register(viewController: viewController, for: name)
} else {
throw AFCError.unregisteredPathIdentifier(identifier: name)
}
}
/**
Returns string representation of whole path to specified page, for example home/start/login.
- Parameter pathComponent: Path component to receive all path steps.
- Parameter variant: Variant of that page (previous path component). Use it only if page supports variants.
- Throws:
AFCError.missingVariant if page's property supportVariants == true you need to pass variant property, otherwise it's not possible to set which page should be presenter.
AFCError.variantNotSupported if page's property supportVariants == false you cannot pass variant property, because there is only one variant of that page.
AFCError.unregisteredPathIdentifier page need to be registered before showing it.
*/
open func pathComponents(for pathComponent: FlowPathComponent, variant: FlowPathComponent? = nil) throws -> String {
let foundStep = try pathStep(from: pathComponent, variant: variant)
let pathComponents = rootPathStep?.allParentPathComponents(from: foundStep) ?? []
let pathComponentStrings = pathComponents.map{ $0.identifier }
return pathComponentStrings.joined(separator: "/")
}
/**
Returns string representation of whole path to current path, for example home/start/login.
*/
open var currentPathDescription: String? {
if let visibleStep = visibleStep {
let items = rootPathStep?.allParentPathComponents(from: visibleStep) ?? []
let itemStrings = items.map{ $0.identifier }
return itemStrings.joined(separator: "/")
} else {
return nil
}
}
/**
Returns currenlty visible path.
*/
open var currentPathComponent: FlowPathComponent? {
return visibleStep?.pathComponent
}
/**
Returns parameter for currently visible path. It's nil if path was presented without any parametes.
*/
open var currentPathParameter: String? {
if let currentPathID = currentPathComponent?.identifier {
return tracker.parameter(for: currentPathID)
} else {
return nil
}
}
/**
Returns parameter for specified path. It's nil if page was presented without any parametes.
- Parameter pathComponent: Path component to retrieve parameter.
- Parameter variant: Variant of that path (previous path). Use it only if page supports variants.
- Throws:
AFCError.missingVariant if pathe's property supportVariants == true you need to pass variant property, otherwise it's not possible to set which page should be presenter.
AFCError.variantNotSupported if path's property supportVariants == false you cannot pass variant property, because there is only one variant of that page.
AFCError.unregisteredPathIdentifier page need to be registered before showing it.
*/
open func parameter(for pathComponent: FlowPathComponent, variant: FlowPathComponent? = nil) throws -> String? {
let step = try pathStep(from: pathComponent, variant: variant)
return tracker.parameter(for: step.pathComponent.identifier)
}
/**
Reset root navigation controller and view's tracker. It removes all view controllers including those presented modally.
*/
open func reset(completion: (()->())? = nil) {
rootNavigationController?.dismissAllPresentedViewControllers() {
self.rootNavigationController?.viewControllers.removeAll()
self.tracker.reset()
completion?()
}
}
// MARK: - Helpers
private var visibleStep: PathStep? {
guard let currentViewController = rootNavigationController?.visibleNavigationController.visible else { return nil }
guard let key = tracker.key(for: currentViewController) else { return nil }
return rootPathStep?.search(identifier: key)
}
private func viewControllers(from pathComponents: [FlowPathComponent], skipPathComponents: [FlowPathComponent]? = nil) -> [UIViewController] {
var viewControllers: [UIViewController] = []
for pathComponent in pathComponents {
if pathComponent.forwardTransition?.shouldPreloadViewController() == true, let viewController = tracker.viewController(for: pathComponent.identifier) {
viewControllers.append(viewController)
continue
}
if skipPathComponents?.contains(where: { $0.identifier == pathComponent.identifier }) == true {
tracker.register(viewController: nil, for: pathComponent.identifier, skipped: true)
continue
}
let viewController = pathComponent.viewControllerInit()
tracker.register(viewController: viewController, for: pathComponent.identifier)
if let step = rootPathStep?.search(pathComponent: pathComponent) {
let preload = step.children.filter({ $0.pathComponent.forwardTransition?.shouldPreloadViewController() == true })
for item in preload {
if let childViewController = self.viewControllers(from: [item.pathComponent], skipPathComponents: skipPathComponents).first {
item.pathComponent.forwardTransition?.preloadViewController(childViewController, from: viewController)
}
}
}
viewControllers.append(pathComponent.forwardTransition?.configureViewController(from: viewController) ?? viewController)
}
return viewControllers
}
private func register(parameters: [TransitionParameter]?, for pathComponents: [FlowPathComponent], skippedPathComponents: [FlowPathComponent]?) {
if let parameters = parameters {
for parameter in parameters {
if pathComponents.filter({ $0.identifier == parameter.identifier }).count == 0 {
continue
}
if (skippedPathComponents?.filter({ $0.identifier == parameter.identifier }).count ?? 0) > 0 {
continue
}
self.tracker.register(parameter: parameter.value, for: parameter.identifier)
}
}
}
private func display(pathComponents: [FlowPathComponent], fromIndexRange indexRange: Range<Int>, animated: Bool, skipPathComponents: [FlowPathComponent]? = nil, completion: (() -> ())?) {
let index = indexRange.lowerBound
let item = pathComponents[index]
let identifier = item.identifier
guard let navigationController = rootNavigationController?.visible.navigationController ?? rootNavigationController else {
completion?()
return
}
func displayNextItem(range: Range<Int>, animated: Bool, offset: Int = 0) {
let newRange:Range<Int> = (range.lowerBound + 1 + offset) ..< range.upperBound
if newRange.count == 0 {
completion?()
} else {
self.display(
pathComponents: pathComponents,
fromIndexRange: newRange,
animated: animated,
skipPathComponents: skipPathComponents,
completion: completion
)
}
}
let viewControllerExists = tracker.viewController(for: item.identifier) != nil
let pathSkipped = tracker.isItemSkipped(at: item.identifier)
let itemIsPreloaded = item.forwardTransition?.shouldPreloadViewController() == true
if navigationController.viewControllers.count == 0 {
let pathComponentsToPush = [item] + pathComponents[1..<pathComponents.count].prefix(while: { $0.forwardTransition is PushPopFlowTransition })
let viewControllersToPush = self.viewControllers(from: pathComponentsToPush, skipPathComponents: skipPathComponents)
let skippedPathComponents = pathComponentsToPush.count - viewControllersToPush.count
navigationController.setViewControllers(viewControllersToPush, animated: false) {
displayNextItem(range: indexRange, animated: false, offset: max(0, viewControllersToPush.count - 1 + skippedPathComponents))
}
} else if (!viewControllerExists || itemIsPreloaded) && !pathSkipped {
let viewControllers = self.viewControllers(from: [item], skipPathComponents: skipPathComponents)
if let viewController = viewControllers.first {
item.forwardTransition?.performForwardTransition(animated: animated){
displayNextItem(range: indexRange, animated: animated)
}(navigationController, viewController)
} else {
displayNextItem(range: indexRange, animated: animated)
}
} else {
displayNextItem(range: indexRange, animated: animated)
}
}
private func dismiss(pathComponents: [FlowPathComponent], fromIndexRange indexRange: Range<Int>, animated: Bool, skipTransition: Bool = false, viewControllerForSkippedPath: UIViewController? = nil, completion:(() -> ())?) {
if indexRange.count == 0 {
completion?()
} else {
let index = indexRange.upperBound - 1
let item = pathComponents[index]
let parentPathComponent = rootPathStep?.search(pathComponent: item)?.parent?.pathComponent
let skipParentPathComponent = parentPathComponent == nil ? false : tracker.isItemSkipped(at: parentPathComponent!.identifier)
let skippedPathComponent = tracker.isItemSkipped(at: item.identifier)
let viewController = tracker.viewController(for: item.identifier)
func dismissNext(viewControllerForSkippedPath: UIViewController? = nil) {
self.dismiss(
pathComponents: pathComponents,
fromIndexRange: indexRange.lowerBound..<indexRange.upperBound - 1,
animated: animated,
skipTransition: skipTransition,
viewControllerForSkippedPath: viewControllerForSkippedPath,
completion: completion
)
}
func dismiss(useTransition: Bool, viewController: UIViewController) {
if useTransition {
item.backwardTransition?.performBackwardTransition(animated: animated){ dismissNext() }(viewController)
} else {
dismissNext()
}
}
if skipParentPathComponent {
dismissNext(viewControllerForSkippedPath: viewController ?? viewControllerForSkippedPath)
} else if let viewController = viewControllerForSkippedPath, skippedPathComponent {
dismiss(useTransition: !skipTransition, viewController: viewController)
} else if let viewController = viewController, !skippedPathComponent {
dismiss(useTransition: !skipTransition, viewController: viewController)
} else {
completion?()
}
}
}
private func pathStep(from pathComponent: FlowPathComponent, variant: FlowPathComponent? = nil) throws -> PathStep {
var pathComponent = pathComponent
if pathComponent.supportVariants && variant == nil {
throw AFCError.missingVariant(identifier: pathComponent.identifier)
}
if !pathComponent.supportVariants && variant != nil {
throw AFCError.variantNotSupported(identifier: pathComponent.identifier)
}
if pathComponent.supportVariants && variant != nil {
pathComponent.variantName = variant?.identifier
}
guard let foundStep = rootPathStep?.search(pathComponent: pathComponent) else {
throw AFCError.unregisteredPathIdentifier(identifier: pathComponent.identifier)
}
return foundStep
}
private func verify(pathComponents: [FlowPathComponent], distance: (up: Int, down: Int)) throws {
if distance.up > 0 {
let lastIndexToDismiss = pathComponents.count - 1 - distance.up
if lastIndexToDismiss >= 0 && lastIndexToDismiss < pathComponents.count - 1 {
let item = pathComponents[lastIndexToDismiss]
if tracker.isItemSkipped(at: item.identifier) {
throw AFCError.showingSkippedPath(identifier: item.identifier)
}
}
}
}
}
| mit | d75062f44f92c3a47692e5fb4d36f0cf | 51.228942 | 238 | 0.65892 | 5.883698 | false | false | false | false |
X140Yu/Lemon | Lemon/Library/GitHub API/User.swift | 1 | 2492 | import Foundation
import ObjectMapper
enum UserType {
case User
case Organization
}
extension UserType {
init(typeString: String) {
if typeString == "Organization" {
self = .Organization
// } else if typeString == "User" {
// self = .User
} else {
self = .User
}
}
}
class User: Mappable {
var avatarUrl : String?
var bio : String?
var blog : String?
var company : String?
var createdAt : String?
var email : String?
var eventsUrl : String?
var followers : Int = 0
var followersUrl : String?
var following : Int = 0
var followingUrl : String?
var gistsUrl : String?
var gravatarId : String?
var hireable : Bool?
var htmlUrl : String?
var id : Int?
var location : String?
var login : String?
var name : String?
var organizationsUrl : String?
var publicGists : Int = 0
var publicRepos : Int = 0
var receivedEventsUrl : String?
var reposUrl : String?
var siteAdmin : Bool?
var starredUrl : String?
var subscriptionsUrl : String?
var type : UserType = .User
var updatedAt : String?
var url : String?
public init(){}
public required init?(map: Map) {}
public func mapping(map: Map)
{
avatarUrl <- map["avatar_url"]
bio <- map["bio"]
blog <- map["blog"]
company <- map["company"]
createdAt <- map["created_at"]
email <- map["email"]
eventsUrl <- map["events_url"]
followers <- map["followers"]
followersUrl <- map["followers_url"]
following <- map["following"]
followingUrl <- map["following_url"]
gistsUrl <- map["gists_url"]
gravatarId <- map["gravatar_id"]
hireable <- map["hireable"]
htmlUrl <- map["html_url"]
id <- map["id"]
location <- map["location"]
login <- map["login"]
name <- map["name"]
organizationsUrl <- map["organizations_url"]
publicGists <- map["public_gists"]
publicRepos <- map["public_repos"]
receivedEventsUrl <- map["received_events_url"]
reposUrl <- map["repos_url"]
siteAdmin <- map["site_admin"]
starredUrl <- map["starred_url"]
subscriptionsUrl <- map["subscriptions_url"]
if let typeString = map["type"].currentValue as? String {
type = UserType(typeString: typeString)
}
// type <- map["type"]
updatedAt <- map["updated_at"]
url <- map["url"]
}
}
extension User: CustomStringConvertible {
var description: String {
return "User: `\(login ?? "")` `\(bio ?? "")` `\(blog ?? "")` `\(company ?? "")`"
}
}
| gpl-3.0 | d249e87b47e23c146f21aa8fe4ee10aa | 24.171717 | 85 | 0.615169 | 3.833846 | false | false | false | false |
Alienson/Bc | source-code/Parketovanie/ParquetElkoObratene.swift | 1 | 2043 | //
// ParquetElkoObratene.swift
// Parketovanie
//
// Created by Adam Turna on 19.4.2016.
// Copyright © 2016 Adam Turna. All rights reserved.
//
import Foundation
import SpriteKit
class ParquetElkoObratene: Parquet {
init(parent: SKSpriteNode, position: CGPoint){
super.init(imageNamed: "7-elko-obratene", position: position)
let abstractCell = Cell()
let height = abstractCell.frame.height
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height), parent: parent))
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height*2), parent: parent))
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height*3), parent: parent))
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX+height, y: self.frame.maxY-height*3), parent: parent))
self.arrayOfCells.append(Cell(position: CGPoint(x: height/2, y: height), parent: parent))
self.arrayOfCells.append(Cell(position: CGPoint(x: height/2, y: 0), parent: parent))
self.arrayOfCells.append(Cell(position: CGPoint(x: height/2, y: -height), parent: parent))
self.arrayOfCells.append(Cell(position: CGPoint(x: -height/2, y: -height), parent: parent))
//let cell1 = Cell(row: 1, collumn: 1, isEmpty: true, parent: parent)
for cell in self.arrayOfCells {
//parent.addChild(cell)
self.addChild(cell)
cell.anchorPoint = CGPoint(x: 0.5, y: 0.5)
cell.alpha = CGFloat(1)
cell.barPosition = cell.position
}
super.alpha = CGFloat(0.5)
//self.arrayOfCells = [[Cell(position: CGPoint(self.frame.),parent: parent), nil],[Cell(parent: parent), nil],[Cell(parent: parent), Cell(parent: parent)]]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | ffdcbd3bd35b6324c0a216f102737016 | 44.377778 | 163 | 0.6381 | 3.626998 | false | false | false | false |
CrossWaterBridge/Attributed | Attributed/Parse.swift | 1 | 3315 | //
// Copyright (c) 2015 Hilton Campbell
//
// 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
extension NSAttributedString {
public static func attributedStringFromMarkup(_ markup: String, withModifier modifier: @escaping Modifier) -> NSAttributedString? {
if let data = "<xml>\(markup)</xml>".data(using: .utf8) {
let parser = XMLParser(data: data)
let parserDelegate = ParserDelegate(modifier: modifier)
parser.delegate = parserDelegate
parser.parse()
return parserDelegate.result
} else {
return nil
}
}
}
private class ParserDelegate: NSObject, XMLParserDelegate {
let result = NSMutableAttributedString()
let modifier: Modifier
var lastIndex = 0
var stack = [MarkupElement]()
init(modifier: @escaping Modifier) {
self.modifier = modifier
}
@objc func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
let range = NSMakeRange(lastIndex, result.length - lastIndex)
let startElement = MarkupElement(name: elementName, attributes: attributeDict)
modify(in: range, startElement: startElement, endElement: nil)
lastIndex = result.length
stack.append(startElement)
}
@objc func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
let range = NSMakeRange(lastIndex, result.length - lastIndex)
let endElement = stack.last
modify(in: range, startElement: nil, endElement: endElement)
lastIndex = result.length
stack.removeLast()
}
@objc func parser(_ parser: XMLParser, foundCharacters string: String) {
result.append(NSAttributedString(string: string))
}
func modify(in range: NSRange, startElement: MarkupElement?, endElement: MarkupElement?) {
if !stack.isEmpty {
let state = State(mutableAttributedString: result, range: range, stack: Array(stack[1..<stack.count]), startElement: startElement, endElement: endElement)
modifier(state)
}
}
}
| mit | 80780c7cbb368ace4e4e8157a4e5d13f | 40.962025 | 179 | 0.693213 | 4.962575 | false | false | false | false |
wburhan2/TicTacToe | tictactoe/TTTImageView.swift | 1 | 594 | //
// TTTImageView.swift
// tictactoe
//
// Created by Wilson Burhan on 10/17/14.
// Copyright (c) 2014 Wilson Burhan. All rights reserved.
//
import UIKit
class TTTImageView: UIImageView {
var player:String?
var activated:Bool = false
func setPlayer(_player:String){
self.player = _player;
if activated == false{
if _player == "X" {
self.image = UIImage(named: "X")
}
else{
self.image = UIImage(named: "O")
}
activated = true
}
}
}
| apache-2.0 | 95ba173bf2b1dfa61d0378fc0a4c225a | 18.8 | 58 | 0.505051 | 3.986577 | false | false | false | false |
fgengine/quickly | Quickly/ViewControllers/Dialog/Background/QDialogBlurBackgroundView.swift | 1 | 1839 | //
// Quickly
//
public final class QDialogBlurBackgroundView : QBlurView, IQDialogContainerBackgroundView {
public weak var containerViewController: IQDialogContainerViewController?
public required init() {
super.init(blur: Const.hiddenBlur)
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func setup() {
super.setup()
self.blur = Const.hiddenBlur
self.isHidden = true
}
public func present(viewController: IQDialogViewController, isFirst: Bool, animated: Bool) {
if isFirst == true {
self.isHidden = false
if animated == true {
UIView.animate(withDuration: Const.duration, delay: 0, options: [ .beginFromCurrentState ], animations: {
self.blur = Const.visibleBlur
})
} else {
self.blur = Const.visibleBlur
}
}
}
public func dismiss(viewController: IQDialogViewController, isLast: Bool, animated: Bool) {
if isLast == true {
if animated == true {
UIView.animate(withDuration: Const.duration, delay: 0, options: [ .beginFromCurrentState ], animations: {
self.blur = Const.hiddenBlur
}, completion: { (_) in
self.isHidden = true
})
} else {
self.blur = Const.hiddenBlur
self.isHidden = true
}
}
}
}
// MARK: Private
private extension QDialogBlurBackgroundView {
struct Const {
static let duration: TimeInterval = 0.25
static let hiddenBlur: UIBlurEffect? = nil
static let visibleBlur: UIBlurEffect? = UIBlurEffect(style: .dark)
}
}
| mit | b715a0cf60d1ffad917d061274fdb0e1 | 26.863636 | 121 | 0.574225 | 5.010899 | false | false | false | false |
epodkorytov/OCTextInput | OCTextInput/Classes/OCTextView.swift | 1 | 2577 | import UIKit
final internal class OCTextView: UITextView {
weak var textInputDelegate: TextInputDelegate?
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
fileprivate func setup() {
delegate = self
}
override func resignFirstResponder() -> Bool {
return super.resignFirstResponder()
}
}
extension OCTextView: TextInput {
var currentText: String? {
get { return text }
set { self.text = newValue }
}
var textAttributes: [NSAttributedString.Key: Any] {
get { return typingAttributes }
set { self.typingAttributes = textAttributes }
}
var currentSelectedTextRange: UITextRange? {
get { return self.selectedTextRange }
set { self.selectedTextRange = newValue }
}
public var currentBeginningOfDocument: UITextPosition? {
return self.beginningOfDocument
}
func changeReturnKeyType(with newReturnKeyType: UIReturnKeyType) {
returnKeyType = newReturnKeyType
}
func currentPosition(from: UITextPosition, offset: Int) -> UITextPosition? {
return position(from: from, offset: offset)
}
}
extension OCTextView: UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
textInputDelegate?.textInputDidBeginEditing(textInput: self)
}
func textViewDidEndEditing(_ textView: UITextView) {
textInputDelegate?.textInputDidEndEditing(textInput: self)
}
func textViewDidChange(_ textView: UITextView) {
textInputDelegate?.textInputDidChange(textInput: self)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
return textInputDelegate?.textInputShouldReturn(textInput: self) ?? true
}
return textInputDelegate?.textInput(textInput: self, shouldChangeCharactersInRange: range, replacementString: text) ?? true
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return textInputDelegate?.textInputShouldBeginEditing(textInput: self) ?? true
}
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
return textInputDelegate?.textInputShouldEndEditing(textInput: self) ?? true
}
}
| mit | d02fb66057fdb72c54f691a2472a2d14 | 28.62069 | 131 | 0.661234 | 5.713969 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Cliqz/Frontend/Browser/Settings/AdBlockerSettingsTableViewController.swift | 2 | 3497 | //
// AdBlockerSettingsTableViewController.swift
// Client
//
// Created by Mahmoud Adam on 7/20/16.
// Copyright © 2016 Mozilla. All rights reserved.
//
import UIKit
class AdBlockerSettingsTableViewController: SubSettingsTableViewController {
private let toggleTitles = [
NSLocalizedString("Block Ads", tableName: "Cliqz", comment: "[Settings -> Block Ads] Block Ads"),
NSLocalizedString("Fair Mode", tableName: "Cliqz", comment: "[Settings -> Block Ads] Fair Mode")
]
private let sectionFooters = [
NSLocalizedString("Block Ads footer", tableName: "Cliqz", comment: "[Settings -> Block Ads] Block Ads footer"),
NSLocalizedString("Fair Mode footer", tableName: "Cliqz", comment: "[Settings -> Block Ads] Fair Mode footer")
]
private lazy var toggles: [Bool] = {
return [SettingsPrefs.shared.getAdBlockerPref(), SettingsPrefs.shared.getFairBlockingPref()]
}()
override func getSectionFooter(section: Int) -> String {
guard section < sectionFooters.count else {
return ""
}
return sectionFooters[section]
}
override func getViewName() -> String {
return "block_ads"
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = getUITableViewCell()
cell.textLabel?.text = toggleTitles[indexPath.section]
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: #selector(switchValueChanged(_:)), for: UIControlEvents.valueChanged)
control.isOn = toggles[indexPath.section]
control.accessibilityLabel = "AdBlock Switch"
cell.accessoryView = control
cell.selectionStyle = .none
control.tag = indexPath.section
if self.toggles[0] == false && indexPath.section == 1 {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = UIColor.gray
control.isEnabled = false
} else {
cell.isUserInteractionEnabled = true
cell.textLabel?.textColor = UIColor.black
control.isEnabled = true
}
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
if self.toggles[0] {
return 2
}
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 1 {
return 0
}
return super.tableView(tableView, heightForHeaderInSection: section)
}
@objc func switchValueChanged(_ toggle: UISwitch) {
self.toggles[toggle.tag] = toggle.isOn
saveToggles()
self.tableView.reloadData()
// log telemetry signal
let target = toggle.tag == 0 ? "enable" : "fair_blocking"
let state = toggle.isOn == true ? "off" : "on" // we log old value
let valueChangedSignal = TelemetryLogEventType.Settings("block_ads", "click", target, state, nil)
TelemetryLogger.sharedInstance.logEvent(valueChangedSignal)
}
private func saveToggles() {
SettingsPrefs.shared.updateAdBlockerPref(self.toggles[0])
SettingsPrefs.shared.updateFairBlockingPref(self.toggles[1])
}
}
| mpl-2.0 | 21d7046bab28475c34145539fc74bd6e | 34.313131 | 119 | 0.643021 | 4.972973 | false | false | false | false |
apple/swift-numerics | Sources/ComplexModule/Complex+StringConvertible.swift | 1 | 788 | //===--- Complex+StringConvertible.swift ----------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Complex: CustomStringConvertible {
public var description: String {
guard isFinite else { return "inf" }
return "(\(x), \(y))"
}
}
extension Complex: CustomDebugStringConvertible {
public var debugDescription: String {
"Complex<\(RealType.self)>(\(String(reflecting: x)), \(String(reflecting: y)))"
}
}
| apache-2.0 | 41c8b58277b528d855788f1087335c65 | 33.26087 | 83 | 0.606599 | 4.89441 | false | false | false | false |
wjk930726/weibo | weiBo/weiBo/iPhone/Modules/Compose/EmotionKeyboard/WBEmotionTool.swift | 1 | 2581 | //
// WBEmotionTool.swift
// weiBo
//
// Created by 王靖凯 on 2016/12/6.
// Copyright © 2016年 王靖凯. All rights reserved.
//
import UIKit
class WBEmotionTool: NSObject {
static let shared = WBEmotionTool()
private var bundlePath: String {
return Bundle.main.path(forResource: "Emoticons", ofType: "bundle")!
}
/// 默认表情的地址
private var defaultPath: String {
return bundlePath + "/Contents/Resources/default/info.plist"
}
/// emoji表情的地址
private var emojiPath: String {
return bundlePath + "/Contents/Resources/emoji/info.plist"
}
/// emoji表情的地址
private var lxhPath: String {
return bundlePath + "/Contents/Resources/lxh/info.plist"
}
/// 根据path解析出表情的model
func parseEmotionModel(path: String) -> [WBEmotionModel] {
var array = [WBEmotionModel]()
if let dictArray = NSArray(contentsOfFile: path) {
for dict in dictArray {
guard let dictionary = dict as? [String: Any] else {
continue
}
let model = WBEmotionModel(dict: dictionary)
if model.type == 0 {
let folderPath = (path as NSString).deletingLastPathComponent
model.fullPath = "\(folderPath)/\(model.png!)"
}
array.append(model)
}
}
return array
}
/// 将表情model根据cell来分组
func devideEmotions(emotions: [WBEmotionModel]) -> [[WBEmotionModel]] {
var resultArray = [[WBEmotionModel]]()
let pageNum = (emotions.count - 1) / 20 + 1
for i in 0 ..< pageNum {
if i + 1 == pageNum {
let range = NSRange(location: i * 20, length: emotions.count - i * 20)
resultArray.append((emotions as NSArray).subarray(with: range) as! [WBEmotionModel])
} else {
let range = NSRange(location: i * 20, length: 20)
resultArray.append((emotions as NSArray).subarray(with: range) as! [WBEmotionModel])
}
}
return resultArray
}
func emotionsDataSource() -> [[[WBEmotionModel]]] {
return [
devideEmotions(emotions: parseEmotionModel(path: defaultPath)),
devideEmotions(emotions: parseEmotionModel(path: defaultPath)),
devideEmotions(emotions: parseEmotionModel(path: emojiPath)),
devideEmotions(emotions: parseEmotionModel(path: lxhPath)),
]
}
}
| mit | 1c5d9b897e698a9b293984c9ba63fb2d | 31.894737 | 100 | 0.5792 | 4.708098 | false | false | false | false |
piwik/piwik-sdk-ios | MatomoTracker/Event.swift | 1 | 5431 | import Foundation
import CoreGraphics
/// Represents an event of any kind.
///
/// - Todo:
/// - Add Action info
/// - Add Content Tracking info
///
/// # Key Mapping:
/// Most properties represent a key defined at: [Tracking HTTP API](https://developer.piwik.org/api-reference/tracking-api). Keys that are not supported for now are:
///
/// - idsite, rec, rand, apiv, res, cookie,
/// - All Plugins: fla, java, dir, qt, realp, pdf, wma, gears, ag
public struct Event: Codable {
public let uuid: UUID
let siteId: String
let visitor: Visitor
let session: Session
/// This flag defines if this event is a so called cutom action.
/// api-key: ca
/// More info: https://github.com/matomo-org/matomo-sdk-ios/issues/354
/// and https://github.com/matomo-org/matomo-sdk-ios/issues/363
let isCustomAction: Bool
/// The Date and Time the event occurred.
/// api-key: h, m, s
let date: Date
/// The full URL for the current action.
/// api-key: url
let url: URL?
/// api-key: action_name
let actionName: [String]
/// The language of the device.
/// Should be in the format of the Accept-Language HTTP header field.
/// api-key: lang
let language: String
/// Should be set to true for the first event of a session.
/// api-key: new_visit
let isNewSession: Bool
/// Currently only used for Campaigns
/// api-key: urlref
let referer: URL?
var screenResolution: CGSize = Device.makeCurrentDevice().screenSize
/// api-key: _cvar
let customVariables: [CustomVariable]
/// Event tracking
/// https://piwik.org/docs/event-tracking/
let eventCategory: String?
let eventAction: String?
let eventName: String?
let eventValue: Float?
/// Campaign tracking
/// https://matomo.org/docs/tracking-campaigns/
let campaignName: String?
let campaignKeyword: String?
/// Search tracking
/// api-keys: search, search_cat, search_count
let searchQuery: String?
let searchCategory: String?
let searchResultsCount: Int?
let dimensions: [CustomDimension]
let customTrackingParameters: [String:String]
/// Content tracking
/// https://matomo.org/docs/content-tracking/
let contentName: String?
let contentPiece: String?
let contentTarget: String?
let contentInteraction: String?
/// Goal tracking
/// https://matomo.org/docs/tracking-goals-web-analytics/
let goalId: Int?
let revenue: Float?
/// Ecommerce Order tracking
/// https://matomo.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required
let orderId: String?
let orderItems: [OrderItem]
let orderRevenue: Float?
let orderSubTotal: Float?
let orderTax: Float?
let orderShippingCost: Float?
let orderDiscount: Float?
let orderLastDate: Date?
}
extension Event {
public init(tracker: MatomoTracker, action: [String], url: URL? = nil, referer: URL? = nil, eventCategory: String? = nil, eventAction: String? = nil, eventName: String? = nil, eventValue: Float? = nil, customTrackingParameters: [String:String] = [:], searchQuery: String? = nil, searchCategory: String? = nil, searchResultsCount: Int? = nil, dimensions: [CustomDimension] = [], variables: [CustomVariable] = [], contentName: String? = nil, contentInteraction: String? = nil, contentPiece: String? = nil, contentTarget: String? = nil, goalId: Int? = nil, revenue: Float? = nil, orderId: String? = nil, orderItems: [OrderItem] = [], orderRevenue: Float? = nil, orderSubTotal: Float? = nil, orderTax: Float? = nil, orderShippingCost: Float? = nil, orderDiscount: Float? = nil, orderLastDate: Date? = nil, isCustomAction: Bool) {
self.siteId = tracker.siteId
self.uuid = UUID()
self.visitor = tracker.visitor
self.session = tracker.session
self.date = Date()
self.url = url ?? tracker.contentBase?.appendingPathComponent(action.joined(separator: "/"))
self.actionName = action
self.language = Locale.httpAcceptLanguage
self.isNewSession = tracker.nextEventStartsANewSession
self.referer = referer
self.eventCategory = eventCategory
self.eventAction = eventAction
self.eventName = eventName
self.eventValue = eventValue
self.searchQuery = searchQuery
self.searchCategory = searchCategory
self.searchResultsCount = searchResultsCount
self.dimensions = tracker.dimensions + dimensions
self.campaignName = tracker.campaignName
self.campaignKeyword = tracker.campaignKeyword
self.customTrackingParameters = customTrackingParameters
self.customVariables = tracker.customVariables + variables
self.contentName = contentName
self.contentPiece = contentPiece
self.contentTarget = contentTarget
self.contentInteraction = contentInteraction
self.goalId = goalId
self.revenue = revenue
self.orderId = orderId
self.orderItems = orderItems
self.orderRevenue = orderRevenue
self.orderSubTotal = orderSubTotal
self.orderTax = orderTax
self.orderShippingCost = orderShippingCost
self.orderDiscount = orderDiscount
self.orderLastDate = orderLastDate
self.isCustomAction = isCustomAction
}
}
| mit | fbad5a2bfcebdf64b6da906bedf874a0 | 37.51773 | 829 | 0.668938 | 4.249609 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.