repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
sarvex/SwiftRecepies | Notification/Sending Notifications/Sending Notifications/ViewController.swift | 1 | 1374 | //
// ViewController.swift
// Sending Notifications
//
// Created by Vandad Nahavandipoor on 7/11/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
class ViewController: UIViewController {
let notificationName = "NotificationNameGoesHere"
override func viewDidLoad() {
super.viewDidLoad()
let notification = NSNotification(name: notificationName,
object: self,
userInfo: [
"Key1" : "Value1",
"Key2" : 2]
)
NSNotificationCenter.defaultCenter().postNotification(notification)
}
}
| isc |
yangboz/SwiftSteeringBehavior | SwiftSteeringBehavors3/SwiftSteeringBehavors3Tests/SwiftSteeringBehavors3Tests.swift | 1 | 1036 | //
// SwiftSteeringBehavors3Tests.swift
// SwiftSteeringBehavors3Tests
//
// Created by yangboz on 12/04/2017.
// Copyright © 2017 ___SMARTKIT.INFO___. All rights reserved.
//
import XCTest
@testable import SwiftSteeringBehavors3
class SwiftSteeringBehavors3Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
alessiobrozzi/firefox-ios | UITests/ClearPrivateDataTests.swift | 1 | 12587 | /* 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
import EarlGrey
import GCDWebServers
class ClearPrivateDataTests: KIFTestCase, UITextFieldDelegate {
fileprivate var webRoot: String!
override func setUp() {
super.setUp()
webRoot = SimplePageServer.start()
BrowserUtils.dismissFirstRunUI()
}
override func tearDown() {
BrowserUtils.resetToAboutHome(tester())
BrowserUtils.clearPrivateData(tester: tester())
}
func visitSites(noOfSites: Int) -> [(title: String, domain: String, dispDomain: String, url: String)] {
var urls: [(title: String, domain: String, dispDomain: String, url: String)] = []
for pageNo in 1...noOfSites {
let url = "\(webRoot!)/numberedPage.html?page=\(pageNo)"
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityID("address"))
.perform(grey_typeText("\(url)\n"))
tester().waitForWebViewElementWithAccessibilityLabel("Page \(pageNo)")
let dom = URL(string: url)!.normalizedHost!
let index = dom.index(dom.startIndex, offsetBy: 7)
let dispDom = dom.substring(to: index) // On IPhone, it only displays first 8 chars
let tuple: (title: String, domain: String, dispDomain: String, url: String)
= ("Page \(pageNo)", dom, dispDom, url)
urls.append(tuple)
}
BrowserUtils.resetToAboutHome(tester())
return urls
}
func anyDomainsExistOnTopSites(_ domains: Set<String>, fulldomains: Set<String>) {
if checkDomains(domains: domains) == true {
return
} else {
if checkDomains(domains: fulldomains) == true {
return
}
}
XCTFail("Couldn't find any domains in top sites.")
}
private func checkDomains(domains: Set<String>) -> Bool {
var errorOrNil: NSError?
for domain in domains {
let withoutDot = domain.replacingOccurrences(of: ".", with: " ")
let matcher = grey_allOfMatchers([grey_accessibilityLabel(withoutDot),
grey_accessibilityID("TopSite"),
grey_sufficientlyVisible()])
EarlGrey.select(elementWithMatcher: matcher!).assert(grey_notNil(), error: &errorOrNil)
if errorOrNil == nil {
return true
}
}
return false
}
func testRemembersToggles() {
BrowserUtils.clearPrivateData([BrowserUtils.Clearable.History], swipe:false, tester: tester())
BrowserUtils.openClearPrivateDataDialog(false, tester: tester())
// Ensure the toggles match our settings.
[
(BrowserUtils.Clearable.Cache, "0"),
(BrowserUtils.Clearable.Cookies, "0"),
(BrowserUtils.Clearable.OfflineData, "0"),
(BrowserUtils.Clearable.History, "1")
].forEach { clearable, switchValue in
XCTAssertNotNil(tester()
.waitForView(withAccessibilityLabel: clearable.rawValue, value: switchValue, traits: UIAccessibilityTraitNone))
}
BrowserUtils.closeClearPrivateDataDialog(tester())
}
func testClearsTopSitesPanel() {
let urls = visitSites(noOfSites: 2)
let dispDomains = Set<String>(urls.map { $0.dispDomain })
let fullDomains = Set<String>(urls.map { $0.domain })
var errorOrNil: NSError?
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Top sites")).perform(grey_tap())
// Only one will be found -- we collapse by domain.
anyDomainsExistOnTopSites(dispDomains, fulldomains: fullDomains)
BrowserUtils.clearPrivateData([BrowserUtils.Clearable.History], swipe: false, tester: tester())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(urls[0].title))
.assert(grey_notNil(), error: &errorOrNil)
XCTAssertEqual(GREYInteractionErrorCode(rawValue: errorOrNil!.code),
GREYInteractionErrorCode.elementNotFoundErrorCode,
"Expected to have removed top site panel \(urls[0])")
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(urls[1].title))
.assert(grey_notNil(), error: &errorOrNil)
XCTAssertEqual(GREYInteractionErrorCode(rawValue: errorOrNil!.code),
GREYInteractionErrorCode.elementNotFoundErrorCode,
"We shouldn't find the other URL, either.")
}
func testDisabledHistoryDoesNotClearTopSitesPanel() {
let urls = visitSites(noOfSites: 2)
let dispDomains = Set<String>(urls.map { $0.dispDomain })
let fullDomains = Set<String>(urls.map { $0.domain })
anyDomainsExistOnTopSites(dispDomains, fulldomains: fullDomains)
BrowserUtils.clearPrivateData(BrowserUtils.AllClearables.subtracting([BrowserUtils.Clearable.History]), swipe: false, tester: tester())
anyDomainsExistOnTopSites(dispDomains, fulldomains: fullDomains)
}
func testClearsHistoryPanel() {
let urls = visitSites(noOfSites: 2)
var errorOrNil: NSError?
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("History")).perform(grey_tap())
let url1 = urls[0].url
let url2 = urls[1].url
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(url1)).assert(grey_notNil())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(url2)).assert(grey_notNil())
BrowserUtils.clearPrivateData([BrowserUtils.Clearable.History], swipe: false, tester: tester())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Bookmarks")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("History")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(url1))
.assert(grey_notNil(), error: &errorOrNil)
XCTAssertEqual(GREYInteractionErrorCode(rawValue: errorOrNil!.code),
GREYInteractionErrorCode.elementNotFoundErrorCode,
"Expected to have removed history row \(url1)")
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(url2))
.assert(grey_notNil(), error: &errorOrNil)
XCTAssertEqual(GREYInteractionErrorCode(rawValue: errorOrNil!.code),
GREYInteractionErrorCode.elementNotFoundErrorCode,
"Expected to have removed history row \(url2)")
}
func testDisabledHistoryDoesNotClearHistoryPanel() {
let urls = visitSites(noOfSites: 2)
var errorOrNil: NSError?
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("History")).perform(grey_tap())
let url1 = urls[0].url
let url2 = urls[1].url
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(url1)).assert(grey_notNil())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(url2)).assert(grey_notNil())
BrowserUtils.clearPrivateData(BrowserUtils.AllClearables.subtracting([BrowserUtils.Clearable.History]), swipe: false, tester: tester())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(url1))
.assert(grey_notNil(), error: &errorOrNil)
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(url2))
.assert(grey_notNil(), error: &errorOrNil)
}
func testClearsCookies() {
let url = "\(webRoot!)/numberedPage.html?page=1"
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityID("address"))
.perform(grey_typeText("\(url)\n"))
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
let webView = tester().waitForView(withAccessibilityLabel: "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.
BrowserUtils.clearPrivateData(BrowserUtils.AllClearables.subtracting([BrowserUtils.Clearable.Cookies]), swipe: true, tester: tester())
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.
BrowserUtils.clearPrivateData([BrowserUtils.Clearable.Cookies], swipe: true, tester: tester())
cookies = getCookies(webView)
XCTAssertEqual(cookies.cookie, "")
XCTAssertEqual(cookies.localStorage, "null")
XCTAssertEqual(cookies.sessionStorage, "null")
}
func testClearsCache() {
let cachedServer = CachedPageServer()
let cacheRoot = cachedServer.start()
let url = "\(cacheRoot)/cachedPage.html"
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityID("address"))
.perform(grey_typeText("\(url)\n"))
tester().waitForWebViewElementWithAccessibilityLabel("Cache test")
let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView
let requests = cachedServer.requests
// Verify that clearing non-cache items will keep the page in the cache.
BrowserUtils.clearPrivateData(BrowserUtils.AllClearables.subtracting([BrowserUtils.Clearable.Cache]), swipe: true, tester: tester())
webView.reload()
XCTAssertEqual(cachedServer.requests, requests)
// Verify that clearing the cache will fire a new request.
BrowserUtils.clearPrivateData([BrowserUtils.Clearable.Cache], swipe: true, tester: tester())
webView.reload()
XCTAssertEqual(cachedServer.requests, requests + 1)
}
fileprivate func setCookies(_ webView: WKWebView, cookie: String) {
let expectation = self.expectation(description: "Set cookie")
webView.evaluateJavaScript("document.cookie = \"\(cookie)\"; localStorage.cookie = \"\(cookie)\"; sessionStorage.cookie = \"\(cookie)\";") { result, _ in
expectation.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
}
fileprivate func getCookies(_ webView: WKWebView) -> (cookie: String, localStorage: String?, sessionStorage: String?) {
var cookie: (String, String?, String?)!
var value: String!
let expectation = self.expectation(description: "Got cookie")
webView.evaluateJavaScript("JSON.stringify([document.cookie, localStorage.cookie, sessionStorage.cookie])") { result, _ in
value = result as! String
expectation.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
value = value.replacingOccurrences(of: "[", with: "")
value = value.replacingOccurrences(of: "]", with: "")
value = value.replacingOccurrences(of: "\"", with: "")
let items = value.components(separatedBy: ",")
cookie = (items[0], items[1], items[2])
return cookie
}
}
/// Server that keeps track of requests.
private class CachedPageServer {
var requests = 0
func start() -> String {
let webServer = GCDWebServer()
webServer?.addHandler(forMethod: "GET", path: "/cachedPage.html", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
self.requests += 1
return GCDWebServerDataResponse(html: "<html><head><title>Cached page</title></head><body>Cache test</body></html>")
}
webServer?.start(withPort: 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 port = (webServer?.port)!
let webRoot = "http://127.0.0.1:\(port)"
return webRoot
}
}
| mpl-2.0 |
jestinson/weather | weatherTests/CacheTests.swift | 1 | 2834 | //
// CacheTests.swift
// weatherTests
//
// Created by Stinson, Justin on 8/9/15.
// Copyright © 2015 Justin Stinson. All rights reserved.
//
import XCTest
@testable import weather
class CacheTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testCacheNormalUsage() {
var cache = Cache<Int>(maximumNumberOfItems: 3)
XCTAssertEqual(cache.maxNumItems, 3)
XCTAssertEqual(cache.count, 0)
cache["a"] = 1
XCTAssertEqual(cache.count, 1)
XCTAssertEqual(cache["a"]!, 1)
cache["b"] = 2
XCTAssertEqual(cache.count, 2)
XCTAssertEqual(cache["b"]!, 2)
cache["c"] = 3
XCTAssertEqual(cache.count, 3)
XCTAssertEqual(cache["c"]!, 3)
cache["d"] = 4
XCTAssertEqual(cache.count, 3)
XCTAssertEqual(cache["d"]!, 4)
cache["e"] = 5
XCTAssertEqual(cache.count, 3)
XCTAssertEqual(cache["e"]!, 5)
XCTAssertEqual(cache["d"]!, 4)
XCTAssertEqual(cache["c"]!, 3)
XCTAssertNil(cache["b"])
XCTAssertNil(cache["a"])
cache["f"] = 6
XCTAssertEqual(cache.count, 3)
XCTAssertEqual(cache["d"]!, 4)
XCTAssertEqual(cache["c"]!, 3)
XCTAssertEqual(cache["f"]!, 6)
cache.removeAll()
XCTAssertEqual(cache.count, 0)
XCTAssertEqual(cache.maxNumItems, 3)
}
func testCacheNegativeMaxSize() {
var negativeCache = Cache<Double>(maximumNumberOfItems: -2)
XCTAssertEqual(negativeCache.maxNumItems, 1)
XCTAssertEqual(negativeCache.count, 0)
negativeCache["a"] = 1.0
XCTAssertEqual(negativeCache.count, 1)
negativeCache["b"] = 1.1
XCTAssertEqual(negativeCache.count, 1)
negativeCache.removeAll()
XCTAssertEqual(negativeCache.count, 0)
XCTAssertEqual(negativeCache.maxNumItems, 1)
}
func testCacheValueChange() {
var cache = Cache<String>(maximumNumberOfItems: 10)
XCTAssertEqual(cache.maxNumItems, 10)
XCTAssertEqual(cache.count, 0)
cache["A"] = "a"
XCTAssertEqual(cache.count, 1)
XCTAssertEqual(cache["A"]!, "a")
cache["B"] = "b"
XCTAssertEqual(cache.count, 2)
XCTAssertEqual(cache["B"]!, "b")
cache["B"] = "A"
XCTAssertEqual(cache.count, 2)
XCTAssertEqual(cache["B"]!, "A")
cache.removeAll()
XCTAssertEqual(cache.count, 0)
XCTAssertEqual(cache.maxNumItems, 10)
}
}
| mit |
GocePetrovski/ListCollectionViewKit | Demo/ListCollectionViewKitDemo/ListCollectionViewController.swift | 1 | 5545 | //
// ListCollectionViewController.swift
// ListCollectionViewDemo
//
// Created by Goce Petrovski on 11/02/2015.
// Copyright (c) 2015 Pomarium. All rights reserved.
//
import UIKit
import ListCollectionViewKit
class ListCollectionViewController: UICollectionViewController, ListCollectionViewDataSource {
var items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10", "Item 11", "Item 12", "Item 13", "Item 14", "Item 15", "Item 16", "Item 17", "Item 18", "Item 19", "Item 20"]
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.editButtonItem
self.collectionView?.register(UINib(nibName: "HeaderView", bundle: nil), forSupplementaryViewOfKind: ListCollectionViewElementKindGlobalHeader, withReuseIdentifier: globalHeaderId)
if let listLayout = collectionView?.collectionViewLayout as? ListCollectionViewFlowLayout {
listLayout.globalHeaderReferenceSize = CGSize(width: 320.0, height: 120.0)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let contentInset = collectionView!.contentInset
let width:CGFloat = (collectionView!.bounds).width - contentInset.left - contentInset.right
if let layout = collectionViewLayout as? UICollectionViewFlowLayout {
layout.itemSize = CGSize(width: width, height: 46.0)
}
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if let listLayout = collectionViewLayout as? ListCollectionViewFlowLayout {
listLayout.editing = editing
listLayout.invalidateLayout()
//collectionView?.reloadData()
}
}
/*
// 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.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ListCollectionViewCell
let item = items[(indexPath as NSIndexPath).row]
let label = cell.viewWithTag(5) as! UILabel
label.text = item
cell.accessoryType = ListCollectionViewCellAccessoryType.disclosureIndicator
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == ListCollectionViewElementKindGlobalHeader {
return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: globalHeaderId, for: indexPath)
}
return UICollectionReusableView();
}
// MARK: ListCollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, commitEditingStyle:ListCollectionViewCellEditingStyle, forRowAtIndexPath indexPath:IndexPath) {
items.remove(at: (indexPath as NSIndexPath).row)
collectionView.deleteItems(at: [indexPath])
}
// MARK: UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, accessoryButtonTappedForRowWithIndexPath indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
print("did select \(String(describing: cell?.contentView.subviews))")
}
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
}
| mit |
ebaker355/IBOutletScanner | src/Options.swift | 1 | 2516 | /*
MIT License
Copyright (c) 2017 DuneParkSoftware, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
public struct Options {
public let rootPath: String
public let customViewClassNames: [String]
private init(rootPath: String, customViewClassNames: [String]) {
self.rootPath = rootPath
self.customViewClassNames = customViewClassNames
}
private static var defaultRootPath: String? {
let environment = ProcessInfo.processInfo.environment
if let srcRoot = environment["SRCROOT"] {
return srcRoot
}
return nil
}
public static func createFromCommandLineArguments() -> Options {
var rootPath = Options.defaultRootPath ?? ""
var customViewClassNames: [String] = []
var isCustomViewClassNamesArg = false
for (index, arg) in CommandLine.arguments.enumerated() {
guard index > 0 else {
continue
}
guard !isCustomViewClassNamesArg else {
customViewClassNames.append(contentsOf: arg.components(separatedBy: ","))
isCustomViewClassNamesArg = false
continue
}
guard arg != "-customViewClassNames" && arg != "-customViewClassName" else {
isCustomViewClassNamesArg = true
continue
}
rootPath = arg
}
return Options(rootPath: rootPath, customViewClassNames: customViewClassNames)
}
}
| mit |
eugenepavlyuk/swift-algorithm-club | Trie/Trie/Trie/ViewController.swift | 4 | 455 | //
// ViewController.swift
// Trie
//
// Created by Rick Zaccone on 2016-12-12.
// Copyright © 2016 Rick Zaccone. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| mit |
fakerabbit/LucasBot | LucasBot/NavController.swift | 2 | 972 | //
// NavController.swift
// LucasBot
//
// Created by Mirko Justiniano on 1/16/17.
// Copyright © 2017 LB. All rights reserved.
//
import Foundation
import UIKit
class NavController: UINavigationController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
self.setNavigationBarHidden(true, animated: false)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
}
| gpl-3.0 |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Calling/CallInfoViewController/CallInfoViewController.swift | 1 | 8162 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
import WireSyncEngine
import WireCommonComponents
protocol CallInfoViewControllerDelegate: AnyObject {
func infoViewController(_ viewController: CallInfoViewController, perform action: CallAction)
}
protocol CallInfoViewControllerInput: CallActionsViewInputType, CallStatusViewInputType {
var accessoryType: CallInfoViewControllerAccessoryType { get }
var degradationState: CallDegradationState { get }
var videoPlaceholderState: CallVideoPlaceholderState { get }
var disableIdleTimer: Bool { get }
}
// Workaround to make the protocol equatable, it might be possible to conform CallInfoConfiguration
// to Equatable with Swift 4.1 and conditional conformances. Right now we would have to make
// the `CallInfoRootViewController` generic to work around the `Self` requirement of
// `Equatable` which we want to avoid.
extension CallInfoViewControllerInput {
func isEqual(toConfiguration other: CallInfoViewControllerInput) -> Bool {
return accessoryType == other.accessoryType &&
degradationState == other.degradationState &&
videoPlaceholderState == other.videoPlaceholderState &&
permissions == other.permissions &&
disableIdleTimer == other.disableIdleTimer &&
canToggleMediaType == other.canToggleMediaType &&
isMuted == other.isMuted &&
mediaState == other.mediaState &&
appearance == other.appearance &&
isVideoCall == other.isVideoCall &&
state == other.state &&
isConstantBitRate == other.isConstantBitRate &&
title == other.title &&
cameraType == other.cameraType &&
networkQuality == other.networkQuality &&
userEnabledCBR == other.userEnabledCBR &&
callState.isEqual(toCallState: other.callState) &&
videoGridPresentationMode == other.videoGridPresentationMode &&
allowPresentationModeUpdates == other.allowPresentationModeUpdates &&
isForcedCBR == other.isForcedCBR &&
classification == other.classification
}
}
final class CallInfoViewController: UIViewController, CallActionsViewDelegate, CallAccessoryViewControllerDelegate {
weak var delegate: CallInfoViewControllerDelegate?
private let backgroundViewController: BackgroundViewController
private let stackView = UIStackView(axis: .vertical)
private let statusViewController: CallStatusViewController
private let accessoryViewController: CallAccessoryViewController
private let actionsView = CallActionsView()
var configuration: CallInfoViewControllerInput {
didSet {
updateState()
}
}
init(configuration: CallInfoViewControllerInput,
selfUser: UserType,
userSession: ZMUserSession? = ZMUserSession.shared()) {
self.configuration = configuration
statusViewController = CallStatusViewController(configuration: configuration)
accessoryViewController = CallAccessoryViewController(configuration: configuration, selfUser: selfUser)
backgroundViewController = BackgroundViewController(user: selfUser, userSession: userSession)
super.init(nibName: nil, bundle: nil)
accessoryViewController.delegate = self
actionsView.delegate = self
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
createConstraints()
updateNavigationItem()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateState()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard traitCollection.didSizeClassChange(from: previousTraitCollection) else { return }
updateAccessoryView()
}
private func setupViews() {
addToSelf(backgroundViewController)
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
stackView.alignment = .center
stackView.distribution = .fill
stackView.spacing = 16
addChild(statusViewController)
[statusViewController.view, accessoryViewController.view, actionsView].forEach(stackView.addArrangedSubview)
statusViewController.didMove(toParent: self)
}
private func createConstraints() {
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
stackView.topAnchor.constraint(equalTo: safeTopAnchor),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
stackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuideOrFallback.bottomAnchor, constant: -25),
statusViewController.view.widthAnchor.constraint(equalTo: view.widthAnchor),
actionsView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
actionsView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
accessoryViewController.view.widthAnchor.constraint(equalTo: view.widthAnchor)
])
backgroundViewController.view.fitIn(view: view)
}
private func updateNavigationItem() {
let minimizeItem = UIBarButtonItem(
icon: .downArrow,
target: self,
action: #selector(minimizeCallOverlay)
)
minimizeItem.accessibilityLabel = "call.actions.label.minimize_call".localized
minimizeItem.accessibilityIdentifier = "CallDismissOverlayButton"
navigationItem.leftBarButtonItem = minimizeItem
}
private func updateAccessoryView() {
let isHidden = traitCollection.verticalSizeClass == .compact && !configuration.callState.isConnected
accessoryViewController.view.isHidden = isHidden
}
private func updateState() {
Log.calling.debug("updating info controller with state: \(configuration)")
actionsView.update(with: configuration)
statusViewController.configuration = configuration
accessoryViewController.configuration = configuration
backgroundViewController.view.isHidden = configuration.videoPlaceholderState == .hidden
updateAccessoryView()
if configuration.networkQuality.isNormal {
navigationItem.titleView = nil
} else {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.attributedText = configuration.networkQuality.attributedString(color: UIColor.nameColor(for: .brightOrange, variant: .light))
label.font = FontSpec(.small, .semibold).font
navigationItem.titleView = label
}
}
// MARK: - Actions + Delegates
@objc
private func minimizeCallOverlay(_ sender: UIBarButtonItem) {
delegate?.infoViewController(self, perform: .minimizeOverlay)
}
func callActionsView(_ callActionsView: CallActionsView, perform action: CallAction) {
delegate?.infoViewController(self, perform: action)
}
func callAccessoryViewControllerDidSelectShowMore(viewController: CallAccessoryViewController) {
delegate?.infoViewController(self, perform: .showParticipantsList)
}
}
| gpl-3.0 |
amieka/FlickStream | FlickStream/NSObject+Extensions.swift | 1 | 596 | //
// NSObject+Extensions.swift
// FlickStream
//
// Created by Arunoday Sarkar on 6/19/16.
// Copyright © 2016 Sark Software LLC. All rights reserved.
//
import Foundation
extension NSObject {
public func safe_setValuesForKeysWithDictionary(keyedValues: [String : AnyObject]) {
let properties = Mirror(reflecting: self)
for (property, value) in properties.children {
guard case let val? = keyedValues[property!] as AnyObject! else {
print("property not found, \(property as String!)")
continue
}
self.setValue(val, forKey: property as String!)
}
}
}
| mit |
jiayuquan/ShopCycle | ShopCycle/ShopCycle/Purchase/View/PurchaseCell.swift | 1 | 2176 | //
// PurchaseCell.swift
// shop
//
// Created by mac on 16/5/6.
// Copyright © 2016年 JiaYQ. All rights reserved.
//
import UIKit
protocol PurchaseCellDelegate: NSObjectProtocol {
func shoppingCartCell(cell: PurchaseCell, button: UIButton, countLabel: UILabel)
func reCalculateTotalPrice()
}
class PurchaseCell: UITableViewCell {
@IBOutlet weak var selectButton: UIButton!
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var newPriceLabel: UILabel!
@IBOutlet weak var oldPriceLabel: UILabel!
@IBOutlet weak var goodCountLabel: UILabel!
@IBOutlet weak var addAndsubtraction: UIButton!
@IBOutlet weak var subtractionButton: UIButton!
weak var delegate: PurchaseCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
iconView.layer.cornerRadius = 30
iconView.layer.masksToBounds = true
self.selectionStyle = UITableViewCellSelectionStyle.None
}
@IBAction func selectButtonClick(button: UIButton) {
// 选中
button.selected = !button.selected
goodModel?.isShopSelected = button.selected
delegate?.reCalculateTotalPrice()
}
@IBAction func addAndsubtractionClick(button: UIButton) {
delegate?.shoppingCartCell(self, button: button, countLabel: goodCountLabel)
}
@IBAction func subtractionButtonClick(button: UIButton) {
delegate?.shoppingCartCell(self, button: button, countLabel: goodCountLabel)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
var goodModel: DrawerCellModel? {
didSet {
selectButton.selected = goodModel!.isShopSelected
goodCountLabel.text = "\(goodModel!.count)"
iconView.image = UIImage(named: goodModel!.imageName!)
titleLabel.text = goodModel?.title
newPriceLabel.text = "\(goodModel!.newPrice!)"
oldPriceLabel.text = "\(goodModel!.oldPrice!)"
layoutIfNeeded()
}
}
}
| apache-2.0 |
toggl/superday | teferi/UI/Modules/Settings/SettingsPresenter.swift | 1 | 1076 | import Foundation
import UIKit
import StoreKit
class SettingsPresenter
{
private weak var viewController : SettingsViewController!
private let viewModelLocator : ViewModelLocator
private init(viewModelLocator: ViewModelLocator)
{
self.viewModelLocator = viewModelLocator
}
static func create(with viewModelLocator: ViewModelLocator) -> SettingsViewController
{
let presenter = SettingsPresenter(viewModelLocator: viewModelLocator)
let viewController = StoryboardScene.Settings.initialScene.instantiate()
viewController.inject(presenter: presenter, viewModel: viewModelLocator.getSettingsViewModel(forViewController: viewController))
presenter.viewController = viewController
return viewController
}
func showHelp()
{
UIApplication.shared.open(Constants.helpURL, options: [:], completionHandler: nil)
}
func requestReview()
{
UIApplication.shared.open(Constants.appStoreURL, options: [:], completionHandler: nil)
}
}
| bsd-3-clause |
lennet/proNotes | app/proNotes/Extenstions/UIStoryboardExtension.swift | 1 | 594 | //
// UIStoryboardExtension.swift
// proNotes
//
// Created by Leo Thomas on 09/12/15.
// Copyright © 2015 leonardthomas. All rights reserved.
//
import UIKit
extension UIStoryboard {
static func documentStoryboard() -> UIStoryboard {
let documentStoryboardName = "Document"
return UIStoryboard(name: documentStoryboardName, bundle: nil)
}
static func documentSettingsContainerStoryBoard() -> UIStoryboard {
let documentStoryboardName = "DocumentSettingsContainer"
return UIStoryboard(name: documentStoryboardName, bundle: nil)
}
}
| mit |
ArshAulakh59/TWGSampleApp | TWGSampleApp/CustomManagement/Utilities/Configuration.swift | 1 | 2999 | //
// Configuration.swift
// TWGSampleApp
//
// Created by Arsh Aulakh BHouse on 16/07/16.
// Copyright © 2016 BHouse. All rights reserved.
//
import UIKit
import Foundation
//MARK: Configuration
struct Configuration {
var mainThemeColor: UIColor
var secondaryThemeColor: UIColor
var onboardingConfiguration: OnboardingConfiguration
var galleryControllerConfiguration: GalleryConfiguration
var galleryCellConfiguration: GalleryCellConfiguration
var settingsConfiguration: SettingsConfiguration
//MARK: Initialisation
init(mainThemeColor: UIColor = Color.Green.values.color, secondaryThemeColor: UIColor = Color.White.values.color) {
self.mainThemeColor = mainThemeColor
self.secondaryThemeColor = secondaryThemeColor
self.onboardingConfiguration = OnboardingConfiguration(backgroundColor: secondaryThemeColor, labelsColor: mainThemeColor, buttonTextColor: mainThemeColor, buttonBackgroundColor: secondaryThemeColor, pageControlTintColor: mainThemeColor)
self.galleryControllerConfiguration = GalleryConfiguration(backgroundColor: secondaryThemeColor, navigationBarTintColor: secondaryThemeColor, navigationBarTextColor: mainThemeColor)
self.galleryCellConfiguration = GalleryCellConfiguration(captionLabelColor: mainThemeColor)
self.settingsConfiguration = SettingsConfiguration(backgroundColor: secondaryThemeColor, navigationBarTintColor: secondaryThemeColor, navigationBarTextColor: mainThemeColor, themeOneLabelColor: mainThemeColor, themeOneSegmentTintColor: mainThemeColor, themeTwoLabelColor: mainThemeColor, themeTwoSegmentTintColor: mainThemeColor)
}
init(mainThemeColor: UIColor, secondaryThemeColor: UIColor, onboardingConfiguration: OnboardingConfiguration, galleryControllerConfiguration: GalleryConfiguration, galleryCellConfiguration: GalleryCellConfiguration, settingsConfiguration: SettingsConfiguration) {
self.mainThemeColor = mainThemeColor
self.secondaryThemeColor = secondaryThemeColor
self.onboardingConfiguration = onboardingConfiguration
self.galleryControllerConfiguration = galleryControllerConfiguration
self.galleryCellConfiguration = galleryCellConfiguration
self.settingsConfiguration = settingsConfiguration
}
}
//MARK: Onboarding Configuration
struct OnboardingConfiguration {
var backgroundColor: UIColor
var labelsColor: UIColor
var buttonTextColor: UIColor
var buttonBackgroundColor: UIColor
var pageControlTintColor: UIColor
}
//MARK: Gallery Configuration
struct GalleryConfiguration {
var backgroundColor: UIColor
var navigationBarTintColor: UIColor
var navigationBarTextColor: UIColor
}
//MARK: Gallery Cell Configuration
struct GalleryCellConfiguration {
var captionLabelColor: UIColor
}
//MARK: Settings Configuration
struct SettingsConfiguration {
var backgroundColor: UIColor
var navigationBarTintColor: UIColor
var navigationBarTextColor: UIColor
var themeOneLabelColor: UIColor
var themeOneSegmentTintColor: UIColor
var themeTwoLabelColor: UIColor
var themeTwoSegmentTintColor: UIColor
} | mit |
neeemo/MobileComputingLab | ButterIt/ButterKnife.swift | 1 | 1244 | //
// Butter.swift
// Toast
//
// Created by James Wellence on 04/12/14.
// Copyright (c) 2014 James Wellence. All rights reserved.
//
import UIKit
class ButterKnife {
var butterAmount_: Double = 0
let maxButterAmount: Double = 1000
let minButterAmount: Double = 0
func setButter(butterAmount: Double){
butterAmount_ = butterAmount
}
//when scooping butter, adds the amount to the knife - returns maxButterAmount when knife can't hold more butter
func addButter(addButterAmount: Double) -> Double {
butterAmount_ = butterAmount_ + addButterAmount
if butterAmount_ > maxButterAmount {
butterAmount_ = maxButterAmount
}
return butterAmount_
}
//when spreading butter, removes the amount from the knife / returns minButterAmount (ie 0) when butter used up
func removeButter(removeButterAmount: Double) -> Double {
butterAmount_ = butterAmount_ - removeButterAmount
if butterAmount_ < minButterAmount {
butterAmount_ = minButterAmount
}
return butterAmount_
}
func getButterAmount() -> Double{
return butterAmount_
}
}
| apache-2.0 |
Awalz/ark-ios-monitor | ArkMonitor/Account Selection/AccountTransitionDelegate.swift | 1 | 3951 | // Copyright (c) 2016 Ark
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
class AccountTransitionDelegate: NSObject, UIViewControllerTransitioningDelegate {
var transitionContext: UIViewControllerContextTransitioning?
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return AccountTransitionAnimator()
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return AccountDismissTransitionAnimator()
}
}
class AccountTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning, CAAnimationDelegate {
var transitionContext: UIViewControllerContextTransitioning?
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.7
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let destinationController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let containerView = transitionContext.containerView as UIView
destinationController.view.alpha = 0.0
containerView.addSubview(destinationController.view)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveEaseInOut, animations: {
destinationController.view.alpha = 1.0
}) { (finished) in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if let transitionContext = self.transitionContext {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
class AccountDismissTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.7
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let destinationController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let containerView = transitionContext.containerView as UIView
destinationController.view.alpha = 0.0
containerView.addSubview(destinationController.view)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveEaseInOut, animations: {
destinationController.view.alpha = 1.0
}) { (finished) in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
| mit |
grandiere/box | box/Model/Help/Energy/MHelpEnergy.swift | 1 | 494 | import Foundation
class MHelpEnergy:MHelp
{
init()
{
let itemIntro:MHelpEnergyIntro = MHelpEnergyIntro()
let itemTime:MHelpEnergyTime = MHelpEnergyTime()
let itemAids:MHelpEnergyAids = MHelpEnergyAids()
let itemPurchase:MHelpEnergyPurchase = MHelpEnergyPurchase()
let items:[MHelpProtocol] = [
itemIntro,
itemTime,
itemAids,
itemPurchase]
super.init(items:items)
}
}
| mit |
zsheikh-systango/WordPower | Skeleton/Word Share/Network/APIManagers/RequestManager.swift | 1 | 915 | //
// RequestManager.swift
// WordPower
//
// Created by BestPeers on 05/06/17.
// Copyright © 2017 BestPeers. All rights reserved.
//
import UIKit
class RequestManager: NSObject {
// MARK: - Word API
func getWordInformation(word:String, completion:@escaping CompletionHandler){
WordInterface().getWordInformation(request: WordRequest().initWordRequest(word: word), completion: completion)
}
// MARK: - Traslation API
func getTranslationInformation(word:String, completion:@escaping CompletionHandler){
WordInterface().getTranslationInformation(request: WordRequest().initTranslatorRequest(word: word), completion: completion)
}
// MARK: - Traslation Languages API
func getLangsList(completion:@escaping CompletionHandler){
WordInterface().getTranslationLangs(request: WordRequest().initGetLangsRequest(), completion: completion)
}
}
| mit |
a2/Kitty | Kitty/ViewController.swift | 1 | 472 | //
// ViewController.swift
// Kitty
//
// Created by Alexsander Akers on 11/9/15.
// Copyright © 2015 Rocket Apps Limited. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
| mit |
krzyzanowskim/Natalie | Sources/natalie/Helpers.swift | 1 | 1655 | //
// Helpers.swift
// Natalie
//
// Created by Marcin Krzyzanowski on 07/08/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
func findStoryboards(rootPath: String, suffix: String) -> [String]? {
var result = [String]()
let fm = FileManager.default
if let paths = fm.subpaths(atPath: rootPath) {
let storyboardPaths = paths.filter({ return $0.hasSuffix(suffix)})
// result = storyboardPaths
for p in storyboardPaths {
result.append((rootPath as NSString).appendingPathComponent(p))
}
}
return result.isEmpty ? nil : result
}
enum FirstLetterFormat {
case none
case capitalize
case lowercase
func format(_ str: String) -> String {
switch self {
case .none:
return str
case .capitalize:
return String(str.uppercased().unicodeScalars.prefix(1) + str.unicodeScalars.suffix(str.unicodeScalars.count - 1))
case .lowercase:
return String(str.lowercased().unicodeScalars.prefix(1) + str.unicodeScalars.suffix(str.unicodeScalars.count - 1))
}
}
}
func swiftRepresentation(for string: String, firstLetter: FirstLetterFormat = .none, doNotShadow: String? = nil) -> String {
var str = string.trimAllWhitespacesAndSpecialCharacters()
str = firstLetter.format(str)
if str == doNotShadow {
str += "_"
}
return str
}
func initIdentifier(for identifierString: String, value: String) -> String {
if identifierString == "String" {
return "\"\(value)\""
} else {
return "\(identifierString)(\"\(value)\")"
}
}
| mit |
renzifeng/ZFZhiHuDaily | ZFZhiHuDaily/Other/Lib/CyclePictureView/CyclePictureCell.swift | 1 | 3259 | //
// CyclePictureCell.swift
// CyclePictureView
//
// Created by wl on 15/11/7.
// Copyright © 2015年 wl. All rights reserved.
//
import UIKit
import Kingfisher
class CyclePictureCell: UICollectionViewCell {
var imageSource: ImageSource = ImageSource.Local(name: ""){
didSet {
switch imageSource {
case let .Local(name):
self.imageView.image = UIImage(named: name)
case let .Network(urlStr):
self.imageView.kf_setImageWithURL(NSURL(string: urlStr)!, placeholderImage: placeholderImage)
}
}
}
var placeholderImage: UIImage?
var imageDetail: String? {
didSet {
detailLable.hidden = false
detailLable.text = imageDetail
}
}
var detailLableTextFont: UIFont = UIFont(name: "Helvetica-Bold", size: 18)! {
didSet {
detailLable.font = detailLableTextFont
}
}
var detailLableTextColor: UIColor = UIColor.whiteColor() {
didSet {
detailLable.textColor = detailLableTextColor
}
}
var detailLableBackgroundColor: UIColor = UIColor.clearColor() {
didSet {
detailLable.backgroundColor = detailLableBackgroundColor
}
}
var detailLableHeight: CGFloat = 60 {
didSet {
detailLable.frame.size.height = detailLableHeight
}
}
var detailLableAlpha: CGFloat = 1 {
didSet {
detailLable.alpha = detailLableAlpha
}
}
var pictureContentMode: UIViewContentMode = .ScaleAspectFill {
didSet {
imageView.contentMode = pictureContentMode
}
}
private var imageView: UIImageView!
private var detailLable: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
self.setupImageView()
self.setupDetailLable()
// self.backgroundColor = UIColor.grayColor()
}
private func setupImageView() {
imageView = UIImageView()
imageView.contentMode = pictureContentMode
imageView.clipsToBounds = true
self.addSubview(imageView)
}
private func setupDetailLable() {
detailLable = UILabel()
detailLable.textColor = detailLableTextColor
detailLable.shadowColor = UIColor.grayColor()
detailLable.numberOfLines = 0
detailLable.backgroundColor = detailLableBackgroundColor
detailLable.hidden = true //默认是没有描述的,所以隐藏它
self.addSubview(detailLable!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = self.bounds
if let _ = self.imageDetail {
let lableX: CGFloat = 20
let lableH: CGFloat = detailLableHeight
let lableW: CGFloat = self.frame.width - lableX
let lableY: CGFloat = self.frame.height - lableH
detailLable.frame = CGRectMake(lableX, lableY, lableW, lableH)
detailLable.font = detailLableTextFont
}
}
}
| apache-2.0 |
mmrmmlrr/ModelsTreeKit | JetPack/Subscription.swift | 1 | 1943 | //
// Disposable.swift
// SessionSwift
//
// Created by aleksey on 25.10.15.
// Copyright © 2015 aleksey chernish. All rights reserved.
//
import Foundation
protocol Invocable: class {
func invoke(_ data: Any) -> Void
func invokeState(_ data: Bool) -> Void
}
class Subscription<U> : Invocable, Disposable {
var handler: ((U) -> Void)?
var stateHandler: ((Bool) -> Void)?
private var signal: Signal<U>
private var deliversOnMainThread = false
private var autodisposes = false
init(handler: ((U) -> Void)?, signal: Signal<U>) {
self.handler = handler
self.signal = signal;
}
func invoke(_ data: Any) -> Void {
if deliversOnMainThread {
DispatchQueue.main.async { [weak self] in
self?.handler?(data as! U)
}
} else {
handler?(data as! U)
}
if autodisposes { dispose() }
}
func invokeState(_ data: Bool) -> Void {
if deliversOnMainThread {
DispatchQueue.main.async { [weak self] in
self?.stateHandler?(data)
}
} else {
stateHandler?(data)
}
}
func dispose() {
signal.nextHandlers = signal.nextHandlers.filter { $0 !== self }
signal.completedHandlers = signal.completedHandlers.filter { $0 !== self }
handler = nil
}
@discardableResult
func deliverOnMainThread() -> Disposable {
deliversOnMainThread = true
return self
}
@discardableResult
func autodispose() -> Disposable {
autodisposes = true
return self
}
@discardableResult
func putInto(_ pool: AutodisposePool) -> Disposable {
pool.add(self)
return self
}
@discardableResult
func takeUntil(_ signal: Pipe<Void>) -> Disposable {
signal.subscribeNext { [weak self] in
self?.dispose()
}.putInto(self.signal.pool)
return self
}
func ownedBy(_ object: DeinitObservable) -> Disposable {
return takeUntil(object.deinitSignal)
}
}
| mit |
tripleCC/GanHuoCode | GanHuo/Views/Base/TPCPageScrollView.swift | 1 | 10565 | //
// TPCPageScrollView.swift
// TPCPageScrollView
//
// Created by tripleCC on 15/11/23.
// Copyright © 2015年 tripleCC. All rights reserved.
//
import UIKit
class TPCPageScrollView: UIView {
let padding: CGFloat = 40
var viewDisappearAction: (() -> ())?
var imageMode: UIViewContentMode = UIViewContentMode.ScaleAspectFit {
didSet {
currentImageView.imageMode = imageMode
backupImageView.imageMode = imageMode
}
}
var imageURLStrings: [String]! {
didSet {
guard imageURLStrings.count > 0 else { return }
if imageURLStrings.count > 1 {
backupImageView.imageURLString = imageURLStrings[1]
backupImageView.tag = 1
} else {
scrollView.scrollEnabled = false
// 覆盖全屏手势
let pan = UIPanGestureRecognizer(target: self, action: nil)
currentImageView.addGestureRecognizer(pan)
}
currentImageView.imageURLString = imageURLStrings[0]
currentImageView.tag = 0
countLabel.text = "1 / \(imageURLStrings.count)"
}
}
private var scrollView: UIScrollView!
private var countLabel: UILabel!
var currentImageView: TPCImageView!
var backupImageView: TPCImageView!
var edgeMaskView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews()
}
func setupSubviews() {
scrollView = UIScrollView()
scrollView.pagingEnabled = true
scrollView.bounces = false
scrollView.delegate = self
scrollView.frame = bounds
scrollView.contentSize = CGSize(width: bounds.width * 3, height: 0)
scrollView.contentOffset = CGPoint(x: bounds.width, y: 0)
scrollView.showsHorizontalScrollIndicator = false
addSubview(scrollView)
currentImageView = TPCImageView(frame: CGRect(x: bounds.width, y: 0, width: bounds.width, height: bounds.height))
currentImageView.oneTapAction = { [unowned self] in
self.removeSelf()
}
currentImageView.longPressAction = { [unowned self] in
self.setupBottomToolView()
}
scrollView.addSubview(currentImageView)
backupImageView = TPCImageView(frame: CGRect(x: bounds.width * 2, y: 0, width: bounds.width, height: bounds.height))
backupImageView.oneTapAction = { [unowned self] in
self.removeSelf()
}
backupImageView.longPressAction = { [unowned self] in
self.setupBottomToolView()
}
scrollView.addSubview(backupImageView)
edgeMaskView = UIView(frame: CGRect(x: -padding, y: 0, width: padding, height: bounds.height))
edgeMaskView.backgroundColor = UIColor.blackColor()
addSubview(edgeMaskView)
setupGradientLayers()
countLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
countLabel.center = CGPoint(x: TPCScreenWidth * 0.5, y: 40)
countLabel.textAlignment = NSTextAlignment.Center
countLabel.font = TPCConfiguration.themeBFont
countLabel.textColor = UIColor.whiteColor()
addSubview(countLabel)
// setupBottomToolView()
}
private func setupGradientLayers() {
let gradientLayerH: CGFloat = 60
let topGradientLayer = CAGradientLayer()
topGradientLayer.colors = [UIColor.blackColor().CGColor, UIColor.clearColor().CGColor];
topGradientLayer.opacity = 0.5
topGradientLayer.frame = CGRect(x: 0, y: 0, width: bounds.width, height: gradientLayerH)
layer.addSublayer(topGradientLayer)
let bottomGradientLayer = CAGradientLayer()
bottomGradientLayer.colors = [UIColor.clearColor().CGColor, UIColor.blackColor().CGColor];
bottomGradientLayer.opacity = 0.5
bottomGradientLayer.frame = CGRect(x: 0, y: bounds.height - gradientLayerH, width: bounds.width, height: gradientLayerH)
layer.addSublayer(bottomGradientLayer)
}
private func setupBottomToolView() {
let alertVc = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
alertVc.addAction(UIAlertAction(title: "保存图片", style: .Default, handler: { (action) in
if let image = self.currentImageView.image {
TPCPhotoUtil.saveImage(image, completion: { (success) -> () in
self.imageDidFinishAuthorize(success: success)
})
}
}))
alertVc.addAction(UIAlertAction(title: "分享图片", style: .Default, handler: { (action) in
TPCShareView.showWithTitle(nil, desc: "干货", image: self.currentImageView.image)
}))
alertVc.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: { (action) in
// self.removeSelf()
}))
viewController?.presentViewController(alertVc, animated: true, completion: nil)
// let buttonWH: CGFloat = 30.0
// let backButtonX = TPCScreenWidth * 0.1
// let backButtonY = TPCScreenHeight - buttonWH * 1.5
// let backButton = TPCSystemButton(frame: CGRect(x: TPCScreenWidth - backButtonX - buttonWH, y: backButtonY, width: buttonWH, height: buttonWH))
// backButton.title = "关闭"
// backButton.animationCompletion = { [unowned self] (inout enable: Bool) in
// self.removeSelf()
// }
// addSubview(backButton)
//
// let saveButton = TPCSystemButton(frame: CGRect(x: TPCScreenWidth * 0.5 - buttonWH * 0.5, y: backButtonY, width: buttonWH, height: buttonWH))
// saveButton.title = "保存"
// saveButton.animationCompletion = { [unowned self] (inout enable: Bool) in
// debugPrint("保存")
// if let image = self.currentImageView.image {
// TPCPhotoUtil.saveImage(image, completion: { (success) -> () in
// self.imageDidFinishAuthorize(success: success)
// })
// }
// }
// addSubview(saveButton)
//
// let shareButton = TPCSystemButton(frame: CGRect(x: backButtonX, y: backButtonY, width: buttonWH, height: buttonWH))
// shareButton.title = "分享"
// shareButton.animationCompletion = { [unowned self] (inout enable: Bool) in
// TPCShareView.showWithTitle(nil, desc: "干货", image: self.currentImageView.image)
// }
// addSubview(shareButton)
}
func imageDidFinishAuthorize(success success: Bool) {
alpha = 0
let vc = UIApplication.sharedApplication().keyWindow!.rootViewController!
var ac: UIAlertController
func recoverActionInSeconds(seconds: NSTimeInterval) {
dispatchSeconds(seconds) {
self.alpha = 1
ac.dismissViewControllerAnimated(false, completion: {
vc.navigationController?.navigationBarHidden = false
ac.navigationController?.navigationBarHidden = false
})
}
}
if success {
ac = UIAlertController(title: "保存成功", message: "恭喜你!又新增一妹子!(。・`ω´・)", preferredStyle: .Alert)
} else {
ac = UIAlertController(title: "保存失败", message: "是否前往设置访问权限", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "确定", style: .Default, handler: { (action) -> Void in
recoverActionInSeconds(0.5)
let url = NSURL(string: UIApplicationOpenSettingsURLString)
if let url = url where UIApplication.sharedApplication().canOpenURL(url) {
UIApplication.sharedApplication().openURL(url)
}
}))
ac.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: { (action) -> Void in
recoverActionInSeconds(0)
}))
}
vc.presentViewController(ac, animated: false, completion: {
vc.navigationController?.navigationBarHidden = true
ac.navigationController?.navigationBarHidden = true
})
if ac.actions.count == 0 {
recoverActionInSeconds(1)
}
}
private func setupBackButton() {
let backButton = TPCSystemButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
addSubview(backButton)
}
private func removeSelf() {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.alpha = 0
self.viewDisappearAction?()
}) { (finished) -> Void in
self.removeFromSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSubviews()
}
}
extension TPCPageScrollView: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x
if offsetX < bounds.width {
edgeMaskView.frame.origin.x = padding / bounds.width * (bounds.width - offsetX) + bounds.width - offsetX - padding
backupImageView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height)
backupImageView.tag = (currentImageView.tag - 1 + imageURLStrings.count) % imageURLStrings.count
backupImageView.imageURLString = imageURLStrings[backupImageView.tag]
} else if offsetX > bounds.width {
edgeMaskView.frame.origin.x = padding / bounds.width * (bounds.width - offsetX) + 2 * bounds.width - offsetX
backupImageView.frame = CGRect(x: bounds.width * 2, y: 0, width: bounds.width, height: bounds.height)
backupImageView.tag = (currentImageView.tag + 1) % imageURLStrings.count
backupImageView.imageURLString = imageURLStrings[backupImageView.tag]
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x
scrollView.contentOffset.x = bounds.size.width
if offsetX < bounds.width * 1.5 && offsetX > bounds.width * 0.5 {
return
}
currentImageView.imageURLString = backupImageView.imageURLString
currentImageView.tag = backupImageView.tag
countLabel.text = "\(currentImageView.tag + 1) / \(imageURLStrings.count)"
}
} | mit |
ahoppen/swift | validation-test/Driver/Dependencies/rdar25405605.swift | 14 | 3185 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: cp %S/Inputs/rdar25405605/helper-1.swift %t/helper.swift
// RUN: touch -t 201401240005 %t/*.swift
// RUN: cd %t && %target-build-swift -c -incremental -output-file-map %S/Inputs/rdar25405605/output.json -parse-as-library ./main.swift ./helper.swift -parseable-output -j1 -module-name main 2>&1 | %FileCheck -check-prefix=CHECK-1 %s
// CHECK-1-NOT: warning
// CHECK-1: {{^{$}}
// CHECK-1-DAG: "kind"{{ ?}}: "began"
// CHECK-1-DAG: "name"{{ ?}}: "compile"
// CHECK-1-DAG: "{{(\.\\\/)?}}main.swift"
// CHECK-1: {{^}$}}
// CHECK-1: {{^{$}}
// CHECK-1-DAG: "kind"{{ ?}}: "began"
// CHECK-1-DAG: "name"{{ ?}}: "compile"
// CHECK-1-DAG: "{{(\.\\\/)?}}helper.swift"
// CHECK-1: {{^}$}}
// RUN: ls %t/ | %FileCheck -check-prefix=CHECK-LS %s
// CHECK-LS-DAG: main.o
// CHECK-LS-DAG: helper.o
// RUN: cd %t && %target-build-swift -c -incremental -output-file-map %S/Inputs/rdar25405605/output.json -parse-as-library ./main.swift ./helper.swift -parseable-output -j1 -module-name main 2>&1 | %FileCheck -check-prefix=CHECK-1-SKIPPED %s
// CHECK-1-SKIPPED-NOT: warning
// CHECK-1-SKIPPED: {{^{$}}
// CHECK-1-SKIPPED-DAG: "kind"{{ ?}}: "skipped"
// CHECK-1-SKIPPED-DAG: "name"{{ ?}}: "compile"
// CHECK-1-SKIPPED-DAG: "{{(\.\\\/)?}}main.swift"
// CHECK-1-SKIPPED: {{^}$}}
// CHECK-1-SKIPPED: {{^{$}}
// CHECK-1-SKIPPED-DAG: "kind"{{ ?}}: "skipped"
// CHECK-1-SKIPPED-DAG: "name"{{ ?}}: "compile"
// CHECK-1-SKIPPED-DAG: "{{(\.\\\/)?}}helper.swift"
// CHECK-1-SKIPPED: {{^}$}}
// RUN: cp %S/Inputs/rdar25405605/helper-2.swift %t/helper.swift
// RUN: touch -t 201401240006 %t/helper.swift
// RUN: cd %t && not %target-build-swift -c -incremental -output-file-map %S/Inputs/rdar25405605/output.json -parse-as-library ./main.swift ./helper.swift -parseable-output -j1 -module-name main 2>&1 | %FileCheck -check-prefix=CHECK-2 %s
// CHECK-2-NOT: warning
// CHECK-2: {{^{$}}
// CHECK-2-DAG: "kind"{{ ?}}: "began"
// CHECK-2-DAG: "name"{{ ?}}: "compile"
// CHECK-2-DAG: "{{(\.\\\/)?}}helper.swift"
// CHECK-2: {{^}$}}
// CHECK-2: {{^{$}}
// CHECK-2-DAG: "kind"{{ ?}}: "skipped"
// CHECK-2-DAG: "name"{{ ?}}: "compile"
// CHECK-2-DAG: "{{(\.\\\/)?}}main.swift"
// CHECK-2: {{^}$}}
// RUN: cp %S/Inputs/rdar25405605/helper-3.swift %t/helper.swift
// RUN: touch -t 201401240007 %t/helper.swift
// Driver now schedules jobs in the order of the inputs, so since this test wants
// helper first, pass helper.swift before main.swift
// RUN: cd %t && not %target-build-swift -c -incremental -output-file-map %S/Inputs/rdar25405605/output.json -parse-as-library ./helper.swift ./main.swift -parseable-output -j1 -module-name main 2>&1 | %FileCheck -check-prefix=CHECK-3 %s
// CHECK-3-NOT: warning
// CHECK-3: {{^{$}}
// CHECK-3-DAG: "kind"{{ ?}}: "began"
// CHECK-3-DAG: "name"{{ ?}}: "compile"
// CHECK-3-DAG: "{{(\.\\\/)?}}helper.swift"
// CHECK-3: {{^}$}}
// CHECK-3: {{^{$}}
// CHECK-3-DAG: "kind"{{ ?}}: "began"
// CHECK-3-DAG: "name"{{ ?}}: "compile"
// CHECK-3-DAG: "{{(\.\\\/)?}}main.swift"
// CHECK-3: {{^}$}}
func foo(_ value: Foo) -> Bool {
switch value {
case .one: return true
case .two: return false
}
}
| apache-2.0 |
megavolt605/CNLDataProvider | CNLDataProvider/CNLModelDictionary.swift | 1 | 4075 | //
// CNLModelDictionary.swift
// CNLDataProvider
//
// Created by Igor Smirnov on 23/12/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import Foundation
import CNLFoundationTools
/// Base dictionary model
public protocol CNLModelDictionary {
/// Default initializer
init()
/// Initializer with values from the dictionary
/// Calls loadFromDictionary(_:) by default
init?(dictionary: CNLDictionary?)
/// Loads (deserialize) values from the dictionary
///
/// - Parameter dictionary: Source dictionary
func loadFromDictionary(_ dictionary: CNLDictionary)
/// Stores (serialize) values to the dictionary
///
/// - Returns: Result dictionart
func storeToDictionary() -> CNLDictionary
/// Updates model values. By default, calls updateDictionary(success:failed:) with empty closures.
func updateDictionary()
/// Updates model values
/// By default, creates API struct instance returned by createAPI() function,
/// perform network request by CNLModel.networkProvider?.performRequest function.
/// When successed, try to deserialize values with loadFromDictionary(_:) function and invokes success callback.
/// Calls failed callback if any error occured during request
///
/// - Parameters:
/// - success: Callback when operation was successfull
/// - failed: Callback when operation was failed
func updateDictionary(success: @escaping CNLModel.Success, failed: @escaping CNLModel.Failed)
}
// MARK: - CNLModelObject
public extension CNLModelDictionary where Self: CNLModelObject {
/// Default implementation. Initializer with values from the dictionary
/// Calls loadFromDictionary(_:) by default
public init?(dictionary: CNLDictionary?) {
self.init()
if let data = dictionary {
loadFromDictionary(data)
} else {
return nil
}
}
/// Default implementation. Stub: does nothing.
///
/// - Parameter dictionary: Source dictionary
public func loadFromDictionary(_ dictionary: CNLDictionary) {
// dummy
}
/// Default implementation. Stub: returns empty dictionary
///
/// - Returns: Result dictionary
public func storeToDictionary() -> CNLDictionary {
return [:] // dummy
}
/// Default implementation. Calls updateDictionary(success:failed:) with empty closures.
public func updateDictionary() {
updateDictionary(success: { _, _ in }, failed: { _, _ in })
}
/// Default implementation. Updates model values
/// Creates API struct instance returned by createAPI() function,
/// perform network request by CNLModel.networkProvider?.performRequest function.
/// When successed, try to deserialize values with loadFromDictionary(_:) function and invokes success callback.
/// Calls failed callback if any error occured during request
///
/// - Parameters:
/// - success: Callback when operation was successfull
/// - failed: Callback when operation was failed
public func updateDictionary(success: @escaping CNLModel.Success, failed: @escaping CNLModel.Failed) {
if let localAPI = createAPI() {
CNLModel.networkProvider?.performRequest(
api: localAPI,
success: { apiObject in
if let json = apiObject.answerJSON {
self.loadFromDictionary(json)
}
success(self, apiObject.status)
},
fail: { (apiObject) in
failed(self, apiObject.errorStatus)
},
networkError: { apiObject, error in
failed(self, apiObject.errorStatus(error))
}
)
}
}
}
/// CNLModelDictionaryKeyStored: CNLModelDictionary protocol with CNLModelObjectPrimaryKey protocol requirements
public protocol CNLModelDictionaryKeyStored: CNLModelDictionary, CNLModelObjectPrimaryKey {
}
| mit |
nathanlea/CS4153MobileAppDev | WIA/WIA11_Lea_Nathan/WIA11_Lea_Nathan/TableViewController.swift | 1 | 5935 | //
// TableViewController.swift
// WIA11_Lea_Nathan
//
// Created by Nathan on 10/30/15.
// Copyright © 2015 Okstate. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
var elements: [Dictionary<String, String>] = []
override func viewDidLoad() {
super.viewDidLoad()
// Note that, beginning with iOS 9, we must use "HTTPS"
// rather than "HTTP".
let postEndpoint =
"https://cs.okstate.edu/~user/trains.php/user/password/dbname/fall15_trains"
// Set up the URL instance for the service.
guard let url = NSURL(string: postEndpoint) else {
print("Error: cannot create URL")
return
}
// Use the URL to set up a URL request.
let urlRequest = NSMutableURLRequest(URL: url)
urlRequest.HTTPMethod = "GET"
// We also need a URL session configuration instance.
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
// Now set up the URL session instance needed to make the call.
let session = NSURLSession(configuration: config)
// The method dataTaskWithRequest specifies a completion
// closure; it is invoked asynchronously when the call to
// the service returns.
let task = session.dataTaskWithRequest(urlRequest)
{ (data, response, error) in
// Check to see if any data was returned.
guard let resultData = data else {
print("Error: Did not receive data")
return
}
// Check to see if any error was encountered.
guard error == nil else {
print("Error making call")
print(error)
return
}
// Create a dictionary for the results
let result: NSArray
do {
// Attempt to turn the result into JSON data.
result =
try NSJSONSerialization.JSONObjectWithData(resultData,
options: []) as! NSArray
} catch {
print("Error trying to convert returned data to JSON")
return
}
self.elements = result as! [Dictionary<String, String>]
dispatch_sync(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
// Make the call to the service.
task.resume()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.elements.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("trains", forIndexPath: indexPath)
//print(self.elements[i]["number"])
cell.textLabel?.text=self.elements[indexPath.item]["roadName"]! + " " + self.elements[indexPath.item]["number"]!
cell.detailTextLabel?.text = self.elements[indexPath.item]["type"]!
// Configure the cell...
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
}
| mit |
tache/swiftkick | SwiftKickPlayground.playground/section-1.swift | 1 | 600 |
import SwiftKick
//-----------------------------------------------------------------------------------------------
// Logger
//-----------------------------------------------------------------------------------------------
// Set a log level to restrict output, and a verbosity of the output
let log = SwiftKick.Logger(.warn, verbosity:.default)
// print a lone at each logging level (some will get hidden based on logger initialization)
log.trace("TESTING TRACE")
log.debug("TESTING DEBUG")
log.info("TESTING INFO")
log.warn("TESTING WARN")
log.error("TESTING ERROR")
log.fatal("TESTING FATAL")
| mit |
KlubJagiellonski/pola-ios | BuyPolish/Pola/Utilities/Categories/Bundle+Additions.swift | 1 | 231 | import Foundation
extension Bundle {
var version: String! {
infoDictionary?["CFBundleVersion"] as? String
}
var shortVersion: String! {
infoDictionary?["CFBundleShortVersionString"] as? String
}
}
| gpl-2.0 |
liufan321/SwiftLearning | 基础语法/Swift基础语法.playground/Pages/002-可选项.xcplaygroundpage/Contents.swift | 1 | 1951 | import Foundation
/*:
## 概念
* `Optional` 是 Swift 的一大特色,也是 Swift 初学者最容易困惑的问题
* 定义变量时,在类型后面添加一个 `?`,表示该变量是可选的
* 定义变量时,如果指定是可选的,表示该变量:
* 可以有一个指定类型的值
* 也可以是 `nil`
## 定义
* 格式1(自动推导):`var 变量名: Optional = 值`
* 格式2(泛型):`var 变量名:Optional<类型> = 值`
* 格式3(简化格式):`var 变量名: 类型? = 值`
*/
// 格式1
let x: Optional = 20
// 格式2
let y: Optional<Int> = 30
// 格式3
let z: Int? = 10
print(x)
print(y)
print(z)
/*:
## 默认值
* 变量可选项的默认值是 `nil`
* 常量可选项没有默认值,需要在定义时,或者构造函数中赋值
*/
var x1: Int?
print(x1)
let x2: Int?
// 常量可选项没有默认值,在赋值之前不能使用
// print(x2)
x2 = 100
print(x2)
/*:
## 计算和强行解包
* 可选值在参与计算前,必须`解包 unwarping`
* 只有`解包(unwrap)`后才能参与计算
* 在可选项后添加一个 `!`,表示强行解包
* 如果有值,会取值,然后参与后续计算
* 如果为 `nil`,强行解包会导致崩溃
> 程序员要对每一个 `!` 负责
*/
print(x! + y! + z!)
/*:
## 可选解包
* 如果只是调用可选项的函数,而不需要参与计算,可以使用**可选解包**
* 在可选项后,使用 `?` 然后再调用函数
* 使用可选解包可以:
* 如果有值,会取值,然后执行后续函数
* 如果为 `nil`,不会执行任何函数
> 与强行解包对比,可选解包更安全,但是只能用于函数调用,而不能用于计算
*/
var optionValue: Int?
print(optionValue?.description)
// 输出 nil
optionValue = 10
print(optionValue?.description)
// 输出 Optional("10")
//: 有关本示例的许可信息,请参阅:[许可协议](License)
| apache-2.0 |
mominul/swiftup | Sources/swiftup/main.swift | 1 | 1476 | /*
swiftup
The Swift toolchain installer
Copyright (C) 2016-present swiftup Authors
Authors:
Muhammad Mominul Huque
*/
import libNix
import Commander
import Environment
import SwiftupFramework
let ver = "0.0.7"
Group {
$0.command("install",
Argument<String>("version"),
description: "Install specified version of toolchain"
) { version in
installToolchain(argument: version)
}
$0.command("show",
description: "Show the active and installed toolchains"
) {
let toolchains = Toolchains()
if let versions = toolchains.installedVersions() {
versions.forEach {
if $0 == toolchains.globalVersion {
print(" * \($0)", color: .cyan)
} else {
print(" \($0)", color: .cyan)
}
}
print("")
print(" * - Version currently in use")
} else {
print("No installed versions found!", color: .yellow)
}
}
$0.command("global",
Argument<String>("version"),
description: "Set the global toolchain version") { version in
var toolchain = Toolchains()
toolchain.globalVersion = version
}
$0.command("which",
Argument<String>("command"),
description: "Display which binary will be run for a given command") { command in
let toolchain = Toolchains()
print(toolchain.getBinaryPath().addingPath(command))
}
$0.command("version",
description: "Display swiftup version") {
print("swiftup \(ver)")
}
}.run()
| apache-2.0 |
PhillipEnglish/TIY-Assignments | TheGrailDiary/HistoricalSitesTableViewController.swift | 1 | 4704 | //
// HistoricalSitesTableViewController.swift
// TheGrailDiary
//
// Created by Phillip English on 10/19/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
class HistoricalSitesTableViewController: UITableViewController {
var temples = Array<Temple>()
override func viewDidLoad() {
super.viewDidLoad()
title = "Temples of Ancient Egypt"
loadTemples()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// #warning Incomplete implementation, return the number of rows
return temples.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TempleCell", forIndexPath: indexPath)
// Configure the cell...
let aTemple = temples[indexPath.row]
cell.textLabel?.text = aTemple.name
cell.detailTextLabel?.text = aTemple.deity
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
func loadTemples()
{
do
{
let filePath = NSBundle.mainBundle().pathForResource("temples", ofType: "json")
let dataFromFile = NSData(contentsOfFile: filePath!)
let templeData: NSArray! = try NSJSONSerialization.JSONObjectWithData(dataFromFile!, options: []) as! NSArray
for templeDictionary in templeData
{
let aTemple = Temple(dictionary: templeDictionary as! NSDictionary)
temples.append(aTemple)
}
temples.sortInPlace({ $0.name < $1.name})
}
catch let error as NSError
{
print(error)
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let aTemple = temples[indexPath.row]
let NVCfromTemplate = storyboard?.instantiateViewControllerWithIdentifier("TempleDetailViewController") as! TempleDetailViewController
NVCfromTemplate.temple = aTemple
presentViewController(NVCfromTemplate, animated: true, completion: nil)
}
}
| cc0-1.0 |
memexapp/memex-swift-sdk | Sources/RequestInvoker.swift | 1 | 8066 |
import Foundation
import ObjectMapper
class RequestInvoker {
// MARK: Lifecycle
weak var spaces: Spaces?
var session: URLSession
// MARK: Lifecycle
init(spaces: Spaces) {
self.spaces = spaces
self.session = URLSession(configuration: URLSessionConfiguration.default)
}
// MARK: General
func request(
method: HTTPMethod,
path: String,
queryStringParameters: [String: Any]? = nil,
bodyParameters: AnyObject? = nil,
headers: [String: String]? = nil,
allowDeauthorization: Bool? = nil,
completionHandler: @escaping RequestCompletion) {
do {
let request = try self.buildRequest(
method: method,
path: path,
queryStringParameters: queryStringParameters,
bodyParameters: bodyParameters,
headers: headers,
userToken: self.spaces!.auth.userToken)
self.invokeRequest(request: request,
allowDeauthorization: allowDeauthorization ?? self.spaces?.configuration.allowDeauthorization ?? false,
completionHandler: completionHandler)
} catch {
completionHandler(nil, nil, nil, MemexError.JSONParsingError)
}
}
private func buildRequest(
method: HTTPMethod,
path: String,
queryStringParameters: [String: Any]?,
bodyParameters: AnyObject?,
headers: [String: String]?,
userToken: String?) throws -> URLRequest {
let base = self.spaces!.configuration.serverURL.appendingPathComponent(path)
var path = "\(base.absoluteString)"
if let query = queryStringParameters, !query.isEmpty {
if let queryString = self.spaces!.queryStringTransformer.queryStringFromParameters(parameters: queryStringParameters,
error: nil) {
path = "\(path)?\(queryString)"
}
}
let url = URL(string: path)!
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
if let userToken = userToken {
request.setValue(userToken, forHTTPHeaderField: HTTPHeader.userToken)
}
request.setValue(self.spaces!.configuration.appToken, forHTTPHeaderField: HTTPHeader.appToken)
if let headers = headers {
for (key, value) in headers {
request.setValue(value, forHTTPHeaderField: key)
}
}
request.setValue(userToken, forHTTPHeaderField: HTTPHeader.userToken)
if let body = bodyParameters {
request.setValue(MIMETypes.JSON, forHTTPHeaderField: HTTPHeader.contentType)
let data = try JSONSerialization.data(withJSONObject: body, options: [])
request.httpBody = data
}
return request
}
private func invokeRequest(request: URLRequest,
allowDeauthorization: Bool,
completionHandler: @escaping RequestCompletion) {
var task: URLSessionTask!
task = self.session.dataTask(with: request) { (data, response, error) -> Void in
if error != nil {
self.logRequest(request: task.originalRequest ?? request,
response: response,
resposneData: data)
completionHandler(nil, nil, nil, error)
} else {
self.processResponseWithRequest(request: request,
response: response!,
data: data!,
allowDeauthorization: allowDeauthorization,
completionHandler: completionHandler)
}
}
task.resume()
}
private func processResponseWithRequest(
request: URLRequest,
response: URLResponse,
data: Data,
allowDeauthorization: Bool,
completionHandler: RequestCompletion) {
let httpResponse = response as! HTTPURLResponse
let code = httpResponse.statusCode
var printLog = false
switch code {
case 200..<300:
printLog = printLog || self.spaces!.configuration.logAllRequests
if data.count == 0 {
completionHandler(nil, code, httpResponse.allHeaderFields, nil)
} else {
var content: AnyObject?
do {
content = try JSONSerialization.jsonObject(with: data, options: []) as AnyObject?
} catch {
completionHandler(nil, code, httpResponse.allHeaderFields, MemexError.JSONParsingError)
return
}
completionHandler(content, code, httpResponse.allHeaderFields, nil)
}
default:
printLog = false
self.logRequest(request: request, response: response, resposneData: data)
self.processResponseErrorWithCode(code: code,
data: data,
allowDeauthorization: allowDeauthorization,
request: request,
completionHandler: completionHandler)
}
if printLog {
self.logRequest(request: request, response: response, resposneData: data)
}
}
private func processResponseErrorWithCode(
code: Int,
data: Data?,
allowDeauthorization: Bool,
request: URLRequest,
completionHandler: RequestCompletion) {
let errorPayload = self.errorPayloadFromData(data: data)
switch code {
case 400..<500:
var notAuthorized = false
if let errorPayload = errorPayload, let errorCode = errorPayload.code {
if errorCode == 401 {
notAuthorized = true
}
}
if code == 401 {
notAuthorized = true
}
if notAuthorized {
if allowDeauthorization {
let requestedToken = request.allHTTPHeaderFields?[HTTPHeader.userToken]
let currentToken = self.spaces!.auth.userToken
if requestedToken == currentToken {
self.spaces!.auth.deauthorize(completionHandler: { (error) in
if error != nil {
NSLog("Session invalidation failed")
}
})
}
}
completionHandler(nil, code, nil, MemexError.notAuthorized)
} else {
if code == 404 {
completionHandler(nil, code, nil, MemexError.endpointNotFound)
} else {
completionHandler(nil, code, nil, MemexError.genericClientError)
}
}
default:
if code == 503 {
self.spaces?.healthChecker.observedEnabledMaintanance()
completionHandler(nil, code, nil, MemexError.serverMaintanance)
} else {
completionHandler(nil, code, nil, MemexError.genericServerError)
}
}
}
private func errorPayloadFromData(data: Data?) -> ErrorPayload? {
do {
var errorMessage: ErrorPayload?
if let data = data {
let json: [String: Any]? =
try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
if let json = json, let errorDictionary = json["error"] {
errorMessage = Mapper<ErrorPayload>().map(JSONObject: errorDictionary)
}
}
return errorMessage
} catch {
return nil
}
}
func logRequest(request: URLRequest, response: URLResponse?, resposneData: Data?) {
var mutableRequest = request
if mutableRequest.allHTTPHeaderFields?[HTTPHeader.userToken] != nil {
mutableRequest.allHTTPHeaderFields?[HTTPHeader.userToken] = "<USER TOKEN>"
}
if mutableRequest.allHTTPHeaderFields?[HTTPHeader.appToken] != nil {
mutableRequest.allHTTPHeaderFields?[HTTPHeader.appToken] = "<APP TOKEN>"
}
if let httpResponse = response as? HTTPURLResponse, let data = resposneData {
let code = httpResponse.statusCode
var contentString = String(data: data, encoding: String.Encoding.utf8)
if contentString == nil {
contentString = "nil"
}
NSLog("\n\nREQUEST:\n\n\(mutableRequest.toCURL())\nRESPONSE:\n\nResponse Code: \(code)\nResponse Body:\n\(contentString!)\n\n-------------")
} else {
NSLog("\n\nREQUEST:\n\n\(mutableRequest.toCURL())")
}
}
}
| mit |
lucaslt89/simpsonizados | simpsonizados/Pods/Alamofire/Source/Request.swift | 49 | 19439 | // Request.swift
//
// Copyright (c) 2014–2016 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 Foundation
/**
Responsible for sending a request and receiving the response and associated data from the server, as well as
managing its underlying `NSURLSessionTask`.
*/
public class Request {
// MARK: - Properties
/// The delegate for the underlying task.
public let delegate: TaskDelegate
/// The underlying task.
public var task: NSURLSessionTask { return delegate.task }
/// The session belonging to the underlying task.
public let session: NSURLSession
/// The request sent or to be sent to the server.
public var request: NSURLRequest? { return task.originalRequest }
/// The response received from the server, if any.
public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
/// The progress of the request lifecycle.
public var progress: NSProgress { return delegate.progress }
// MARK: - Lifecycle
init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
switch task {
case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task)
default:
self.delegate = TaskDelegate(task: task)
}
}
// MARK: - Authentication
/**
Associates an HTTP Basic credential with the request.
- parameter user: The user.
- parameter password: The password.
- parameter persistence: The URL credential persistence. `.ForSession` by default.
- returns: The request.
*/
public func authenticate(
user user: String,
password: String,
persistence: NSURLCredentialPersistence = .ForSession)
-> Self
{
let credential = NSURLCredential(user: user, password: password, persistence: persistence)
return authenticate(usingCredential: credential)
}
/**
Associates a specified credential with the request.
- parameter credential: The credential.
- returns: The request.
*/
public func authenticate(usingCredential credential: NSURLCredential) -> Self {
delegate.credential = credential
return self
}
// MARK: - Progress
/**
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read
from the server.
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected
to write.
- For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes
expected to read.
- parameter closure: The code to be executed periodically during the lifecycle of the request.
- returns: The request.
*/
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataProgress = closure
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
/**
Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
This closure returns the bytes most recently received from the server, not including data from previous calls.
If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
also important to note that the `response` closure will be called with nil `responseData`.
- parameter closure: The code to be executed periodically during the lifecycle of the request.
- returns: The request.
*/
public func stream(closure: (NSData -> Void)? = nil) -> Self {
if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataStream = closure
}
return self
}
// MARK: - State
/**
Suspends the request.
*/
public func suspend() {
task.suspend()
}
/**
Resumes the request.
*/
public func resume() {
task.resume()
}
/**
Cancels the request.
*/
public func cancel() {
if let
downloadDelegate = delegate as? DownloadTaskDelegate,
downloadTask = downloadDelegate.downloadTask
{
downloadTask.cancelByProducingResumeData { data in
downloadDelegate.resumeData = data
}
} else {
task.cancel()
}
}
// MARK: - TaskDelegate
/**
The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
executing all operations attached to the serial operation queue upon task completion.
*/
public class TaskDelegate: NSObject {
/// The serial operation queue used to execute all operations after the task completes.
public let queue: NSOperationQueue
let task: NSURLSessionTask
let progress: NSProgress
var data: NSData? { return nil }
var error: NSError?
var credential: NSURLCredential?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
self.queue = {
let operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.suspended = true
if #available(OSX 10.10, *) {
operationQueue.qualityOfService = NSQualityOfService.Utility
}
return operationQueue
}()
}
deinit {
queue.cancelAllOperations()
queue.suspended = false
}
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
// MARK: Delegate Methods
func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
completionHandler: ((NSURLRequest?) -> Void))
{
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if let
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
disposition = .UseCredential
credential = NSURLCredential(forTrust: serverTrust)
} else {
disposition = .CancelAuthenticationChallenge
}
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
if credential != nil {
disposition = .UseCredential
}
}
}
completionHandler(disposition, credential)
}
func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
{
var bodyStream: NSInputStream?
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
bodyStream = taskNeedNewBodyStream(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let taskDidCompleteWithError = taskDidCompleteWithError {
taskDidCompleteWithError(session, task, error)
} else {
if let error = error {
self.error = error
if let
downloadDelegate = self as? DownloadTaskDelegate,
userInfo = error.userInfo as? [String: AnyObject],
resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData
{
downloadDelegate.resumeData = resumeData
}
}
queue.suspended = false
}
}
}
// MARK: - DataTaskDelegate
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask }
private var totalBytesReceived: Int64 = 0
private var mutableData: NSMutableData
override var data: NSData? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
private var expectedContentLength: Int64?
private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
private var dataStream: ((data: NSData) -> Void)?
override init(task: NSURLSessionTask) {
mutableData = NSMutableData()
super.init(task: task)
}
// MARK: - NSURLSessionDataDelegate
// MARK: Override Closures
var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
// MARK: Delegate Methods
func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
completionHandler: (NSURLSessionResponseDisposition -> Void))
{
var disposition: NSURLSessionResponseDisposition = .Allow
expectedContentLength = response.expectedContentLength
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
{
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data: data)
} else {
mutableData.appendData(data)
}
totalBytesReceived += data.length
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpected
progress.completedUnitCount = totalBytesReceived
dataProgress?(
bytesReceived: Int64(data.length),
totalBytesReceived: totalBytesReceived,
totalBytesExpectedToReceive: totalBytesExpected
)
}
}
func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: ((NSCachedURLResponse?) -> Void))
{
var cachedResponse: NSCachedURLResponse? = proposedResponse
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
// MARK: - CustomStringConvertible
extension Request: CustomStringConvertible {
/**
The textual representation used when written to an output stream, which includes the HTTP method and URL, as
well as the response status code if a response has been received.
*/
public var description: String {
var components: [String] = []
if let HTTPMethod = request?.HTTPMethod {
components.append(HTTPMethod)
}
if let URLString = request?.URL?.absoluteString {
components.append(URLString)
}
if let response = response {
components.append("(\(response.statusCode))")
}
return components.joinWithSeparator(" ")
}
}
// MARK: - CustomDebugStringConvertible
extension Request: CustomDebugStringConvertible {
func cURLRepresentation() -> String {
var components = ["$ curl -i"]
guard let
request = self.request,
URL = request.URL,
host = URL.host
else {
return "$ curl command could not be created"
}
if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" {
components.append("-X \(HTTPMethod)")
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(
host: host,
port: URL.port?.integerValue ?? 0,
`protocol`: URL.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values {
for credential in credentials {
components.append("-u \(credential.user!):\(credential.password!)")
}
} else {
if let credential = delegate.credential {
components.append("-u \(credential.user!):\(credential.password!)")
}
}
}
if session.configuration.HTTPShouldSetCookies {
if let
cookieStorage = session.configuration.HTTPCookieStorage,
cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty
{
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
if let headerFields = request.allHTTPHeaderFields {
for (field, value) in headerFields {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
for (field, value) in additionalHeaders {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if let
HTTPBodyData = request.HTTPBody,
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
{
let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(URL.absoluteString)\"")
return components.joinWithSeparator(" \\\n\t")
}
/// The textual representation used when written to an output stream, in the form of a cURL command.
public var debugDescription: String {
return cURLRepresentation()
}
}
| mit |
adrfer/swift | test/TypeCoercion/constructor_return.swift | 24 | 298 | // RUN: %target-parse-verify-swift
func foo() {}
func bar() {}
struct S {
init(b:Bool) {
foo()
if b { return }
bar()
}
}
class C {
var b:Bool
init(b:Bool) {
self.b = b
foo()
if b { return }
bar()
}
deinit {
foo()
if b { return }
bar()
}
}
| apache-2.0 |
adrfer/swift | validation-test/compiler_crashers_fixed/26007-swift-constraints-solution-computesubstitutions.swift | 13 | 277 | // 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
protocol A{
let:A{}func b
class d<e{struct d:A{var g=b{}func b
| apache-2.0 |
mmsaddam/TheMovie | TheMovie/ViewController.swift | 1 | 10965 | //
// ViewController.swift
// TheMovie
//
// Created by Md. Muzahidul Islam on 7/16/16.
// Copyright © 2016 iMuzahid. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
private let reuseIdentifier = "FlickrCell"
private let sectionInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
class ViewController: UIViewController {
// MARK: Outlet Properties
@IBOutlet var collectionView: UICollectionView!
@IBOutlet weak var segmentedControl: UISegmentedControl!
// MARK: Instance properties
let gridHieght = 300 // iamgeview height
let gridWidth = 180 // imageview width
let spacing = 10
var nowPlayingPageNo = 1
var topRatedPageNo = 1
var upcomingPageNo = 1
var refreshing = false
struct List {
static let NowPlaying = "Now"
static let TopRated = "Top"
static let Upcoming = "UP"
}
enum Action: Int {
case NowPlaying
case TopRated
case Upcoming
func getType() -> String {
switch self {
case .NowPlaying: return List.NowPlaying
case .TopRated: return List.TopRated
case .Upcoming: return List.Upcoming
}
}
}
// Movie List Dic: Under every key there will be an array
var movieList = [String:[Movie]]()
var selectedMovie: Movie? // movie tapped for details
var actionType = Action.NowPlaying
var imageDownloadInProgress = [NSIndexPath: IconDownloader]()
var pullUpInProgress = false
override func viewDidLoad() {
super.viewDidLoad()
self.title = "The Movie"
self.collectionView.delegate = self
self.collectionView.dataSource = self
// Initalize shared instance
LibAPI.sharedInstance
self.makeRequestForMovies()
}
// MARK: Helper function
// Get url string for movies
func getPageUrlStr() -> String{
var commonStr = ""
let pageNo = getPageIndex()
switch self.actionType {
case .NowPlaying:
commonStr += kNowPlaying
case .TopRated:
commonStr += kTopRated
case .Upcoming:
commonStr += kUpcoming
}
let finalStr = commonStr + String(pageNo)
return finalStr
}
// make reques for the movies
func makeRequestForMovies() {
let urlStr = getPageUrlStr()
self.beforeMakeRequestCompletion()
Alamofire.request(.GET, urlStr, parameters: nil)
.validate()
.responseData { response in
if let data = response.data{
self.afterRequestCompletionWithData(data)
}
}
}
// set up required before request for new movies
func beforeMakeRequestCompletion(){
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
footerControl(isHidden: false)
self.refreshing = true
}
// Made required change after completing request
func afterRequestCompletionWithData(data: NSData) {
if let movies = LibAPI.sharedInstance.parseJSON(data){
if let _ = self.movieList[self.actionType.getType()]{
self.movieList[self.actionType.getType()]! += movies
}else{
self.movieList[self.actionType.getType()] = movies
}
self.refreshing = false
footerControl(isHidden: true)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.collectionView?.reloadData()
self.incrementPageIndex()
}
}
// Get current page index to make new request
func getPageIndex() -> Int {
switch actionType {
case .NowPlaying: return nowPlayingPageNo
case .TopRated: return topRatedPageNo
default: return upcomingPageNo
}
}
// After downloading increment the index number
func incrementPageIndex() {
switch actionType {
case .NowPlaying: nowPlayingPageNo += 1
case .TopRated: topRatedPageNo += 1
default: upcomingPageNo += 1
}
}
// Download cover image for the movie
func startImageDownload(record: Movie, forIndexPath: NSIndexPath){
var iconDownloader = self.imageDownloadInProgress[forIndexPath]
if iconDownloader == nil{
iconDownloader = IconDownloader()
iconDownloader?.record = record
iconDownloader?.completionHandler = {
if let cell = self.collectionView.cellForItemAtIndexPath(forIndexPath) as? CustomCell{
dispatch_async(dispatch_get_main_queue(), {
cell.imageView.image = record.coverImage
cell.spinner.stopAnimating()
self.imageDownloadInProgress[forIndexPath] = nil
})
}
}
self.imageDownloadInProgress[forIndexPath] = iconDownloader
iconDownloader?.startDownload()
}
}
// MARK: Action
@IBAction func segmentedAction(sender: AnyObject) {
let segmentedControl = sender as! UISegmentedControl
self.actionType = Action(rawValue: segmentedControl.selectedSegmentIndex)!
if let _ = movieList[actionType.getType()]{
collectionView.reloadData()
}else{
self.makeRequestForMovies()
}
}
// Load image for the visible cell
func loadImageForVisibleCells() {
if let movies = self.movieList[actionType.getType()] where movies.count > 0{
let visiblePaths = collectionView.indexPathsForVisibleItems()
for path in visiblePaths{
let movie = movies[path.section + path.row]
if movie.coverImage == nil{
self.startImageDownload(movie, forIndexPath: path)
}
}
}
}
// 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?) {
if segue.identifier == "ShowDetails"{
let destinationVC = segue.destinationViewController as! DetailViewController
destinationVC.movie = self.selectedMovie
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: UICollectionView DataSource
extension ViewController: UICollectionViewDataSource{
// MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let list = self.movieList[self.actionType.getType()] where list.count > 0 {
return list.count
}else{
return 0
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CustomCell
if let movies = movieList[actionType.getType()] where movies.count > 0 {
let movie = movies[indexPath.section + indexPath.row]
// Configure the cell
if let image = movie.coverImage{
cell.imageView.image = image
cell.spinner.stopAnimating()
}else{
if !collectionView.decelerating && !collectionView.dragging{
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.startImageDownload(movie, forIndexPath: indexPath)
})
}
// Set default image until cover image dowload completed
cell.imageView.image = UIImage(named: "emptyCell")
}
}
return cell
}
}
// MARK: UICollectionView Delegate
extension ViewController: UICollectionViewDelegate{
// Tap on the cell
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if !collectionView.decelerating && !collectionView.dragging {
let movie = movieList[actionType.getType()]![indexPath.section + indexPath.row]
self.selectedMovie = movie
dispatch_async(dispatch_get_main_queue(), {
self.performSegueWithIdentifier("ShowDetails", sender: nil)
})
}
}
// Set Footer
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionFooter{
let footer = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer", forIndexPath: indexPath) as! FooterCell
footer.hidden = true
if pullUpInProgress {
return footer
}else{
return footer
}
}else{
return UICollectionReusableView()
}
}
// Cell Size cofigure
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let size = self.view.bounds.size
return CGSize(width: CGFloat(size.width / 2) - 10, height: 250)
}
// Set Cell EdgeInset
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return sectionInsets
}
}
// MARK: ScrollView Delegate
extension ViewController: UIScrollViewDelegate{
// This behavior start when user start dragging...
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
let currentOffsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
let scrollViewHeight = scrollView.frame.size.height
if (currentOffsetY + scrollViewHeight) >= contentHeight {
pullUpInProgress = true
}else{
pullUpInProgress = false
}
if pullUpInProgress{
print("Start pull down process")
}else{
}
}
// Scroll continuing...
func scrollViewDidScroll(scrollView: UIScrollView) {
let currentOffsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
let scrollViewHeight = scrollView.frame.size.height
if pullUpInProgress && ((currentOffsetY + scrollViewHeight) >= contentHeight) {
// check the user scrolling satisfy the condition
if (currentOffsetY + scrollViewHeight) > (contentHeight + 40) {
//print("release to add")
}else{
//print("pull to add")
}
}else{
pullUpInProgress = false
}
}
// When scrollview stop, Download images for visible cell
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
loadImageForVisibleCells()
}
// User stop dragging
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let currentOffsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
let scrollViewHeight = scrollView.frame.size.height
// check whether the user pull up enough
if (currentOffsetY + scrollViewHeight) > (contentHeight + 40) {
self.makeRequestForMovies()
}else{
}
loadImageForVisibleCells()
}
// make footer visible when start laod new page
func footerControl(isHidden isHide: Bool) {
for view in collectionView.subviews{
if view.isKindOfClass(FooterCell){
view.hidden = isHide
}
}
}
}
| mit |
GaborWnuk/image-preview-ios-demo | ImagePreviewExample/Article.swift | 1 | 1286 | //
// Article.swift
// ImagePreviewExample
//
// MIT License
//
// Copyright (c) 2016 Gabor Wnuk
//
// 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
struct Article {
var title: String?
var img: ArticleWebAsset?
}
| mit |
1aurabrown/eidolon | Kiosk/Admin/AdminPanelViewController.swift | 1 | 2105 | import UIKit
class AdminPanelViewController: UIViewController {
@IBOutlet weak var auctionIDLabel: UILabel!
@IBAction func backTapped(sender: AnyObject) {
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func closeAppTapped(sender: AnyObject) {
exit(1)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// TODO: Show help button
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue == .LoadAdminWebViewController {
let webVC = segue.destinationViewController as AuctionWebViewController
let auctionID = AppSetup.sharedState.auctionID
let base = AppSetup.sharedState.useStaging ? "staging.artsy.net" : "artsy.net"
webVC.URL = NSURL(string: "https://\(base)/feature/\(auctionID)")!
// TODO: Hide help button
}
}
override func viewDidLoad() {
super.viewDidLoad()
let state = AppSetup.sharedState
auctionIDLabel.text = state.auctionID
let environment = state.useStaging ? "PRODUCTION" : "STAGING"
environmentChangeButton.setTitle("USE \(environment)", forState: .Normal)
let buttonsTitle = state.showDebugButtons ? "HIDE" : "SHOW"
showAdminButtonsButton.setTitle(buttonsTitle, forState: .Normal)
}
@IBOutlet weak var environmentChangeButton: ActionButton!
@IBAction func switchStagingProductionTapped(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(!AppSetup.sharedState.useStaging, forKey: "KioskUseStaging")
defaults.synchronize()
exit(1)
}
@IBOutlet weak var showAdminButtonsButton: ActionButton!
@IBAction func toggleAdminButtons(sender: ActionButton) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(!AppSetup.sharedState.showDebugButtons, forKey: "KioskShowDebugButtons")
defaults.synchronize()
exit(1)
}
}
| mit |
fizx/jane | ruby/lib/vendor/grpc-swift/Tests/SwiftGRPCTests/ChannelArgumentTests.swift | 3 | 3570 | /*
* Copyright 2018, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if SWIFT_PACKAGE
import CgRPC
#endif
import Foundation
@testable import SwiftGRPC
import XCTest
fileprivate class ChannelArgumentTestProvider: Echo_EchoProvider {
func get(request: Echo_EchoRequest, session: Echo_EchoGetSession) throws -> Echo_EchoResponse {
// We simply return the user agent we received, which can then be inspected by the test code.
return Echo_EchoResponse(text: (session as! ServerSessionBase).handler.requestMetadata["user-agent"]!)
}
func expand(request: Echo_EchoRequest, session: Echo_EchoExpandSession) throws -> ServerStatus? {
fatalError("not implemented")
}
func collect(session: Echo_EchoCollectSession) throws -> Echo_EchoResponse? {
fatalError("not implemented")
}
func update(session: Echo_EchoUpdateSession) throws -> ServerStatus? {
fatalError("not implemented")
}
}
class ChannelArgumentTests: BasicEchoTestCase {
static var allTests: [(String, (ChannelArgumentTests) -> () throws -> Void)] {
return [
("testArgumentKey", testArgumentKey),
("testStringArgument", testStringArgument),
("testIntegerArgument", testIntegerArgument),
("testBoolArgument", testBoolArgument),
("testTimeIntervalArgument", testTimeIntervalArgument),
]
}
fileprivate func makeClient(_ arguments: [Channel.Argument]) -> Echo_EchoServiceClient {
let client = Echo_EchoServiceClient(address: address, secure: false, arguments: arguments)
client.timeout = defaultTimeout
return client
}
override func makeProvider() -> Echo_EchoProvider { return ChannelArgumentTestProvider() }
}
extension ChannelArgumentTests {
func testArgumentKey() {
let argument = Channel.Argument.defaultAuthority("default")
XCTAssertEqual(String(cString: argument.toCArg().wrapped.key), "grpc.default_authority")
}
func testStringArgument() {
let argument = Channel.Argument.primaryUserAgent("Primary/0.1")
XCTAssertEqual(String(cString: argument.toCArg().wrapped.value.string), "Primary/0.1")
}
func testIntegerArgument() {
let argument = Channel.Argument.http2MaxPingsWithoutData(5)
XCTAssertEqual(argument.toCArg().wrapped.value.integer, 5)
}
func testBoolArgument() {
let argument = Channel.Argument.keepAlivePermitWithoutCalls(true)
XCTAssertEqual(argument.toCArg().wrapped.value.integer, 1)
}
func testTimeIntervalArgument() {
let argument = Channel.Argument.keepAliveTime(2.5)
XCTAssertEqual(argument.toCArg().wrapped.value.integer, 2500) // in ms
}
}
extension ChannelArgumentTests {
func testPracticalUse() {
let client = makeClient([.primaryUserAgent("FOO"), .secondaryUserAgent("BAR")])
let responseText = try! client.get(Echo_EchoRequest(text: "")).text
XCTAssertTrue(responseText.hasPrefix("FOO "), "user agent \(responseText) should begin with 'FOO '")
XCTAssertTrue(responseText.hasSuffix(" BAR"), "user agent \(responseText) should end with ' BAR'")
}
}
| mit |
iAugux/Augus | Settings/TodayViewController+Apps.swift | 1 | 3873 | //
// TodayViewController+Apps.swift
// Augus
//
// Created by Augus on 2/24/16.
// Copyright © 2016 iAugus. All rights reserved.
//
import UIKit
// MARK: - MacID
extension TodayViewController {
internal func configureMacIDPanel() {
macIDClipboardButton.setImageForMacIDButton(UIColor.yellowColor())
macIDWakeButton.setImageForMacIDButton(UIColor.greenColor())
macIDClipboardButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(TodayViewController.openMacID)))
macIDWakeButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(TodayViewController.openMacID)))
macIDLockButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(TodayViewController.openMacID)))
}
@IBAction func macIDSendClipboard(sender: AnyObject) {
openSettingWithURL(AppsURL.MacIDClipboard.scheme)
}
@IBAction func macIDLock(sender: AnyObject) {
openSettingWithURL(AppsURL.MacIDLock.scheme)
}
@IBAction func macIDWake(sender: AnyObject) {
openSettingWithURL(AppsURL.MacIDWake.scheme)
}
internal func openMacID() {
openSettingWithURL(AppsURL.MacID.scheme)
}
private func image(named: String) -> UIImage? {
return UIImage(named: "mac_id")?.imageWithRenderingMode(.AlwaysTemplate)
}
}
// MARK: - Surge
let kSurgeAutoClose = "kSurgeAutoClose"
let kSurgeAutoCloseDefaultBool = true
extension TodayViewController {
internal func configureSurgePanel() {
surgeAutoCloseSwitch.transform = CGAffineTransformMakeScale(0.55, 0.55)
let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(surgeToggleDidLongPress(_:)))
surgeButton?.addGestureRecognizer(recognizer)
}
internal func surgeToggleDidLongPress(sender: UILongPressGestureRecognizer) {
guard sender.state == .Began else { return }
let url = surgeAutoCloseSwitch.on ? AppsURL.SurgeAutoClose.scheme : AppsURL.SurgeToggle.scheme
openSettingWithURL(url)
}
@IBAction func surgeAutoCloseSwitchDidTap(sender: UISwitch) {
NSUserDefaults.standardUserDefaults().setBool(sender.on, forKey: kSurgeAutoClose)
NSUserDefaults.standardUserDefaults().synchronize()
}
@IBAction func surgeToggleDidTap(sender: AnyObject) {
let url = AppsURL.Surge.scheme
openSettingWithURL(url)
}
}
// MARK: -
extension TodayViewController {
@IBAction func open1Password(sender: AnyObject) {
openSettingWithURL(AppsURL.OnePassword.scheme)
}
@IBAction func openOTPAuth(sender: AnyObject) {
openSettingWithURL(AppsURL.OTPAuth.scheme)
}
@IBAction func openDuetDisplay(sender: AnyObject) {
openSettingWithURL(AppsURL.Duet.scheme)
}
@IBAction func openReminders(sender: AnyObject) {
openSettingWithURL(AppsURL.Reminders.scheme)
}
@IBAction func openNotes(sender: AnyObject) {
openSettingWithURL(AppsURL.Notes.scheme)
}
}
extension TodayViewController {
@IBAction func openTumblr(sender: AnyObject) {
openSettingWithURL(AppsURL.Tumblr.scheme)
}
}
extension UIButton {
private func setImageForMacIDButton(tintColor: UIColor) {
setImage("mac_id", tintColor: tintColor)
}
private func setImage(named: String, tintColor: UIColor) {
imageView?.tintColor = tintColor
imageView?.layer.cornerRadius = imageView!.bounds.width / 2
imageView?.layer.borderWidth = 1.5
imageView?.layer.borderColor = UIColor.whiteColor().CGColor
setImage(UIImage(named: named)?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
}
} | mit |
noppoMan/aws-sdk-swift | Sources/Soto/Services/Athena/Athena_Error.swift | 1 | 2951 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for Athena
public struct AthenaErrorType: AWSErrorType {
enum Code: String {
case internalServerException = "InternalServerException"
case invalidRequestException = "InvalidRequestException"
case metadataException = "MetadataException"
case resourceNotFoundException = "ResourceNotFoundException"
case tooManyRequestsException = "TooManyRequestsException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize Athena
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// Indicates a platform issue, which may be due to a transient condition or outage.
public static var internalServerException: Self { .init(.internalServerException) }
/// Indicates that something is wrong with the input to the request. For example, a required parameter may be missing or out of range.
public static var invalidRequestException: Self { .init(.invalidRequestException) }
/// An exception that Athena received when it called a custom metastore. Occurs if the error is not caused by user input (InvalidRequestException) or from the Athena platform (InternalServerException). For example, if a user-created Lambda function is missing permissions, the Lambda 4XX exception is returned in a MetadataException.
public static var metadataException: Self { .init(.metadataException) }
/// A resource, such as a workgroup, was not found.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
/// Indicates that the request was throttled.
public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) }
}
extension AthenaErrorType: Equatable {
public static func == (lhs: AthenaErrorType, rhs: AthenaErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension AthenaErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 |
banxi1988/BXWebAppViewController | Example/Tests/Tests.swift | 1 | 777 | import UIKit
import XCTest
import BXWebAppViewController
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/00917-swift-lexer-leximpl.swift | 11 | 269 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
init(){->{
func g{{
}
func b({
{
{{
{
{
(((
(
[{
{
{
"""
}
}
}
protocol A{
typealias B:b
typealias b | mit |
radex/swift-compiler-crashes | crashes-fuzzing/02098-llvm-smallvectorimpl-swift-diagnosticargument-operator.swift | 11 | 216 | // 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 b=B()?->
class A<T where h:H{
typealias e=e | mit |
apple/swift-algorithms | Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift | 1 | 2580 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2021 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
//
//===----------------------------------------------------------------------===//
import XCTest
import Algorithms
final class AdjacentPairsTests: XCTestCase {
func testEmptySequence() {
let pairs = (0...).prefix(0).adjacentPairs()
XCTAssertEqualSequences(pairs, [], by: ==)
}
func testOneElementSequence() {
let pairs = (0...).prefix(1).adjacentPairs()
XCTAssertEqualSequences(pairs, [], by: ==)
}
func testTwoElementSequence() {
let pairs = (0...).prefix(2).adjacentPairs()
XCTAssertEqualSequences(pairs, [(0, 1)], by: ==)
}
func testThreeElementSequence() {
let pairs = (0...).prefix(3).adjacentPairs()
XCTAssertEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
}
func testManySequences() {
for n in 4...100 {
let pairs = (0...).prefix(n).adjacentPairs()
XCTAssertEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
}
}
func testZeroElements() {
let pairs = (0..<0).adjacentPairs()
XCTAssertEqual(pairs.startIndex, pairs.endIndex)
XCTAssertEqualSequences(pairs, [], by: ==)
}
func testOneElement() {
let pairs = (0..<1).adjacentPairs()
XCTAssertEqual(pairs.startIndex, pairs.endIndex)
XCTAssertEqualSequences(pairs, [], by: ==)
}
func testTwoElements() {
let pairs = (0..<2).adjacentPairs()
XCTAssertEqualSequences(pairs, [(0, 1)], by: ==)
}
func testThreeElements() {
let pairs = (0..<3).adjacentPairs()
XCTAssertEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
}
func testManyElements() {
for n in 4...100 {
let pairs = (0..<n).adjacentPairs()
XCTAssertEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
}
}
func testIndexTraversals() {
let validator = IndexValidator<AdjacentPairsCollection<Range<Int>>>()
validator.validate((0..<0).adjacentPairs(), expectedCount: 0)
validator.validate((0..<1).adjacentPairs(), expectedCount: 0)
validator.validate((0..<2).adjacentPairs(), expectedCount: 1)
validator.validate((0..<5).adjacentPairs(), expectedCount: 4)
}
func testLaziness() {
XCTAssertLazySequence((0...).lazy.adjacentPairs())
XCTAssertLazyCollection((0..<100).lazy.adjacentPairs())
}
}
| apache-2.0 |
rokuz/omim | iphone/Maps/Core/Ads/Mopub/MopubBanner.swift | 1 | 5041 | final class MopubBanner: NSObject, Banner {
private enum Limits {
static let minTimeOnScreen: TimeInterval = 3
static let minTimeSinceLastRequest: TimeInterval = 5
}
fileprivate var success: Banner.Success!
fileprivate var failure: Banner.Failure!
fileprivate var click: Banner.Click!
private var requestDate: Date?
private var showDate: Date?
private var remainingTime = Limits.minTimeOnScreen
private let placementID: String
func reload(success: @escaping Banner.Success, failure: @escaping Banner.Failure, click: @escaping Click) {
self.success = success
self.failure = failure
self.click = click
load()
requestDate = Date()
}
func unregister() {
nativeAd?.unregister()
}
var isBannerOnScreen = false {
didSet {
if isBannerOnScreen {
startCountTimeOnScreen()
} else {
stopCountTimeOnScreen()
}
}
}
private(set) var isNeedToRetain = false
var isPossibleToReload: Bool {
if let date = requestDate {
return Date().timeIntervalSince(date) > Limits.minTimeSinceLastRequest
}
return true
}
var type: BannerType { return .mopub(bannerID) }
var mwmType: MWMBannerType { return type.mwmType }
var bannerID: String { return placementID }
var statisticsDescription: [String: String] {
return [kStatBanner: bannerID, kStatProvider: kStatMopub]
}
init(bannerID: String) {
placementID = bannerID
super.init()
let center = NotificationCenter.default
center.addObserver(self,
selector: #selector(enterForeground),
name: UIApplication.willEnterForegroundNotification,
object: nil)
center.addObserver(self,
selector: #selector(enterBackground),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func enterForeground() {
if isBannerOnScreen {
startCountTimeOnScreen()
}
}
@objc private func enterBackground() {
if isBannerOnScreen {
stopCountTimeOnScreen()
}
}
private func startCountTimeOnScreen() {
if showDate == nil {
showDate = Date()
}
if remainingTime > 0 {
perform(#selector(setEnoughTimeOnScreen), with: nil, afterDelay: remainingTime)
}
}
private func stopCountTimeOnScreen() {
guard let date = showDate else {
assert(false)
return
}
let timePassed = Date().timeIntervalSince(date)
if timePassed < Limits.minTimeOnScreen {
remainingTime = Limits.minTimeOnScreen - timePassed
NSObject.cancelPreviousPerformRequests(withTarget: self)
} else {
remainingTime = 0
}
}
@objc private func setEnoughTimeOnScreen() {
isNeedToRetain = false
}
// MARK: - Content
private(set) var nativeAd: MPNativeAd?
var title: String {
return nativeAd?.properties[kAdTitleKey] as? String ?? ""
}
var text: String {
return nativeAd?.properties[kAdTextKey] as? String ?? ""
}
var iconURL: String {
return nativeAd?.properties[kAdIconImageKey] as? String ?? ""
}
var ctaText: String {
return nativeAd?.properties[kAdCTATextKey] as? String ?? ""
}
var privacyInfoURL: URL? {
guard let nativeAd = nativeAd else { return nil }
if nativeAd.adAdapter is FacebookNativeAdAdapter {
return (nativeAd.adAdapter as! FacebookNativeAdAdapter).fbNativeAd.adChoicesLinkURL
}
return URL(string: kDAAIconTapDestinationURL)
}
// MARK: - Helpers
private var request: MPNativeAdRequest!
private func load() {
let settings = MPStaticNativeAdRendererSettings()
let config = MPStaticNativeAdRenderer.rendererConfiguration(with: settings)!
request = MPNativeAdRequest(adUnitIdentifier: placementID, rendererConfigurations: [config])
let targeting = MPNativeAdRequestTargeting()
targeting.keywords = "user_lang:\(AppInfo.shared().twoLetterLanguageId ?? "")"
targeting.desiredAssets = [kAdTitleKey, kAdTextKey, kAdIconImageKey, kAdCTATextKey]
if let location = MWMLocationManager.lastLocation() {
targeting.location = location
}
request.targeting = targeting
request.start { [weak self] _, nativeAd, error in
guard let s = self else { return }
if let error = error as NSError? {
let params: [String: Any] = [
kStatBanner: s.bannerID,
kStatProvider: kStatMopub,
]
let event = kStatPlacePageBannerError
s.failure(s.type, event, params, error)
} else {
nativeAd?.delegate = self
s.nativeAd = nativeAd
s.success(s)
}
}
}
}
extension MopubBanner: MPNativeAdDelegate {
func willPresentModal(for nativeAd: MPNativeAd!) {
guard nativeAd === self.nativeAd else { return }
click(self)
}
func viewControllerForPresentingModalView() -> UIViewController! {
return UIViewController.topViewController()
}
}
| apache-2.0 |
lvogelzang/Blocky | Blocky/Levels/Level43.swift | 1 | 877 | //
// Level43.swift
// Blocky
//
// Created by Lodewijck Vogelzang on 07-12-18
// Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved.
//
import UIKit
final class Level43: Level {
let levelNumber = 43
var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]
let cameraFollowsBlock = false
let blocky: Blocky
let enemies: [Enemy]
let foods: [Food]
init() {
blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1))
let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0)
let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1)
enemies = [enemy0, enemy1]
foods = []
}
}
| mit |
sayheyrickjames/codepath-dev | week5/week4-class-tinder/week4-class-tinderTests/week4_class_tinderTests.swift | 2 | 935 | //
// week4_class_tinderTests.swift
// week4-class-tinderTests
//
// Created by Rick James! Chatas on 5/24/15.
// Copyright (c) 2015 SayHey. All rights reserved.
//
import UIKit
import XCTest
class week4_class_tinderTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
safx/TypetalkKit | IDL/IDLProtocols.swift | 1 | 405 | //
// Protocols.swift
// Swift-idl
//
// Created by Safx Developer on 2015/05/12.
// Copyright (c) 2015年 Safx Developers. All rights reserved.
//
protocol ClassInit {}
protocol EnumStaticInit {}
protocol Printable {}
protocol Encodable {}
protocol Decodable {}
protocol JSON {}
protocol URLRequestHelper {}
protocol APIKitHelper {}
protocol WSHelper {}
protocol ErrorType {}
protocol EJDB {}
| mit |
mentalfaculty/impeller | Sources/LocalRepository.swift | 1 | 1334 | //
// Repository.swift
// Impeller
//
// Created by Drew McCormack on 08/12/2016.
// Copyright © 2016 Drew McCormack. All rights reserved.
//
public protocol LocalRepository {
func fetchValue<T:Repositable>(identifiedBy uniqueIdentifier:UniqueIdentifier) -> T?
func commit<T:Repositable>(_ value: inout T, resolvingConflictsWith conflictResolver: ConflictResolver)
func delete<T:Repositable>(_ root: inout T, resolvingConflictsWith conflictResolver: ConflictResolver)
}
public protocol PropertyReader: class {
func read<T:RepositablePrimitive>(_ key:String) -> T?
func read<T:RepositablePrimitive>(optionalFor key:String) -> T??
func read<T:RepositablePrimitive>(_ key:String) -> [T]?
func read<T:Repositable>(_ key:String) -> T?
func read<T:Repositable>(optionalFor key:String) -> T??
func read<T:Repositable>(_ key:String) -> [T]?
}
public protocol PropertyWriter: class {
func write<T:RepositablePrimitive>(_ value:T, for key:String)
func write<T:RepositablePrimitive>(_ optionalValue:T?, for key:String)
func write<T:RepositablePrimitive>(_ values:[T], for key:String)
func write<T:Repositable>(_ value:inout T, for key:String)
func write<T:Repositable>(_ optionalValue:inout T?, for key:String)
func write<T:Repositable>(_ values:inout [T], for key:String)
}
| mit |
Speicher210/wingu-sdk-ios-demoapp | Example/Pods/SKPhotoBrowser/SKPhotoBrowser/SKPagingScrollView.swift | 1 | 7810 | //
// SKPagingScrollView.swift
// SKPhotoBrowser
//
// Created by 鈴木 啓司 on 2016/08/18.
// Copyright © 2016年 suzuki_keishi. All rights reserved.
//
import Foundation
class SKPagingScrollView: UIScrollView {
let pageIndexTagOffset: Int = 1000
let sideMargin: CGFloat = 10
fileprivate var visiblePages = [SKZoomingScrollView]()
fileprivate var recycledPages = [SKZoomingScrollView]()
fileprivate weak var browser: SKPhotoBrowser?
var numberOfPhotos: Int {
return browser?.photos.count ?? 0
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
isPagingEnabled = true
showsHorizontalScrollIndicator = true
showsVerticalScrollIndicator = true
}
convenience init(frame: CGRect, browser: SKPhotoBrowser) {
self.init(frame: frame)
self.browser = browser
updateFrame(bounds, currentPageIndex: browser.currentPageIndex)
}
func reload() {
visiblePages.forEach({$0.removeFromSuperview()})
visiblePages.removeAll()
recycledPages.removeAll()
}
func loadAdjacentPhotosIfNecessary(_ photo: SKPhotoProtocol, currentPageIndex: Int) {
guard let browser = browser, let page = pageDisplayingAtPhoto(photo) else {
return
}
let pageIndex = (page.tag - pageIndexTagOffset)
if currentPageIndex == pageIndex {
// Previous
if pageIndex > 0 {
let previousPhoto = browser.photos[pageIndex - 1]
if previousPhoto.underlyingImage == nil {
previousPhoto.loadUnderlyingImageAndNotify()
}
}
// Next
if pageIndex < numberOfPhotos - 1 {
let nextPhoto = browser.photos[pageIndex + 1]
if nextPhoto.underlyingImage == nil {
nextPhoto.loadUnderlyingImageAndNotify()
}
}
}
}
func deleteImage() {
// index equals 0 because when we slide between photos delete button is hidden and user cannot to touch on delete button. And visible pages number equals 0
if numberOfPhotos > 0 {
visiblePages[0].captionView?.removeFromSuperview()
}
}
func animate(_ frame: CGRect) {
setContentOffset(CGPoint(x: frame.origin.x - sideMargin, y: 0), animated: true)
}
func updateFrame(_ bounds: CGRect, currentPageIndex: Int) {
var frame = bounds
frame.origin.x -= sideMargin
frame.size.width += (2 * sideMargin)
self.frame = frame
if visiblePages.count > 0 {
for page in visiblePages {
let pageIndex = page.tag - pageIndexTagOffset
page.frame = frameForPageAtIndex(pageIndex)
page.setMaxMinZoomScalesForCurrentBounds()
if page.captionView != nil {
page.captionView.frame = frameForCaptionView(page.captionView, index: pageIndex)
}
}
}
updateContentSize()
updateContentOffset(currentPageIndex)
}
func updateContentSize() {
contentSize = CGSize(width: bounds.size.width * CGFloat(numberOfPhotos), height: bounds.size.height)
}
func updateContentOffset(_ index: Int) {
let pageWidth = bounds.size.width
let newOffset = CGFloat(index) * pageWidth
contentOffset = CGPoint(x: newOffset, y: 0)
}
func tilePages() {
guard let browser = browser else { return }
let firstIndex: Int = getFirstIndex()
let lastIndex: Int = getLastIndex()
visiblePages
.filter({ $0.tag - pageIndexTagOffset < firstIndex || $0.tag - pageIndexTagOffset > lastIndex })
.forEach { page in
recycledPages.append(page)
page.prepareForReuse()
page.removeFromSuperview()
}
let visibleSet: Set<SKZoomingScrollView> = Set(visiblePages)
let visibleSetWithoutRecycled: Set<SKZoomingScrollView> = visibleSet.subtracting(recycledPages)
visiblePages = Array(visibleSetWithoutRecycled)
while recycledPages.count > 2 {
recycledPages.removeFirst()
}
for index: Int in firstIndex...lastIndex {
if visiblePages.filter({ $0.tag - pageIndexTagOffset == index }).count > 0 {
continue
}
let page: SKZoomingScrollView = SKZoomingScrollView(frame: frame, browser: browser)
page.frame = frameForPageAtIndex(index)
page.tag = index + pageIndexTagOffset
page.photo = browser.photos[index]
visiblePages.append(page)
addSubview(page)
// if exists caption, insert
if let captionView: SKCaptionView = createCaptionView(index) {
captionView.frame = frameForCaptionView(captionView, index: index)
captionView.alpha = browser.areControlsHidden() ? 0 : 1
addSubview(captionView)
// ref val for control
page.captionView = captionView
}
}
}
func frameForCaptionView(_ captionView: SKCaptionView, index: Int) -> CGRect {
let pageFrame = frameForPageAtIndex(index)
let captionSize = captionView.sizeThatFits(CGSize(width: pageFrame.size.width, height: 0))
let navHeight = browser?.navigationController?.navigationBar.frame.size.height ?? 44
return CGRect(x: pageFrame.origin.x, y: pageFrame.size.height - captionSize.height - navHeight,
width: pageFrame.size.width, height: captionSize.height)
}
func pageDisplayedAtIndex(_ index: Int) -> SKZoomingScrollView? {
for page in visiblePages where page.tag - pageIndexTagOffset == index {
return page
}
return nil
}
func pageDisplayingAtPhoto(_ photo: SKPhotoProtocol) -> SKZoomingScrollView? {
for page in visiblePages where page.photo === photo {
return page
}
return nil
}
func getCaptionViews() -> Set<SKCaptionView> {
var captionViews = Set<SKCaptionView>()
visiblePages
.filter({ $0.captionView != nil })
.forEach {
captionViews.insert($0.captionView)
}
return captionViews
}
}
private extension SKPagingScrollView {
func frameForPageAtIndex(_ index: Int) -> CGRect {
var pageFrame = bounds
pageFrame.size.width -= (2 * sideMargin)
pageFrame.origin.x = (bounds.size.width * CGFloat(index)) + sideMargin
return pageFrame
}
func createCaptionView(_ index: Int) -> SKCaptionView? {
guard let photo = browser?.photoAtIndex(index), photo.caption != nil else {
return nil
}
return SKCaptionView(photo: photo)
}
func getFirstIndex() -> Int {
let firstIndex = Int(floor((bounds.minX + sideMargin * 2) / bounds.width))
if firstIndex < 0 {
return 0
}
if firstIndex > numberOfPhotos - 1 {
return numberOfPhotos - 1
}
return firstIndex
}
func getLastIndex() -> Int {
let lastIndex = Int(floor((bounds.maxX - sideMargin * 2 - 1) / bounds.width))
if lastIndex < 0 {
return 0
}
if lastIndex > numberOfPhotos - 1 {
return numberOfPhotos - 1
}
return lastIndex
}
}
| apache-2.0 |
saagarjha/iina | iina/MPVPlaylistItem.swift | 3 | 802 | //
// MPVPlaylistItem.swift
// iina
//
// Created by lhc on 23/8/16.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
class MPVPlaylistItem: NSObject {
/** Actually this is the path. Use `filename` to conform mpv API's naming. */
var filename: String
/** Title or the real filename */
var filenameForDisplay: String {
return title ?? (isNetworkResource ? filename : NSString(string: filename).lastPathComponent)
}
var isCurrent: Bool
var isPlaying: Bool
var isNetworkResource: Bool
var title: String?
init(filename: String, isCurrent: Bool, isPlaying: Bool, title: String?) {
self.filename = filename
self.isCurrent = isCurrent
self.isPlaying = isPlaying
self.title = title
self.isNetworkResource = Regex.url.matches(filename)
}
}
| gpl-3.0 |
radvansky-tomas/NutriFacts | nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Renderers/ChartRendererBase.swift | 6 | 1808 | //
// ChartRendererBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics.CGBase
public class ChartRendererBase: NSObject
{
/// the component that handles the drawing area of the chart and it's offsets
public var viewPortHandler: ChartViewPortHandler!;
/// the minimum value on the x-axis that should be plotted
internal var _minX: Int = 0;
/// the maximum value on the x-axis that should be plotted
internal var _maxX: Int = 0;
public override init()
{
super.init();
}
public init(viewPortHandler: ChartViewPortHandler)
{
super.init();
self.viewPortHandler = viewPortHandler;
}
/// Returns true if the specified value fits in between the provided min and max bounds, false if not.
internal func fitsBounds(val: Float, min: Float, max: Float) -> Bool
{
if (val < min || val > max)
{
return false;
}
else
{
return true;
}
}
/// Calculates the minimum and maximum x-value the chart can currently display (with the given zoom level).
public func calcXBounds(#chart: BarLineChartViewBase, xAxisModulus: Int)
{
let low = chart.lowestVisibleXIndex;
let high = chart.highestVisibleXIndex;
let subLow = (low % xAxisModulus == 0) ? xAxisModulus : 0;
_minX = max((low / xAxisModulus) * (xAxisModulus) - subLow, 0);
_maxX = min((high / xAxisModulus) * (xAxisModulus) + xAxisModulus, Int(chart.chartXMax));
}
}
| gpl-2.0 |
lsonlee/Swift_MVVM | Swift_Project/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallZigZag.swift | 2 | 3537 | //
// NVActivityIndicatorAnimationBallZigZag.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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 QuartzCore
class NVActivityIndicatorAnimationBallZigZag: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize: CGFloat = size.width / 5
let duration: CFTimeInterval = 0.7
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize)
// Circle 1 animation
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.keyTimes = [0.0, 0.33, 0.66, 1.0]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.values = [
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle 1
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
// Circle 2 animation
animation.values = [
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
]
// Draw circle 2
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
}
func circleAt(frame: CGRect, layer: CALayer, size: CGSize, color: UIColor, animation: CAAnimation) {
let circle = NVActivityIndicatorShape.circle.layerWith(size: size, color: color)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| mit |
nodes-vapor/admin-panel | Sources/AdminPanel/Controllers/DashboardController.swift | 1 | 528 | import Vapor
import Leaf
public protocol DashboardControllerType {
func renderDashboard(_ req: Request) throws -> Future<Response>
}
public final class DashboardController<U: AdminPanelUserType>: DashboardControllerType {
public init() {}
public func renderDashboard(_ req: Request) throws -> Future<Response> {
let config = try req.make(AdminPanelConfig<U>.self)
return try req
.view()
.render(config.views.dashboard.index, on: req)
.encode(for: req)
}
}
| mit |
cho15255/PaintWithMetal | PaintWithMetal/JHViewController+Renderer.swift | 1 | 3259 | //
// JHViewController+Renderer.swift
// PaintWithMetal
//
// Created by Jae Hee Cho on 2015-11-29.
// Copyright © 2015 Jae Hee Cho. All rights reserved.
//
import Foundation
import UIKit
import Metal
extension JHViewController {
func render() {
if let drawable = self.metalLayer.nextDrawable() {
if self.bufferCleared <= 3 {
self.renderPassDescriptor = MTLRenderPassDescriptor()
self.renderPassDescriptor.colorAttachments[0].loadAction = .Clear
self.renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0.9, 0.9, 0.9, 1)
self.renderPassDescriptor.colorAttachments[0].storeAction = .Store
self.bufferCleared += 1
} else {
self.renderPassDescriptor.colorAttachments[0].loadAction = .Load
}
self.renderPassDescriptor.colorAttachments[0].texture = drawable.texture
if self.vertexData.count <= 0 {
let commandBuffer = self.commandQueue.commandBuffer()
let renderEncoderOpt:MTLRenderCommandEncoder? = commandBuffer.renderCommandEncoderWithDescriptor(self.renderPassDescriptor)
if let renderEncoder = renderEncoderOpt {
renderEncoder.setRenderPipelineState(self.pipelineState)
renderEncoder.endEncoding()
}
commandBuffer.presentDrawable(drawable)
commandBuffer.commit()
} else {
let commandBuffer = self.commandQueue.commandBuffer()
let renderEncoderOpt:MTLRenderCommandEncoder? = commandBuffer.renderCommandEncoderWithDescriptor(self.renderPassDescriptor)
if let renderEncoder = renderEncoderOpt {
renderEncoder.setRenderPipelineState(self.pipelineState)
renderEncoder.setVertexBuffer(self.vertexBuffer, offset: 0, atIndex: 0)
renderEncoder.setVertexBuffer(self.colorBuffer, offset: 0, atIndex: 1)
if self.vertexData.count > 0 {
renderEncoder.drawPrimitives(.TriangleStrip, vertexStart: 0, vertexCount: self.vertexData.count/4, instanceCount: 3)
}
renderEncoder.endEncoding()
}
if self.vertexData.count > 800 {
self.vertexData.removeFirst(400)
}
if self.colorData.count > 800 {
self.colorData.removeFirst(400)
}
if self.didTouchEnded < 3 {
self.didTouchEnded += 1
} else {
self.vertexData = []
self.colorData = []
self.prevVertex = nil
}
commandBuffer.presentDrawable(drawable)
commandBuffer.commit()
}
}
}
func gameLoop() {
autoreleasepool {
self.render()
}
}
}
| mit |
DigitalRogues/SwiftNotes | SwiftNotes/LeftMenuViewController.swift | 1 | 3781 | //
// LeftMenuViewController.swift
// SSASideMenuExample
//
// Created by Sebastian Andersen on 20/10/14.
// Copyright (c) 2014 Sebastian Andersen. All rights reserved.
//
import Foundation
import UIKit
////I think we'll have to use the app delegate as a central point so the viewcontrollers arent reinited each time they are called. its a bad thing to do but I dont know of a better way
// let view = appDelegate.rootView
class LeftMenuViewController: UIViewController {
var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .None
tableView.frame = CGRectMake(20, (self.view.frame.size.height - 54 * 5) / 2.0, self.view.frame.size.width, 54 * 5)
tableView.autoresizingMask = .FlexibleTopMargin | .FlexibleBottomMargin | .FlexibleWidth
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.bounces = false
return tableView
}()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK : TableViewDataSource & Delegate Methods
extension LeftMenuViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 54
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let titles: [String] = ["Notes List", "Add Note", "Profile", "Settings", "Log Out"]
let images: [String] = ["IconHome", "IconCalendar", "IconProfile", "IconSettings", "IconEmpty"]
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 21)
cell.textLabel?.textColor = UIColor.blackColor()
cell.textLabel?.text = titles[indexPath.row]
cell.selectionStyle = .None
cell.imageView?.image = UIImage(named: images[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row {
case 0:
//Notes
let view = appDelegate.sb.instantiateViewControllerWithIdentifier("noteListView") as! UIViewController
sideMenuViewController?.contentViewController = view
sideMenuViewController?.hideMenuViewController()
break
case 1:
//note input view
let view = appDelegate.noteInputView as UIViewController
sideMenuViewController?.contentViewController = view
sideMenuViewController?.hideMenuViewController()
break
default:
break
}
}
}
| mit |
36Kr-Mobile/StatusBarNotificationCenter | Example/StatusBarNotificationCenter/Main View Controller/ViewController.swift | 1 | 4706 | //
// ViewController.swift
// StatusBarNotification
//
// Created by Shannon Wu on 9/16/15.
// Copyright © 2015 Shannon Wu. All rights reserved.
//
import UIKit
import StatusBarNotificationCenter
class ViewController: UIViewController {
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var notificationTextField: UITextField!
@IBOutlet weak var durationSlider: UISlider!
@IBOutlet weak var segFromStyle: UISegmentedControl!
@IBOutlet weak var segToStyle: UISegmentedControl!
@IBOutlet weak var segNotificationType: UISegmentedControl!
@IBOutlet weak var segAnimationType: UISegmentedControl!
@IBOutlet weak var heightLabel: UILabel!
@IBOutlet weak var multiLine: UISwitch!
@IBOutlet weak var isCustomView: UISwitch!
@IBOutlet weak var concurrentNotificationNumberLabel: UILabel!
@IBOutlet weak var concurrentNotificationNumberSlider: UISlider!
@IBOutlet weak var heightSlider: UISlider!
let notificationQ = DispatchQueue(label: "ViewControllerNotificationQ", attributes: DispatchQueue.Attributes.concurrent)
var notificationCenter: StatusBarNotificationCenter!
override func viewDidLoad() {
let labelText = "\(durationSlider.value) seconds"
durationLabel.text = labelText
notificationTextField.text = "Hello, Programmer"
}
@IBAction func durationValueChanged(_ sender: UISlider) {
let labelText = "\(sender.value) seconds"
durationLabel.text = labelText
}
@IBAction func heightValueChanged(_ sender: UISlider) {
let labelText = sender.value == 0 ? "Standard Height" : "\(sender.value) of the screen height"
heightLabel.text = labelText
}
@IBAction func notificationNumberChanged(_ sender: UISlider) {
let labelText = "\(Int(concurrentNotificationNumberSlider.value))"
concurrentNotificationNumberLabel.text = labelText
}
@IBAction func showNotification(_ sender: UIButton) {
var notificationCenterConfiguration = NotificationCenterConfiguration(baseWindow: view.window!)
notificationCenterConfiguration.animateInDirection = StatusBarNotificationCenter.AnimationDirection(rawValue: segFromStyle.selectedSegmentIndex)!
notificationCenterConfiguration.animateOutDirection = StatusBarNotificationCenter.AnimationDirection(rawValue: segToStyle.selectedSegmentIndex)!
notificationCenterConfiguration.animationType = StatusBarNotificationCenter.AnimationType(rawValue: segAnimationType.selectedSegmentIndex)!
notificationCenterConfiguration.style = StatusBarNotificationCenter.Style(rawValue: segNotificationType.selectedSegmentIndex)!
notificationCenterConfiguration.height = (UIScreen.main.bounds.height * CGFloat(heightSlider.value))
notificationCenterConfiguration.animateInLength = 0.25
notificationCenterConfiguration.animateOutLength = 0.75
notificationCenterConfiguration.style = StatusBarNotificationCenter.Style(rawValue: segNotificationType.selectedSegmentIndex)!
notificationQ.async { () -> Void in
for i in 1...Int(self.concurrentNotificationNumberSlider.value) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(Double(i) * drand48() * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: { () -> Void in
if self.isCustomView.isOn {
let nibContents = Bundle.main.loadNibNamed("NotificationView", owner: self, options: nil)
let view = nibContents?.first as! UIView
StatusBarNotificationCenter.showStatusBarNotificationWithView(view, forDuration: TimeInterval(self.durationSlider.value), withNotificationCenterConfiguration: notificationCenterConfiguration)
} else {
var notificationLabelConfiguration = NotificationLabelConfiguration()
notificationLabelConfiguration.font = UIFont.systemFont(ofSize: 14.0)
notificationLabelConfiguration.multiline = self.multiLine.isOn
notificationLabelConfiguration.backgroundColor = self.view.tintColor
notificationLabelConfiguration.textColor = UIColor.black
StatusBarNotificationCenter.showStatusBarNotificationWithMessage(self.notificationTextField.text! + "\(i)", forDuration: TimeInterval(self.durationSlider.value), withNotificationCenterConfiguration: notificationCenterConfiguration, andNotificationLabelConfiguration: notificationLabelConfiguration)
}
})
}
}
}
}
| mit |
kharrison/CodeExamples | Encode/encode/ViewController.swift | 1 | 2453 | //
// ViewController.swift
// encode
//
// Created by Keith Harrison https://useyourloaf.com
// Copyright (c) 2016-2020 Keith Harrison. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var rfc3986Output: UILabel!
@IBOutlet weak var formOutput: UILabel!
@IBOutlet weak var textInput: UITextField!
@IBOutlet weak var plusSwitch: UISwitch!
@IBAction func plusValueChanged(sender: UISwitch) {
updateOutputLabels()
}
func updateOutputLabels() {
let input = textInput.text
let usePlusForSpace = plusSwitch.isOn
rfc3986Output.text = input?.stringByAddingPercentEncodingForRFC3986()
formOutput.text = input?.stringByAddingPercentEncodingForFormData(plusForSpace: usePlusForSpace)
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
updateOutputLabels()
return true
}
}
| bsd-3-clause |
skedgo/tripkit-ios | Sources/TripKit/vendor/ASPolygonKit/CLLocationCoordinate2D+EncodePolylineString.swift | 1 | 2444 | //
// CLLocationCoordinate2D+EncodePolylineString.swift
//
//
// Created by Adrian Schönig on 5/11/21.
//
import Foundation
extension Polygon {
/// This function encodes an `Polygon` to a `String`
///
/// - parameter precision: The precision used to encode coordinates (default: `1e5`)
///
/// - returns: A `String` representing the encoded Polyline
func encodeCoordinates(precision: Double = 1e5) -> String {
var previousCoordinate = IntegerCoordinates(0, 0)
var encodedPolyline = ""
for coordinate in points {
let intLatitude = Int(round(coordinate.lat * precision))
let intLongitude = Int(round(coordinate.lng * precision))
let coordinatesDifference = (intLatitude - previousCoordinate.latitude, intLongitude - previousCoordinate.longitude)
encodedPolyline += Self.encodeCoordinate(coordinatesDifference)
previousCoordinate = (intLatitude,intLongitude)
}
return encodedPolyline
}
// MARK: - Private -
// MARK: Encode Coordinate
private static func encodeCoordinate(_ locationCoordinate: IntegerCoordinates) -> String {
let latitudeString = encodeSingleComponent(locationCoordinate.latitude)
let longitudeString = encodeSingleComponent(locationCoordinate.longitude)
return latitudeString + longitudeString
}
private static func encodeSingleComponent(_ value: Int) -> String {
var intValue = value
if intValue < 0 {
intValue = intValue << 1
intValue = ~intValue
} else {
intValue = intValue << 1
}
return encodeFiveBitComponents(intValue)
}
// MARK: Encode Levels
private static func encodeLevel(_ level: UInt32) -> String {
return encodeFiveBitComponents(Int(level))
}
private static func encodeFiveBitComponents(_ value: Int) -> String {
var remainingComponents = value
var fiveBitComponent = 0
var returnString = String()
repeat {
fiveBitComponent = remainingComponents & 0x1F
if remainingComponents >= 0x20 {
fiveBitComponent |= 0x20
}
fiveBitComponent += 63
let char = UnicodeScalar(fiveBitComponent)!
returnString.append(String(char))
remainingComponents = remainingComponents >> 5
} while (remainingComponents != 0)
return returnString
}
private typealias IntegerCoordinates = (latitude: Int, longitude: Int)
}
| apache-2.0 |
mengxiangyue/Swift-Design-Pattern-In-Chinese | Design_Pattern.playground/Pages/Iterator.xcplaygroundpage/Contents.swift | 1 | 3536 | /*:
### **Iterator**
---
[回到列表](Index)
1. 定义:迭代器模式(Iterator Pattern):提供一种方法来访问聚合对象,而不用暴露这个对象的内部表示,其别名为游标(Cursor)。迭代器模式是一种对象行为型模式。迭代器内部关联着需要访问的对象。
1. Iterator(抽象迭代器):它定义了访问和遍历元素的接口,声明了用于遍历数据元素的方法,例如:用于获取第一个元素的first()方法,用于访问下一个元素的next()方法,用于判断是否还有下一个元素的hasNext()方法,用于获取当前元素的currentItem()方法等,在具体迭代器中将实现这些方法。
2. ConcreteIterator(具体迭代器):它实现了抽象迭代器接口,完成对聚合对象的遍历,同时在具体迭代器中通过游标来记录在聚合对象中所处的当前位置,在具体实现时,游标通常是一个表示位置的非负整数。
3. Aggregate(抽象聚合类):它用于存储和管理元素对象,声明一个createIterator()方法用于创建一个迭代器对象,充当抽象迭代器工厂角色。
4. ConcreteAggregate(具体聚合类):它实现了在抽象聚合类中声明的createIterator()方法,该方法返回一个与该具体聚合类对应的具体迭代器ConcreteIterator实例。
2. 问题:迭代输出我读过的小说,但是我们不想暴露内部的存储,这时候可以使用迭代器模式。
3. 解决方案:
4. 使用方法:
1. 定义抽象的聚合类
2. 定义具体的聚合类
3. 定义抽象迭代器,这里使用的系统的IteratorProtocol协议。
4. 定义具体的迭代器 NovellasIterator, 同时关联了聚合类,用于保存数据。
5. 优点:
1. 它支持以不同的方式遍历一个聚合对象,在同一个聚合对象上可以定义多种遍历方式。在迭代器模式中只需要用一个不同的迭代器来替换原有迭代器即可改变遍历算法,我们也可以自己定义迭代器的子类以支持新的遍历方式。
2. 迭代器简化了聚合类。由于引入了迭代器,在原有的聚合对象中不需要再自行提供数据遍历等方法,这样可以简化聚合类的设计。
3. 在迭代器模式中,由于引入了抽象层,增加新的聚合类和迭代器类都很方便,无须修改原有代码,满足“开闭原则”的要求。
6. 缺点:
1. 由于迭代器模式将存储数据和遍历数据的职责分离,增加新的聚合类需要对应增加新的迭代器类,类的个数成对增加,这在一定程度上增加了系统的复杂性。
2. 抽象迭代器的设计难度较大,需要充分考虑到系统将来的扩展。
*/
import Foundation
// 中篇小说
struct Novella {
let name: String
}
struct Novellas {
let novellas: [Novella]
}
struct NovellasIterator: IteratorProtocol {
private var current = 0
private let novellas: [Novella]
init(novellas: [Novella]) {
self.novellas = novellas
}
mutating func next() -> Novella? {
defer { current += 1 }
return novellas.count > current ? novellas[current] : nil
}
}
extension Novellas: Sequence {
func makeIterator() -> NovellasIterator {
return NovellasIterator(novellas: novellas)
}
}
/*:
### Usage
*/
let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] )
for novella in greatNovellas {
print("I've read: \(novella)")
}
| mit |
ethanneff/organize | Organize/IntroNavigationController.swift | 1 | 1103 | import UIKit
import Firebase
class IntroNavigationController: UINavigationController {
override func loadView() {
super.loadView()
navigationBar.hidden = true
pushViewController(IntroViewController(), animated: true)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
determineController()
}
private func determineController() {
Notebook.get { data in
if data == nil {
Remote.Auth.signOut()
}
Util.delay(Constant.App.loadingDelay) {
if let _ = Remote.Auth.user {
self.displayController(navController: MenuNavigationController())
} else {
self.displayController(navController: AccessNavigationController())
}
}
}
}
private func displayController(navController navController: UINavigationController) {
navController.modalTransitionStyle = .CrossDissolve
presentViewController(navController, animated: true, completion: nil)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
| mit |
RxSwiftCommunity/RxSwiftExt | Playground/RxSwiftExtPlayground.playground/Pages/UIScrollView.reachedBottom.xcplaygroundpage/Contents.swift | 2 | 1781 | /*:
> # IMPORTANT: To use `RxSwiftExtPlayground.playground`, please:
1. Make sure you have [Carthage](https://github.com/Carthage/Carthage) installed
1. Fetch Carthage dependencies from shell: `carthage bootstrap --platform ios`
1. Build scheme `RxSwiftExtPlayground` scheme for a simulator target
1. Choose `View > Show Debug Area`
*/
//: [Previous](@previous)
import RxSwift
import RxCocoa
import RxSwiftExt
import PlaygroundSupport
import UIKit
/*:
## reachedBottom
`reachedBottom` provides a sequence that emits every time the `UIScrollView` is scrolled to the bottom, with an optional offset.
Please open the Assistant Editor (⌘⌥⏎) to see the Interactive Live View example.
*/
final class ReachedBottomViewController: UITableViewController {
private let dataSource = Array(stride(from: 0, to: 28, by: 1))
private let identifier = "identifier"
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: identifier)
tableView.rx.reachedBottom(offset: 40)
.subscribe { print("Reached bottom") }
.disposed(by: disposeBag)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
cell.textLabel?.text = "\(dataSource[indexPath.row])"
return cell
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = ReachedBottomViewController()
//: [Next](@next)
| mit |
mono0926/LicensePlist | Sources/LicensePlistCore/Extension/Extensions.swift | 1 | 587 | import Foundation
public struct LicensePlistExtension<Base> {
let base: Base
init (_ base: Base) {
self.base = base
}
}
public protocol LicensePlistCompatible {
associatedtype Compatible
static var lp: LicensePlistExtension<Compatible>.Type { get }
var lp: LicensePlistExtension<Compatible> { get }
}
extension LicensePlistCompatible {
public static var lp: LicensePlistExtension<Self>.Type {
return LicensePlistExtension<Self>.self
}
public var lp: LicensePlistExtension<Self> {
return LicensePlistExtension(self)
}
}
| mit |
edragoev1/pdfjet | Sources/PDFjet/Paragraph.swift | 1 | 1226 | /**
* Paragraph.swift
*
Copyright 2020 Innovatics Inc.
*/
import Foundation
///
/// Used to create paragraph objects.
/// See the TextColumn class for more information.
///
public class Paragraph {
var list: [TextLine]?
var alignment: UInt32 = Align.LEFT
///
/// Constructor for creating paragraph objects.
///
public init() {
list = [TextLine]()
}
public init(_ text: TextLine) {
list = [TextLine]()
list!.append(text)
}
///
/// Adds a text line to this paragraph.
///
/// @param text the text line to add to this paragraph.
/// @return this paragraph.
///
@discardableResult
public func add(_ text: TextLine) -> Paragraph {
list!.append(text)
return self
}
///
/// Sets the alignment of the text in this paragraph.
///
/// @param alignment the alignment code.
/// @return this paragraph.
///
/// <pre>Supported values: Align.LEFT, Align.RIGHT, Align.CENTER and Align.JUSTIFY.</pre>
///
@discardableResult
public func setAlignment(_ alignment: UInt32) -> Paragraph {
self.alignment = alignment
return self
}
} // End of Paragraph.swift
| mit |
HabitRPG/habitrpg-ios | HabitRPG/Utilities/NotificationManager.swift | 1 | 6613 | //
// NotificationManager.swift
// Habitica
//
// Created by Phillip Thelen on 24.06.20.
// Copyright © 2020 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import FirebaseAnalytics
class NotificationManager {
private static var seenNotifications = Set<String>()
private static let configRepository = ConfigRepository()
private static let userRepository = UserRepository()
static func handle(notifications: [NotificationProtocol]) -> [NotificationProtocol] {
notifications.filter { notification in
return NotificationManager.seenNotifications.contains(notification.id) != true
}.forEach { notification in
var notificationDisplayed: Bool? = false
switch notification.type {
case HabiticaNotificationType.achievementPartyUp, HabiticaNotificationType.achievementPartyOn,
HabiticaNotificationType.achievementBeastMaster,
HabiticaNotificationType.achievementTriadBingo,
HabiticaNotificationType.achievementGuildJoined,
HabiticaNotificationType.achievementMountMaster,
HabiticaNotificationType.achievementInvitedFriend,
HabiticaNotificationType.achievementChallengeJoined,
HabiticaNotificationType.achievementOnboardingComplete:
notificationDisplayed = NotificationManager.displayAchievement(notification: notification, isOnboarding: false, isLastOnboardingAchievement: false)
case HabiticaNotificationType.achievementGeneric:
notificationDisplayed = NotificationManager.displayAchievement(notification: notification, isOnboarding: true, isLastOnboardingAchievement: notifications.contains {
return $0.type == HabiticaNotificationType.achievementOnboardingComplete
})
case HabiticaNotificationType.firstDrop:
notificationDisplayed = NotificationManager.displayFirstDrop(notification: notification)
default:
notificationDisplayed = false
}
if notificationDisplayed == true {
NotificationManager.seenNotifications.insert(notification.id)
}
}
return notifications.filter {
return !seenNotifications.contains($0.id)
}
}
static func displayFirstDrop(notification: NotificationProtocol) -> Bool {
guard let firstDropNotification = notification as? NotificationFirstDropProtocol else {
return true
}
userRepository.retrieveUser().observeCompleted {}
userRepository.readNotification(notification: notification).observeCompleted {}
let alert = HabiticaAlertController(title: L10n.firstDropTitle)
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .center
stackView.spacing = 12
let iconStackView = UIStackView()
iconStackView.axis = .horizontal
iconStackView.spacing = 16
let eggView = NetworkImageView()
eggView.setImagewith(name: "Pet_Egg_\(firstDropNotification.egg ?? "")")
eggView.backgroundColor = ThemeService.shared.theme.windowBackgroundColor
eggView.cornerRadius = 4
eggView.contentMode = .center
iconStackView.addArrangedSubview(eggView)
eggView.addWidthConstraint(width: 80)
let potionView = NetworkImageView()
potionView.setImagewith(name: "Pet_HatchingPotion_\(firstDropNotification.hatchingPotion ?? "")")
potionView.backgroundColor = ThemeService.shared.theme.windowBackgroundColor
potionView.cornerRadius = 4
potionView.contentMode = .center
iconStackView.addArrangedSubview(potionView)
potionView.addWidthConstraint(width: 80)
stackView.addArrangedSubview(iconStackView)
iconStackView.addHeightConstraint(height: 80)
let firstLabel = UILabel()
firstLabel.text = L10n.firstDropExplanation1
firstLabel.textColor = ThemeService.shared.theme.ternaryTextColor
firstLabel.font = .systemFont(ofSize: 14)
firstLabel.textAlignment = .center
firstLabel.numberOfLines = 0
stackView.addArrangedSubview(firstLabel)
let firstSize = firstLabel.sizeThatFits(CGSize(width: 240, height: 600))
firstLabel.addHeightConstraint(height: firstSize.height)
let secondLabel = UILabel()
secondLabel.text = L10n.firstDropExplanation2
secondLabel.textColor = ThemeService.shared.theme.secondaryTextColor
secondLabel.font = .systemFont(ofSize: 14)
secondLabel.textAlignment = .center
secondLabel.numberOfLines = 0
stackView.addArrangedSubview(secondLabel)
let size = secondLabel.sizeThatFits(CGSize(width: 240, height: 600))
secondLabel.addHeightConstraint(height: size.height)
alert.contentView = stackView
alert.addAction(title: L10n.goToItems, isMainAction: true) { _ in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
RouterHandler.shared.handle(urlString: "/inventory/items")
}
}
alert.addCloseAction()
alert.enqueue()
return true
}
static func displayAchievement(notification: NotificationProtocol, isOnboarding: Bool, isLastOnboardingAchievement: Bool) -> Bool {
userRepository.retrieveUser().observeCompleted {}
userRepository.readNotification(notification: notification).observeCompleted {}
if !configRepository.bool(variable: .enableAdventureGuide) {
if isOnboarding || notification.type == HabiticaNotificationType.achievementOnboardingComplete {
return true
}
}
if isOnboarding {
Analytics.logEvent(notification.achievementKey ?? "", parameters: nil)
}
if notification.type == HabiticaNotificationType.achievementOnboardingComplete {
Analytics.logEvent(notification.type.rawValue, parameters: nil)
Analytics.setUserProperty("true", forName: "completedOnboarding")
}
let alert = AchievementAlertController()
alert.setNotification(notification: notification, isOnboarding: isOnboarding, isLastOnboardingAchievement: isLastOnboardingAchievement)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
// add a slight delay to make sure that any running VC transitions are done
alert.enqueue()
}
return true
}
}
| gpl-3.0 |
ZeeQL/ZeeQL3 | Sources/ZeeQL/Access/AdaptorChannelPool.swift | 1 | 7414 | //
// AdaptorChannelPool.swift
// ZeeQL3
//
// Copyright © 2018-2020 ZeeZide GmbH. All rights reserved.
//
import Foundation
public protocol AdaptorChannelPool {
func grab() -> AdaptorChannel?
func add(_ channel: AdaptorChannel)
}
// Those are not great, but OKayish.
// The expiration queue probably forks an own thread.
/**
* A naive pool which keeps open just a single connection.
*
* Usage:
*
* private var pool = SingleConnectionPool(maxAge: 10)
*
* open func openChannelFromPool() throws -> AdaptorChannel {
* return pool.grab() ?? (try openChannel())
* }
*
* open func releaseChannel(_ channel: AdaptorChannel) {
* guard let pgChannel = channel as? PostgreSQLAdaptorChannel else {
* assertionFailure("unexpected channel type!")
* return
* }
* guard pgChannel.handle != nil else { return } // closed
*
* pool.add(pgChannel)
* }
*
*/
public final class SingleConnectionPool: AdaptorChannelPool {
struct Entry {
let releaseDate : Date
let connection : AdaptorChannel
var age : TimeInterval { return -(releaseDate.timeIntervalSinceNow) }
}
private let maxAge : TimeInterval
private let lock = NSLock()
private let expirationQueue = DispatchQueue(label: "de.zeezide.zeeql.expire")
private var entry : Entry? // here we just pool one :-)
private var gc : DispatchWorkItem?
public init(maxAge: TimeInterval) {
self.maxAge = maxAge
assert(maxAge > 0)
}
public func grab() -> AdaptorChannel? {
lock.lock(); defer { entry = nil; lock.unlock() }
return entry?.connection
}
public func add(_ channel: AdaptorChannel) {
guard !channel.isTransactionInProgress else {
globalZeeQLLogger.warn("releasing a channel w/ an open TX:", channel)
do {
try channel.rollback()
}
catch {
globalZeeQLLogger.warn("failed to rollback TX in released channel:",
error)
}
return // do not pool such
}
lock.lock()
let doAdd = entry == nil
if doAdd {
entry = Entry(releaseDate: Date(), connection: channel)
}
lock.unlock()
if doAdd {
globalZeeQLLogger.info("adding channel to pool:", channel)
}
else {
globalZeeQLLogger.info("did not add channel to pool:", channel)
}
expirationQueue.async {
if self.gc != nil { return } // already running
self.gc = DispatchWorkItem(block: self.expire)
self.expirationQueue.asyncAfter(deadline: .now() + .seconds(1),
execute: self.gc!)
}
}
private func expire() {
let rerun : Bool
do {
lock.lock(); defer { lock.unlock() }
if let entry = entry {
rerun = entry.age > maxAge
if !rerun { self.entry = nil }
}
else { rerun = false }
}
if rerun {
gc = DispatchWorkItem(block: self.expire)
expirationQueue.asyncAfter(deadline: .now() + .seconds(1),
execute: gc!)
}
else {
gc = nil
}
}
}
/**
* A naive pool which keeps open a number of connections.
*
* Usage:
*
* private var pool = SimpleAdaptorChannelPool(maxAge: 10)
*
* open func openChannelFromPool() throws -> AdaptorChannel {
* return pool.grab() ?? (try openChannel())
* }
*
* open func releaseChannel(_ channel: AdaptorChannel) {
* guard let pgChannel = channel as? PostgreSQLAdaptorChannel else {
* assertionFailure("unexpected channel type!")
* return
* }
* guard pgChannel.handle != nil else { return } // closed
* pool.add(pgChannel)
* }
*
*/
public final class SimpleAdaptorChannelPool: AdaptorChannelPool {
struct Entry {
let releaseDate : Date
let connection : AdaptorChannel
var age : TimeInterval { return -(releaseDate.timeIntervalSinceNow) }
}
private let maxSize : Int
private let maxAge : TimeInterval
private let lock = NSLock()
private let expirationQueue = DispatchQueue(label: "de.zeezide.zeeql.expire")
private var entries = [ Entry ]()
private var gc : DispatchWorkItem?
public init(maxSize: Int, maxAge: TimeInterval) {
assert(maxSize >= 0)
assert(maxSize > 0 && maxSize < 128) // weird size
assert(maxAge > 0)
self.maxSize = max(0, maxSize)
self.maxAge = maxAge
}
public func grab() -> AdaptorChannel? {
lock.lock()
let entry = entries.popLast()
lock.unlock()
return entry?.connection
}
public func add(_ channel: AdaptorChannel) {
guard !channel.isTransactionInProgress else {
globalZeeQLLogger.warn("release a channel w/ an open TX:", channel)
assertionFailure("releasing a channel w/ an open TX")
do {
try channel.rollback()
}
catch {
globalZeeQLLogger.warn("failed to rollback TX in released channel:",
error)
}
return // do not pool such
}
lock.lock()
let doAdd = entries.count < maxSize
if doAdd {
let entry = Entry(releaseDate: Date(), connection: channel)
entries.append(entry)
}
lock.unlock()
if doAdd {
globalZeeQLLogger.info("adding channel to pool:", channel)
}
else {
globalZeeQLLogger.info("did not add channel to pool:", channel)
}
expirationQueue.async {
if self.gc != nil { return } // already running
let now = Date()
self.lock.lock()
let hasContent = !self.entries.isEmpty
let maxAge = self.entries.reduce(0) {
max($0, -($1.releaseDate.timeIntervalSince(now)))
}
self.lock.unlock()
guard hasContent else { return } // no entries
if maxAge > self.maxAge {
return self.expire()
}
let left = self.maxAge - maxAge
self.gc = DispatchWorkItem(block: self.expire)
self.expirationQueue
.asyncAfter(deadline: .now() + .milliseconds(Int(left * 1000)),
execute: self.gc!)
}
}
private func expire() { // Q: expirationQueue
let rerun : Bool
var maxAge : TimeInterval = 0
var stats : ( expired: Int, alive: Int ) = ( 0, 0 )
do {
lock.lock(); defer { lock.unlock() }
let count = entries.count
if count > 0 {
let now = Date()
for ( idx, entry ) in entries.enumerated().reversed() {
let age = -(entry.releaseDate.timeIntervalSince(now))
if age >= self.maxAge {
entries.remove(at: idx)
stats.expired += 1
}
else {
maxAge = max(maxAge, age)
stats.alive += 1
}
}
rerun = !entries.isEmpty
}
else {
rerun = false
}
}
if stats.expired > 0 && stats.alive > 0 {
globalZeeQLLogger
.info("pool expired #\(stats.expired) alive #\(stats.alive)",
rerun ? "rerun" : "done")
}
if rerun {
let left = self.maxAge - maxAge
gc = DispatchWorkItem(block: self.expire)
expirationQueue
.asyncAfter(deadline: .now() + .milliseconds(Int(left * 1000)),
execute: self.gc!)
}
else {
gc = nil
}
}
}
| apache-2.0 |
kenwilcox/AdaptiveWeather | AdaptiveWeatherTests/AdaptiveWeatherTests.swift | 1 | 931 | //
// AdaptiveWeatherTests.swift
// AdaptiveWeatherTests
//
// Created by Kenneth Wilcox on 12/29/14.
// Copyright (c) 2014 Kenneth Wilcox. All rights reserved.
//
import UIKit
import XCTest
class AdaptiveWeatherTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
fwagner/WPJsonAPI | Source/WPJOAuth2Manager.swift | 1 | 2540 | //
// WPJOAuth2Manager.swift
// WordpressJSONApi
//
// Created by Flo on 08.09.15.
// Copyright (c) 2015 Florian Wagner. All rights reserved.
//
import Foundation
public class WPJOAuth2Manager {
public var configuration : WPJOAuth2Configuration;
public var tokenStore : WPJOAuth2TokenStore;
public convenience init()
{
self.init(configuration: WPJOAuth2Configuration());
}
public convenience init(configuration : WPJOAuth2Configuration) {
self.init(configuration: configuration, tokenStore : WPJOAuth2TokenStore());
}
public init(configuration : WPJOAuth2Configuration, tokenStore : WPJOAuth2TokenStore)
{
self.configuration = configuration;
self.tokenStore = tokenStore;
}
public func buildAuthenticationURL() -> NSURL
{
var authorizationURL : NSURLComponents = NSURLComponents(string: self.configuration.authorizationEndpoint)!;
authorizationURL.queryItems = [
NSURLQueryItem(name: "client_id", value: self.configuration.clientId),
NSURLQueryItem(name: "redirect_uri", value: self.configuration.redirectURL),
NSURLQueryItem(name: "response_type", value: "token"),
NSURLQueryItem(name: "scope", value: "global")
];
return authorizationURL.URL!;
}
public func isAuthenticationRedirect(url : NSURL) -> Bool {
let urlAsString = url.scheme! + "://" + url.host! + url.path!;
debugPrintln(urlAsString + " == " + self.configuration.redirectURL);
return urlAsString == self.configuration.redirectURL;
}
public func handleRedirectWithToken(url : NSURL) -> WPJOAuth2Token? {
if let token = self.extractTokenFromFragment(url.fragmentComponents()) {
self.tokenStore.saveToken(token);
return token;
} else {
return nil;
}
}
public func hasSession() -> Bool {
return self.tokenStore.hasValidToken();
}
public func getCurrentToken() -> WPJOAuth2Token? {
return self.tokenStore.retrieveToken();
}
private func extractTokenFromFragment(fragmentComponents : [String : String]) -> WPJOAuth2Token? {
if let token = fragmentComponents["access_token"], expiryInterval = fragmentComponents["expires_in"]?.toInt() {
return WPJOAuth2Token(token: token.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!, expiresIn: expiryInterval);
}
return nil;
}
}
| mit |
groue/GRDB.swift | Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerEditionView.swift | 1 | 1278 | import SwiftUI
/// The view that edits an existing player.
struct PlayerEditionView: View {
/// Write access to the database
@Environment(\.appDatabase) private var appDatabase
@Environment(\.isPresented) private var isPresented
private let player: Player
@State private var form: PlayerForm
init(player: Player) {
self.player = player
self.form = PlayerForm(player)
}
var body: some View {
PlayerFormView(form: $form)
.onChange(of: isPresented) { isPresented in
// Save when back button is pressed
if !isPresented {
Task {
var savedPlayer = player
form.apply(to: &savedPlayer)
// Ignore error because I don't know how to cancel the
// back button and present the error
try? await appDatabase.savePlayer(&savedPlayer)
}
}
}
}
}
struct PlayerEditionView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerEditionView(player: Player.makeRandom())
.navigationBarTitle("Player Edition")
}
}
}
| mit |
Sajjon/ViewComposer | Source/Classes/ViewStyle/UIView+ViewStyle/UIStackView+ViewStyle.swift | 1 | 1214 | //
// UIStackView+ViewStyle.swift
// ViewComposer
//
// Created by Alexander Cyon on 2017-06-15.
//
//
import Foundation
internal extension UIStackView {
func apply(_ style: ViewStyle) {
style.attributes.forEach {
switch $0 {
case .alignment(let alignment):
self.alignment = alignment
case .axis(let axis):
self.axis = axis
case .spacing(let spacing):
self.spacing = spacing
case .distribution(let distribution):
self.distribution = distribution
case .baselineRelative(let isBaselineRelativeArrangement):
self.isBaselineRelativeArrangement = isBaselineRelativeArrangement
case .marginsRelative(let isLayoutMarginsRelativeArrangement):
self.isLayoutMarginsRelativeArrangement = isLayoutMarginsRelativeArrangement
case .margin(let marginExpressible):
let margin = marginExpressible.margin
self.layoutMargins = margin.insets
self.isLayoutMarginsRelativeArrangement = margin.isRelative
default:
break
}
}
}
}
| mit |
hgani/ganilib-ios | glib/Classes/View/GBarButtonItem.swift | 1 | 735 | import SwiftIconFont
import UIKit
open class GBarButtonItem: UIBarButtonItem {
private var onClick: (() -> Void)?
public func onClick(_ command: @escaping () -> Void) -> Self {
onClick = command
target = self
action = #selector(performClick)
return self
}
@objc private func performClick() {
if let callback = self.onClick {
callback()
}
}
public func icon(_ icon: GIcon) -> Self {
super.icon(from: icon.font, code: icon.code, ofSize: 20)
return self
}
public func title(_ text: String) -> Self {
super.title = text
return self
}
public func end() {
// End chaining initialisation
}
}
| mit |
IdeasOnCanvas/Ashton | Sources/Ashton/CrossPlatformCompatibility.swift | 1 | 2078 | //
// CrossPlatformCompatibility.swift
// Ashton
//
// Created by Michael Schwarz on 11.12.17.
// Copyright © 2017 Michael Schwarz. All rights reserved.
//
#if os(iOS)
import UIKit
typealias Font = UIFont
typealias FontDescriptor = UIFontDescriptor
typealias FontDescriptorSymbolicTraits = UIFontDescriptor.SymbolicTraits
typealias Color = UIColor
extension UIFont {
class var cpFamilyNames: [String] { return UIFont.familyNames }
var cpFamilyName: String { return self.familyName }
class func cpFontNames(forFamilyName familyName: String) -> [String] {
return UIFont.fontNames(forFamilyName: familyName)
}
}
extension UIFontDescriptor {
var cpPostscriptName: String { return self.postscriptName }
}
extension NSAttributedString.Key {
static let superscript = NSAttributedString.Key(rawValue: "NSSuperScript")
}
extension FontDescriptor.FeatureKey {
static let selectorIdentifier = FontDescriptor.FeatureKey("CTFeatureSelectorIdentifier")
static let cpTypeIdentifier = FontDescriptor.FeatureKey("CTFeatureTypeIdentifier")
}
#elseif os(macOS)
import AppKit
typealias Font = NSFont
typealias FontDescriptor = NSFontDescriptor
typealias FontDescriptorSymbolicTraits = NSFontDescriptor.SymbolicTraits
typealias Color = NSColor
extension NSFont {
class var cpFamilyNames: [String] { return NSFontManager.shared.availableFontFamilies }
var cpFamilyName: String { return self.familyName ?? "" }
class func cpFontNames(forFamilyName familyName: String) -> [String] {
let fontManager = NSFontManager.shared
let availableMembers = fontManager.availableMembers(ofFontFamily: familyName)
return availableMembers?.compactMap { member in
let memberArray = member as Array<Any>
return memberArray.first as? String
} ?? []
}
}
extension NSFontDescriptor {
var cpPostscriptName: String { return self.postscriptName ?? "" }
}
extension FontDescriptor.FeatureKey {
static let cpTypeIdentifier = FontDescriptor.FeatureKey("CTFeatureTypeIdentifier")
}
#endif
| mit |
nathawes/swift | test/stdlib/NSStringAPI.swift | 17 | 61870 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
// FIXME: rdar://problem/31311598
// UNSUPPORTED: OS=ios
// UNSUPPORTED: OS=tvos
// UNSUPPORTED: OS=watchos
//
// Tests for the NSString APIs as exposed by String
//
import StdlibUnittest
import Foundation
import StdlibUnittestFoundationExtras
// The most simple subclass of NSString that CoreFoundation does not know
// about.
class NonContiguousNSString : NSString {
required init(coder aDecoder: NSCoder) {
fatalError("don't call this initializer")
}
required init(itemProviderData data: Data, typeIdentifier: String) throws {
fatalError("don't call this initializer")
}
override init() {
_value = []
super.init()
}
init(_ value: [UInt16]) {
_value = value
super.init()
}
@objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any {
// Ensure that copying this string produces a class that CoreFoundation
// does not know about.
return self
}
@objc override var length: Int {
return _value.count
}
@objc override func character(at index: Int) -> unichar {
return _value[index]
}
var _value: [UInt16]
}
let temporaryFileContents =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,\n" +
"sed do eiusmod tempor incididunt ut labore et dolore magna\n" +
"aliqua.\n"
func createNSStringTemporaryFile()
-> (existingPath: String, nonExistentPath: String) {
let existingPath =
createTemporaryFile("NSStringAPIs.", ".txt", temporaryFileContents)
let nonExistentPath = existingPath + "-NoNeXiStEnT"
return (existingPath, nonExistentPath)
}
var NSStringAPIs = TestSuite("NSStringAPIs")
NSStringAPIs.test("Encodings") {
let availableEncodings: [String.Encoding] = String.availableStringEncodings
expectNotEqual(0, availableEncodings.count)
let defaultCStringEncoding = String.defaultCStringEncoding
expectTrue(availableEncodings.contains(defaultCStringEncoding))
expectNotEqual("", String.localizedName(of: .utf8))
}
NSStringAPIs.test("NSStringEncoding") {
// Make sure NSStringEncoding and its values are type-compatible.
var enc: String.Encoding
enc = .windowsCP1250
enc = .utf32LittleEndian
enc = .utf32BigEndian
enc = .ascii
enc = .utf8
expectEqual(.utf8, enc)
}
NSStringAPIs.test("NSStringEncoding.Hashable") {
let instances: [String.Encoding] = [
.windowsCP1250,
.utf32LittleEndian,
.utf32BigEndian,
.ascii,
.utf8,
]
checkHashable(instances, equalityOracle: { $0 == $1 })
}
NSStringAPIs.test("localizedStringWithFormat(_:...)") {
let world: NSString = "world"
expectEqual("Hello, world!%42", String.localizedStringWithFormat(
"Hello, %@!%%%ld", world, 42))
withOverriddenLocaleCurrentLocale("en_US") {
expectEqual("0.5", String.localizedStringWithFormat("%g", 0.5))
}
withOverriddenLocaleCurrentLocale("uk") {
expectEqual("0,5", String.localizedStringWithFormat("%g", 0.5))
}
}
NSStringAPIs.test("init(contentsOfFile:encoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
do {
let content = try String(
contentsOfFile: existingPath, encoding: .ascii)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
do {
let _ = try String(
contentsOfFile: nonExistentPath, encoding: .ascii)
expectUnreachable()
} catch {
}
}
NSStringAPIs.test("init(contentsOfFile:usedEncoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
do {
var usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
let content = try String(
contentsOfFile: existingPath, usedEncoding: &usedEncoding)
expectNotEqual(0, usedEncoding.rawValue)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
let usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
do {
_ = try String(contentsOfFile: nonExistentPath)
expectUnreachable()
} catch {
expectEqual(0, usedEncoding.rawValue)
}
}
NSStringAPIs.test("init(contentsOf:encoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
let existingURL = URL(string: "file://" + existingPath)!
let nonExistentURL = URL(string: "file://" + nonExistentPath)!
do {
let content = try String(
contentsOf: existingURL, encoding: .ascii)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
do {
_ = try String(contentsOf: nonExistentURL, encoding: .ascii)
expectUnreachable()
} catch {
}
}
NSStringAPIs.test("init(contentsOf:usedEncoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
let existingURL = URL(string: "file://" + existingPath)!
let nonExistentURL = URL(string: "file://" + nonExistentPath)!
do {
var usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
let content = try String(
contentsOf: existingURL, usedEncoding: &usedEncoding)
expectNotEqual(0, usedEncoding.rawValue)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
var usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
do {
_ = try String(contentsOf: nonExistentURL, usedEncoding: &usedEncoding)
expectUnreachable()
} catch {
expectEqual(0, usedEncoding.rawValue)
}
}
NSStringAPIs.test("init(cString_:encoding:)") {
expectEqual("foo, a basmati bar!",
String(cString:
"foo, a basmati bar!", encoding: String.defaultCStringEncoding))
}
NSStringAPIs.test("init(utf8String:)") {
let s = "foo あいう"
let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100)
var i = 0
for b in s.utf8 {
up[i] = b
i += 1
}
up[i] = 0
let cstr = UnsafeMutableRawPointer(up)
.bindMemory(to: CChar.self, capacity: 100)
expectEqual(s, String(utf8String: cstr))
up.deallocate()
}
NSStringAPIs.test("canBeConvertedToEncoding(_:)") {
expectTrue("foo".canBeConverted(to: .ascii))
expectFalse("あいう".canBeConverted(to: .ascii))
}
NSStringAPIs.test("capitalized") {
expectEqual("Foo Foo Foo Foo", "foo Foo fOO FOO".capitalized)
expectEqual("Жжж", "жжж".capitalized)
}
NSStringAPIs.test("localizedCapitalized") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectEqual(
"Foo Foo Foo Foo",
"foo Foo fOO FOO".localizedCapitalized)
expectEqual("Жжж", "жжж".localizedCapitalized)
return ()
}
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
withOverriddenLocaleCurrentLocale("en") {
expectEqual("Iii Iii", "iii III".localizedCapitalized)
}
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0130}ii Iıı", "iii III".localizedCapitalized)
}
}
}
/// Checks that executing the operation in the locale with the given
/// `localeID` (or if `localeID` is `nil`, the current locale) gives
/// the expected result, and that executing the operation with a nil
/// locale gives the same result as explicitly passing the system
/// locale.
///
/// - Parameter expected: the expected result when the operation is
/// executed in the given localeID
func expectLocalizedEquality(
_ expected: String,
_ op: (_: Locale?) -> String,
_ localeID: String? = nil,
_ message: @autoclosure () -> String = "",
showFrame: Bool = true,
stackTrace: SourceLocStack = SourceLocStack(),
file: String = #file, line: UInt = #line
) {
let trace = stackTrace.pushIf(showFrame, file: file, line: line)
let locale = localeID.map {
Locale(identifier: $0)
} ?? Locale.current
expectEqual(
expected, op(locale),
message(), stackTrace: trace)
}
NSStringAPIs.test("capitalizedString(with:)") {
expectLocalizedEquality(
"Foo Foo Foo Foo",
{ loc in "foo Foo fOO FOO".capitalized(with: loc) })
expectLocalizedEquality("Жжж", { loc in "жжж".capitalized(with: loc) })
expectEqual(
"Foo Foo Foo Foo",
"foo Foo fOO FOO".capitalized(with: nil))
expectEqual("Жжж", "жжж".capitalized(with: nil))
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
expectLocalizedEquality(
"Iii Iii",
{ loc in "iii III".capitalized(with: loc) }, "en")
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
expectLocalizedEquality(
"İii Iıı",
{ loc in "iii III".capitalized(with: loc) }, "tr")
}
NSStringAPIs.test("caseInsensitiveCompare(_:)") {
expectEqual(ComparisonResult.orderedSame,
"abCD".caseInsensitiveCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"abCD".caseInsensitiveCompare("AbCdE"))
expectEqual(ComparisonResult.orderedSame,
"абвг".caseInsensitiveCompare("АбВг"))
expectEqual(ComparisonResult.orderedAscending,
"абВГ".caseInsensitiveCompare("АбВгД"))
}
NSStringAPIs.test("commonPrefix(with:options:)") {
expectEqual("ab",
"abcd".commonPrefix(with: "abdc", options: []))
expectEqual("abC",
"abCd".commonPrefix(with: "abce", options: .caseInsensitive))
expectEqual("аб",
"абвг".commonPrefix(with: "абгв", options: []))
expectEqual("абВ",
"абВг".commonPrefix(with: "абвд", options: .caseInsensitive))
}
NSStringAPIs.test("compare(_:options:range:locale:)") {
expectEqual(ComparisonResult.orderedSame,
"abc".compare("abc"))
expectEqual(ComparisonResult.orderedAscending,
"абв".compare("где"))
expectEqual(ComparisonResult.orderedSame,
"abc".compare("abC", options: .caseInsensitive))
expectEqual(ComparisonResult.orderedSame,
"абв".compare("абВ", options: .caseInsensitive))
do {
let s = "abcd"
let r = s.index(after: s.startIndex)..<s.endIndex
expectEqual(ComparisonResult.orderedSame,
s.compare("bcd", range: r))
}
do {
let s = "абвг"
let r = s.index(after: s.startIndex)..<s.endIndex
expectEqual(ComparisonResult.orderedSame,
s.compare("бвг", range: r))
}
expectEqual(ComparisonResult.orderedSame,
"abc".compare("abc", locale: Locale.current))
expectEqual(ComparisonResult.orderedSame,
"абв".compare("абв", locale: Locale.current))
}
NSStringAPIs.test("completePath(into:caseSensitive:matchesInto:filterTypes)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
do {
let count = nonExistentPath.completePath(caseSensitive: false)
expectEqual(0, count)
}
do {
var outputName = "None Found"
let count = nonExistentPath.completePath(
into: &outputName, caseSensitive: false)
expectEqual(0, count)
expectEqual("None Found", outputName)
}
do {
var outputName = "None Found"
var outputArray: [String] = ["foo", "bar"]
let count = nonExistentPath.completePath(
into: &outputName, caseSensitive: false, matchesInto: &outputArray)
expectEqual(0, count)
expectEqual("None Found", outputName)
expectEqual(["foo", "bar"], outputArray)
}
do {
let count = existingPath.completePath(caseSensitive: false)
expectEqual(1, count)
}
do {
var outputName = "None Found"
let count = existingPath.completePath(
into: &outputName, caseSensitive: false)
expectEqual(1, count)
expectEqual(existingPath, outputName)
}
do {
var outputName = "None Found"
var outputArray: [String] = ["foo", "bar"]
let count = existingPath.completePath(
into: &outputName, caseSensitive: false, matchesInto: &outputArray)
expectEqual(1, count)
expectEqual(existingPath, outputName)
expectEqual([existingPath], outputArray)
}
do {
var outputName = "None Found"
let count = existingPath.completePath(
into: &outputName, caseSensitive: false, filterTypes: ["txt"])
expectEqual(1, count)
expectEqual(existingPath, outputName)
}
}
NSStringAPIs.test("components(separatedBy:) (NSCharacterSet)") {
expectEqual([""], "".components(
separatedBy: CharacterSet.decimalDigits))
expectEqual(
["абв", "", "あいう", "abc"],
"абв12あいう3abc".components(
separatedBy: CharacterSet.decimalDigits))
expectEqual(
["абв", "", "あいう", "abc"],
"абв\u{1F601}\u{1F602}あいう\u{1F603}abc"
.components(
separatedBy: CharacterSet(charactersIn: "\u{1F601}\u{1F602}\u{1F603}")))
// Performs Unicode scalar comparison.
expectEqual(
["abcし\u{3099}def"],
"abcし\u{3099}def".components(
separatedBy: CharacterSet(charactersIn: "\u{3058}")))
}
NSStringAPIs.test("components(separatedBy:) (String)") {
expectEqual([""], "".components(separatedBy: "//"))
expectEqual(
["абв", "あいう", "abc"],
"абв//あいう//abc".components(separatedBy: "//"))
// Performs normalization.
expectEqual(
["abc", "def"],
"abcし\u{3099}def".components(separatedBy: "\u{3058}"))
}
NSStringAPIs.test("cString(usingEncoding:)") {
expectNil("абв".cString(using: .ascii))
let expectedBytes: [UInt8] = [ 0xd0, 0xb0, 0xd0, 0xb1, 0xd0, 0xb2, 0 ]
let expectedStr: [CChar] = expectedBytes.map { CChar(bitPattern: $0) }
expectEqual(expectedStr,
"абв".cString(using: .utf8)!)
}
NSStringAPIs.test("data(usingEncoding:allowLossyConversion:)") {
expectNil("あいう".data(using: .ascii, allowLossyConversion: false))
do {
let data = "あいう".data(using: .utf8)!
let expectedBytes: [UInt8] = [
0xe3, 0x81, 0x82, 0xe3, 0x81, 0x84, 0xe3, 0x81, 0x86
]
expectEqualSequence(expectedBytes, data)
}
}
NSStringAPIs.test("init(data:encoding:)") {
let bytes: [UInt8] = [0xe3, 0x81, 0x82, 0xe3, 0x81, 0x84, 0xe3, 0x81, 0x86]
let data = Data(bytes: bytes)
expectNil(String(data: data, encoding: .nonLossyASCII))
expectEqualSequence(
"あいう",
String(data: data, encoding: .utf8)!)
}
NSStringAPIs.test("decomposedStringWithCanonicalMapping") {
expectEqual("abc", "abc".decomposedStringWithCanonicalMapping)
expectEqual("\u{305f}\u{3099}くてん", "だくてん".decomposedStringWithCanonicalMapping)
expectEqual("\u{ff80}\u{ff9e}クテン", "ダクテン".decomposedStringWithCanonicalMapping)
}
NSStringAPIs.test("decomposedStringWithCompatibilityMapping") {
expectEqual("abc", "abc".decomposedStringWithCompatibilityMapping)
expectEqual("\u{30bf}\u{3099}クテン", "ダクテン".decomposedStringWithCompatibilityMapping)
}
NSStringAPIs.test("enumerateLines(_:)") {
var lines: [String] = []
"abc\n\ndefghi\njklm".enumerateLines {
(line: String, stop: inout Bool)
in
lines.append(line)
if lines.count == 3 {
stop = true
}
}
expectEqual(["abc", "", "defghi"], lines)
}
NSStringAPIs.test("enumerateLinguisticTagsIn(_:scheme:options:orthography:_:") {
let s: String = "Абв. Глокая куздра штеко будланула бокра и кудрячит бокрёнка. Абв."
let startIndex = s.index(s.startIndex, offsetBy: 5)
let endIndex = s.index(s.startIndex, offsetBy: 62)
var tags: [String] = []
var tokens: [String] = []
var sentences: [String] = []
let range = startIndex..<endIndex
let scheme: NSLinguisticTagScheme = .tokenType
s.enumerateLinguisticTags(in: range,
scheme: scheme.rawValue,
options: [],
orthography: nil) {
(tag: String, tokenRange: Range<String.Index>, sentenceRange: Range<String.Index>, stop: inout Bool)
in
tags.append(tag)
tokens.append(String(s[tokenRange]))
sentences.append(String(s[sentenceRange]))
if tags.count == 3 {
stop = true
}
}
expectEqual([
NSLinguisticTag.word.rawValue,
NSLinguisticTag.whitespace.rawValue,
NSLinguisticTag.word.rawValue
], tags)
expectEqual(["Глокая", " ", "куздра"], tokens)
let sentence = String(s[startIndex..<endIndex])
expectEqual([sentence, sentence, sentence], sentences)
}
NSStringAPIs.test("enumerateSubstringsIn(_:options:_:)") {
let s = "え\u{304b}\u{3099}お\u{263a}\u{fe0f}😀😊"
let startIndex = s.index(s.startIndex, offsetBy: 1)
let endIndex = s.index(s.startIndex, offsetBy: 5)
do {
var substrings: [String] = []
// FIXME(strings): this API should probably change to accept a Substring?
// instead of a String? and a range.
s.enumerateSubstrings(in: startIndex..<endIndex,
options: String.EnumerationOptions.byComposedCharacterSequences) {
(substring: String?, substringRange: Range<String.Index>,
enclosingRange: Range<String.Index>, stop: inout Bool)
in
substrings.append(substring!)
expectEqual(substring, String(s[substringRange]))
expectEqual(substring, String(s[enclosingRange]))
}
expectEqual(["\u{304b}\u{3099}", "お", "☺️", "😀"], substrings)
}
do {
var substrings: [String] = []
s.enumerateSubstrings(in: startIndex..<endIndex,
options: [.byComposedCharacterSequences, .substringNotRequired]) {
(substring_: String?, substringRange: Range<String.Index>,
enclosingRange: Range<String.Index>, stop: inout Bool)
in
expectNil(substring_)
let substring = s[substringRange]
substrings.append(String(substring))
expectEqual(substring, s[enclosingRange])
}
expectEqual(["\u{304b}\u{3099}", "お", "☺️", "😀"], substrings)
}
}
NSStringAPIs.test("fastestEncoding") {
let availableEncodings: [String.Encoding] = String.availableStringEncodings
expectTrue(availableEncodings.contains("abc".fastestEncoding))
}
NSStringAPIs.test("getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)") {
let s = "abc абв def где gh жз zzz"
let startIndex = s.index(s.startIndex, offsetBy: 8)
let endIndex = s.index(s.startIndex, offsetBy: 22)
do {
// 'maxLength' is limiting.
let bufferLength = 100
var expectedStr: [UInt8] = Array("def где ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: 11, usedLength: &usedLength,
encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(11, usedLength)
expectEqual(remainingRange.lowerBound, s.index(startIndex, offsetBy: 8))
expectEqual(remainingRange.upperBound, endIndex)
}
do {
// 'bufferLength' is limiting. Note that the buffer is not filled
// completely, since doing that would break a UTF sequence.
let bufferLength = 5
var expectedStr: [UInt8] = Array("def ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: 11, usedLength: &usedLength,
encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(4, usedLength)
expectEqual(remainingRange.lowerBound, s.index(startIndex, offsetBy: 4))
expectEqual(remainingRange.upperBound, endIndex)
}
do {
// 'range' is converted completely.
let bufferLength = 100
var expectedStr: [UInt8] = Array("def где gh жз ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: bufferLength,
usedLength: &usedLength, encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(19, usedLength)
expectEqual(remainingRange.lowerBound, endIndex)
expectEqual(remainingRange.upperBound, endIndex)
}
do {
// Inappropriate encoding.
let bufferLength = 100
var expectedStr: [UInt8] = Array("def ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: bufferLength,
usedLength: &usedLength, encoding: .ascii,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(4, usedLength)
expectEqual(remainingRange.lowerBound, s.index(startIndex, offsetBy: 4))
expectEqual(remainingRange.upperBound, endIndex)
}
}
NSStringAPIs.test("getCString(_:maxLength:encoding:)") {
let s = "abc あかさた"
do {
// A significantly too small buffer
let bufferLength = 1
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = s.getCString(&buffer, maxLength: 100,
encoding: .utf8)
expectFalse(result)
let result2 = s.getCString(&buffer, maxLength: 1,
encoding: .utf8)
expectFalse(result2)
}
do {
// The largest buffer that cannot accommodate the string plus null terminator.
let bufferLength = 16
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = s.getCString(&buffer, maxLength: 100,
encoding: .utf8)
expectFalse(result)
let result2 = s.getCString(&buffer, maxLength: 16,
encoding: .utf8)
expectFalse(result2)
}
do {
// The smallest buffer where the result can fit.
let bufferLength = 17
var expectedStr = "abc あかさた\0".utf8.map { CChar(bitPattern: $0) }
while (expectedStr.count != bufferLength) {
expectedStr.append(CChar(bitPattern: 0xff))
}
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = s.getCString(&buffer, maxLength: 100,
encoding: .utf8)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
let result2 = s.getCString(&buffer, maxLength: 17,
encoding: .utf8)
expectTrue(result2)
expectEqualSequence(expectedStr, buffer)
}
do {
// Limit buffer size with 'maxLength'.
let bufferLength = 100
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = s.getCString(&buffer, maxLength: 8,
encoding: .utf8)
expectFalse(result)
}
do {
// String with unpaired surrogates.
let illFormedUTF16 = NonContiguousNSString([ 0xd800 ]) as String
let bufferLength = 100
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = illFormedUTF16.getCString(&buffer, maxLength: 100,
encoding: .utf8)
expectFalse(result)
}
}
NSStringAPIs.test("getLineStart(_:end:contentsEnd:forRange:)") {
let s = "Глокая куздра\nштеко будланула\nбокра и кудрячит\nбокрёнка."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
var outStartIndex = s.startIndex
var outLineEndIndex = s.startIndex
var outContentsEndIndex = s.startIndex
s.getLineStart(&outStartIndex, end: &outLineEndIndex,
contentsEnd: &outContentsEndIndex, for: r)
expectEqual("штеко будланула\nбокра и кудрячит\n",
s[outStartIndex..<outLineEndIndex])
expectEqual("штеко будланула\nбокра и кудрячит",
s[outStartIndex..<outContentsEndIndex])
}
}
NSStringAPIs.test("getParagraphStart(_:end:contentsEnd:forRange:)") {
let s = "Глокая куздра\nштеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n Абв."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
var outStartIndex = s.startIndex
var outEndIndex = s.startIndex
var outContentsEndIndex = s.startIndex
s.getParagraphStart(&outStartIndex, end: &outEndIndex,
contentsEnd: &outContentsEndIndex, for: r)
expectEqual("штеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n",
s[outStartIndex..<outEndIndex])
expectEqual("штеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.",
s[outStartIndex..<outContentsEndIndex])
}
}
NSStringAPIs.test("hash") {
let s: String = "abc"
let nsstr: NSString = "abc"
expectEqual(nsstr.hash, s.hash)
}
NSStringAPIs.test("init(bytes:encoding:)") {
var s: String = "abc あかさた"
expectEqual(
s, String(bytes: s.utf8, encoding: .utf8))
/*
FIXME: Test disabled because the NSString documentation is unclear about
what should actually happen in this case.
expectNil(String(bytes: bytes, length: bytes.count,
encoding: .ascii))
*/
// FIXME: add a test where this function actually returns nil.
}
NSStringAPIs.test("init(bytesNoCopy:length:encoding:freeWhenDone:)") {
var s: String = "abc あかさた"
var bytes: [UInt8] = Array(s.utf8)
expectEqual(s, String(bytesNoCopy: &bytes,
length: bytes.count, encoding: .utf8,
freeWhenDone: false))
/*
FIXME: Test disabled because the NSString documentation is unclear about
what should actually happen in this case.
expectNil(String(bytesNoCopy: &bytes, length: bytes.count,
encoding: .ascii, freeWhenDone: false))
*/
// FIXME: add a test where this function actually returns nil.
}
NSStringAPIs.test("init(utf16CodeUnits:count:)") {
let expected = "abc абв \u{0001F60A}"
let chars: [unichar] = Array(expected.utf16)
expectEqual(expected, String(utf16CodeUnits: chars, count: chars.count))
}
NSStringAPIs.test("init(utf16CodeUnitsNoCopy:count:freeWhenDone:)") {
let expected = "abc абв \u{0001F60A}"
let chars: [unichar] = Array(expected.utf16)
expectEqual(expected, String(utf16CodeUnitsNoCopy: chars,
count: chars.count, freeWhenDone: false))
}
NSStringAPIs.test("init(format:_:...)") {
expectEqual("", String(format: ""))
expectEqual(
"abc абв \u{0001F60A}", String(format: "abc абв \u{0001F60A}"))
let world: NSString = "world"
expectEqual("Hello, world!%42",
String(format: "Hello, %@!%%%ld", world, 42))
// test for rdar://problem/18317906
expectEqual("3.12", String(format: "%.2f", 3.123456789))
expectEqual("3.12", NSString(format: "%.2f", 3.123456789))
}
NSStringAPIs.test("init(format:arguments:)") {
expectEqual("", String(format: "", arguments: []))
expectEqual(
"abc абв \u{0001F60A}",
String(format: "abc абв \u{0001F60A}", arguments: []))
let world: NSString = "world"
let args: [CVarArg] = [ world, 42 ]
expectEqual("Hello, world!%42",
String(format: "Hello, %@!%%%ld", arguments: args))
}
NSStringAPIs.test("init(format:locale:_:...)") {
let world: NSString = "world"
expectEqual("Hello, world!%42", String(format: "Hello, %@!%%%ld",
locale: nil, world, 42))
}
NSStringAPIs.test("init(format:locale:arguments:)") {
let world: NSString = "world"
let args: [CVarArg] = [ world, 42 ]
expectEqual("Hello, world!%42", String(format: "Hello, %@!%%%ld",
locale: nil, arguments: args))
}
NSStringAPIs.test("utf16Count") {
expectEqual(1, "a".utf16.count)
expectEqual(2, "\u{0001F60A}".utf16.count)
}
NSStringAPIs.test("lengthOfBytesUsingEncoding(_:)") {
expectEqual(1, "a".lengthOfBytes(using: .utf8))
expectEqual(2, "あ".lengthOfBytes(using: .shiftJIS))
}
NSStringAPIs.test("lineRangeFor(_:)") {
let s = "Глокая куздра\nштеко будланула\nбокра и кудрячит\nбокрёнка."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
let result = s.lineRange(for: r)
expectEqual("штеко будланула\nбокра и кудрячит\n", s[result])
}
}
NSStringAPIs.test("linguisticTagsIn(_:scheme:options:orthography:tokenRanges:)") {
let s: String = "Абв. Глокая куздра штеко будланула бокра и кудрячит бокрёнка. Абв."
let startIndex = s.index(s.startIndex, offsetBy: 5)
let endIndex = s.index(s.startIndex, offsetBy: 17)
var tokenRanges: [Range<String.Index>] = []
let scheme = NSLinguisticTagScheme.tokenType
let tags = s.linguisticTags(in: startIndex..<endIndex,
scheme: scheme.rawValue,
options: [],
orthography: nil, tokenRanges: &tokenRanges)
expectEqual([
NSLinguisticTag.word.rawValue,
NSLinguisticTag.whitespace.rawValue,
NSLinguisticTag.word.rawValue
], tags)
expectEqual(["Глокая", " ", "куздра"],
tokenRanges.map { String(s[$0]) } )
}
NSStringAPIs.test("localizedCaseInsensitiveCompare(_:)") {
expectEqual(ComparisonResult.orderedSame,
"abCD".localizedCaseInsensitiveCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"abCD".localizedCaseInsensitiveCompare("AbCdE"))
expectEqual(ComparisonResult.orderedSame,
"абвг".localizedCaseInsensitiveCompare("АбВг"))
expectEqual(ComparisonResult.orderedAscending,
"абВГ".localizedCaseInsensitiveCompare("АбВгД"))
}
NSStringAPIs.test("localizedCompare(_:)") {
expectEqual(ComparisonResult.orderedAscending,
"abCD".localizedCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"абвг".localizedCompare("АбВг"))
}
NSStringAPIs.test("localizedStandardCompare(_:)") {
expectEqual(ComparisonResult.orderedAscending,
"abCD".localizedStandardCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"абвг".localizedStandardCompare("АбВг"))
}
NSStringAPIs.test("localizedLowercase") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") {
expectEqual("abcd", "abCD".localizedLowercase)
}
withOverriddenLocaleCurrentLocale("en") {
expectEqual("абвг", "абВГ".localizedLowercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("абвг", "абВГ".localizedLowercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("たちつてと", "たちつてと".localizedLowercase)
}
//
// Special casing.
//
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
withOverriddenLocaleCurrentLocale("en") {
expectEqual("\u{0069}\u{0307}", "\u{0130}".localizedLowercase)
}
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0069}", "\u{0130}".localizedLowercase)
}
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
withOverriddenLocaleCurrentLocale("en") {
expectEqual(
"\u{0069}\u{0307}",
"\u{0049}\u{0307}".localizedLowercase)
}
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0069}", "\u{0049}\u{0307}".localizedLowercase)
}
}
}
NSStringAPIs.test("lowercased(with:)") {
expectLocalizedEquality("abcd", { loc in "abCD".lowercased(with: loc) }, "en")
expectLocalizedEquality("абвг", { loc in "абВГ".lowercased(with: loc) }, "en")
expectLocalizedEquality("абвг", { loc in "абВГ".lowercased(with: loc) }, "ru")
expectLocalizedEquality("たちつてと", { loc in "たちつてと".lowercased(with: loc) }, "ru")
//
// Special casing.
//
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectLocalizedEquality("\u{0069}\u{0307}", { loc in "\u{0130}".lowercased(with: loc) }, "en")
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
expectLocalizedEquality("\u{0069}", { loc in "\u{0130}".lowercased(with: loc) }, "tr")
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectLocalizedEquality("\u{0069}\u{0307}", { loc in "\u{0049}\u{0307}".lowercased(with: loc) }, "en")
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
expectLocalizedEquality("\u{0069}", { loc in "\u{0049}\u{0307}".lowercased(with: loc) }, "tr")
}
NSStringAPIs.test("maximumLengthOfBytesUsingEncoding(_:)") {
do {
let s = "abc"
expectLE(s.utf8.count,
s.maximumLengthOfBytes(using: .utf8))
}
do {
let s = "abc абв"
expectLE(s.utf8.count,
s.maximumLengthOfBytes(using: .utf8))
}
do {
let s = "\u{1F60A}"
expectLE(s.utf8.count,
s.maximumLengthOfBytes(using: .utf8))
}
}
NSStringAPIs.test("paragraphRangeFor(_:)") {
let s = "Глокая куздра\nштеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n Абв."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
let result = s.paragraphRange(for: r)
expectEqual("штеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n", s[result])
}
}
NSStringAPIs.test("pathComponents") {
expectEqual([ "/", "foo", "bar" ] as [NSString], ("/foo/bar" as NSString).pathComponents as [NSString])
expectEqual([ "/", "абв", "где" ] as [NSString], ("/абв/где" as NSString).pathComponents as [NSString])
}
NSStringAPIs.test("precomposedStringWithCanonicalMapping") {
expectEqual("abc", "abc".precomposedStringWithCanonicalMapping)
expectEqual("だくてん",
"\u{305f}\u{3099}くてん".precomposedStringWithCanonicalMapping)
expectEqual("ダクテン",
"\u{ff80}\u{ff9e}クテン".precomposedStringWithCanonicalMapping)
expectEqual("\u{fb03}", "\u{fb03}".precomposedStringWithCanonicalMapping)
}
NSStringAPIs.test("precomposedStringWithCompatibilityMapping") {
expectEqual("abc", "abc".precomposedStringWithCompatibilityMapping)
/*
Test disabled because of:
<rdar://problem/17041347> NFKD normalization as implemented by
'precomposedStringWithCompatibilityMapping:' is not idempotent
expectEqual("\u{30c0}クテン",
"\u{ff80}\u{ff9e}クテン".precomposedStringWithCompatibilityMapping)
*/
expectEqual("ffi", "\u{fb03}".precomposedStringWithCompatibilityMapping)
}
NSStringAPIs.test("propertyList()") {
expectEqual(["foo", "bar"],
"(\"foo\", \"bar\")".propertyList() as! [String])
}
NSStringAPIs.test("propertyListFromStringsFileFormat()") {
expectEqual(["foo": "bar", "baz": "baz"],
"/* comment */\n\"foo\" = \"bar\";\n\"baz\";"
.propertyListFromStringsFileFormat() as Dictionary<String, String>)
}
NSStringAPIs.test("rangeOfCharacterFrom(_:options:range:)") {
do {
let charset = CharacterSet(charactersIn: "абв")
do {
let s = "Глокая куздра"
let r = s.rangeOfCharacter(from: charset)!
expectEqual(s.index(s.startIndex, offsetBy: 4), r.lowerBound)
expectEqual(s.index(s.startIndex, offsetBy: 5), r.upperBound)
}
do {
expectNil("клмн".rangeOfCharacter(from: charset))
}
do {
let s = "абвклмнабвклмн"
let r = s.rangeOfCharacter(from: charset,
options: .backwards)!
expectEqual(s.index(s.startIndex, offsetBy: 9), r.lowerBound)
expectEqual(s.index(s.startIndex, offsetBy: 10), r.upperBound)
}
do {
let s = "абвклмнабв"
let r = s.rangeOfCharacter(from: charset,
range: s.index(s.startIndex, offsetBy: 3)..<s.endIndex)!
expectEqual(s.index(s.startIndex, offsetBy: 7), r.lowerBound)
expectEqual(s.index(s.startIndex, offsetBy: 8), r.upperBound)
}
}
do {
let charset = CharacterSet(charactersIn: "\u{305f}\u{3099}")
expectNil("\u{3060}".rangeOfCharacter(from: charset))
}
do {
let charset = CharacterSet(charactersIn: "\u{3060}")
expectNil("\u{305f}\u{3099}".rangeOfCharacter(from: charset))
}
do {
let charset = CharacterSet(charactersIn: "\u{1F600}")
do {
let s = "abc\u{1F600}"
expectEqual("\u{1F600}",
s[s.rangeOfCharacter(from: charset)!])
}
do {
expectNil("abc\u{1F601}".rangeOfCharacter(from: charset))
}
}
}
NSStringAPIs.test("rangeOfComposedCharacterSequence(at:)") {
let s = "\u{1F601}abc \u{305f}\u{3099} def"
expectEqual("\u{1F601}", s[s.rangeOfComposedCharacterSequence(
at: s.startIndex)])
expectEqual("a", s[s.rangeOfComposedCharacterSequence(
at: s.index(s.startIndex, offsetBy: 1))])
expectEqual("\u{305f}\u{3099}", s[s.rangeOfComposedCharacterSequence(
at: s.index(s.startIndex, offsetBy: 5))])
expectEqual(" ", s[s.rangeOfComposedCharacterSequence(
at: s.index(s.startIndex, offsetBy: 6))])
}
NSStringAPIs.test("rangeOfComposedCharacterSequences(for:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual("\u{1F601}a", s[s.rangeOfComposedCharacterSequences(
for: s.startIndex..<s.index(s.startIndex, offsetBy: 2))])
expectEqual("せ\u{3099}そ\u{3099}", s[s.rangeOfComposedCharacterSequences(
for: s.index(s.startIndex, offsetBy: 8)..<s.index(s.startIndex, offsetBy: 10))])
}
func toIntRange<
S : StringProtocol
>(
_ string: S, _ maybeRange: Range<String.Index>?
) -> Range<Int>? where S.Index == String.Index {
guard let range = maybeRange else { return nil }
return
string.distance(from: string.startIndex, to: range.lowerBound) ..<
string.distance(from: string.startIndex, to: range.upperBound)
}
NSStringAPIs.test("range(of:options:range:locale:)") {
do {
let s = ""
expectNil(s.range(of: ""))
expectNil(s.range(of: "abc"))
}
do {
let s = "abc"
expectNil(s.range(of: ""))
expectNil(s.range(of: "def"))
expectEqual(0..<3, toIntRange(s, s.range(of: "abc")))
}
do {
let s = "さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual(2..<3, toIntRange(s, s.range(of: "す\u{3099}")))
expectEqual(2..<3, toIntRange(s, s.range(of: "\u{305a}")))
expectNil(s.range(of: "\u{3099}す"))
expectNil(s.range(of: "す"))
// Note: here `rangeOf` API produces indexes that don't point between
// grapheme cluster boundaries -- these cannot be created with public
// String interface.
//
// FIXME: why does this search succeed and the above queries fail? There is
// no apparent pattern.
expectEqual("\u{3099}", s[s.range(of: "\u{3099}")!])
}
do {
let s = "а\u{0301}б\u{0301}в\u{0301}г\u{0301}"
expectEqual(0..<1, toIntRange(s, s.range(of: "а\u{0301}")))
expectEqual(1..<2, toIntRange(s, s.range(of: "б\u{0301}")))
expectNil(s.range(of: "б"))
expectNil(s.range(of: "\u{0301}б"))
// FIXME: Again, indexes that don't correspond to grapheme
// cluster boundaries.
expectEqual("\u{0301}", s[s.range(of: "\u{0301}")!])
}
}
NSStringAPIs.test("contains(_:)") {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectFalse("".contains(""))
expectFalse("".contains("a"))
expectFalse("a".contains(""))
expectFalse("a".contains("b"))
expectTrue("a".contains("a"))
expectFalse("a".contains("A"))
expectFalse("A".contains("a"))
expectFalse("a".contains("a\u{0301}"))
expectTrue("a\u{0301}".contains("a\u{0301}"))
expectFalse("a\u{0301}".contains("a"))
expectTrue("a\u{0301}".contains("\u{0301}"))
expectFalse("a".contains("\u{0301}"))
expectFalse("i".contains("I"))
expectFalse("I".contains("i"))
expectFalse("\u{0130}".contains("i"))
expectFalse("i".contains("\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectFalse("\u{0130}".contains("ı"))
}
}
NSStringAPIs.test("localizedCaseInsensitiveContains(_:)") {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectFalse("".localizedCaseInsensitiveContains(""))
expectFalse("".localizedCaseInsensitiveContains("a"))
expectFalse("a".localizedCaseInsensitiveContains(""))
expectFalse("a".localizedCaseInsensitiveContains("b"))
expectTrue("a".localizedCaseInsensitiveContains("a"))
expectTrue("a".localizedCaseInsensitiveContains("A"))
expectTrue("A".localizedCaseInsensitiveContains("a"))
expectFalse("a".localizedCaseInsensitiveContains("a\u{0301}"))
expectTrue("a\u{0301}".localizedCaseInsensitiveContains("a\u{0301}"))
expectFalse("a\u{0301}".localizedCaseInsensitiveContains("a"))
expectTrue("a\u{0301}".localizedCaseInsensitiveContains("\u{0301}"))
expectFalse("a".localizedCaseInsensitiveContains("\u{0301}"))
expectTrue("i".localizedCaseInsensitiveContains("I"))
expectTrue("I".localizedCaseInsensitiveContains("i"))
expectFalse("\u{0130}".localizedCaseInsensitiveContains("i"))
expectFalse("i".localizedCaseInsensitiveContains("\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectFalse("\u{0130}".localizedCaseInsensitiveContains("ı"))
}
}
NSStringAPIs.test("localizedStandardContains(_:)") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectFalse("".localizedStandardContains(""))
expectFalse("".localizedStandardContains("a"))
expectFalse("a".localizedStandardContains(""))
expectFalse("a".localizedStandardContains("b"))
expectTrue("a".localizedStandardContains("a"))
expectTrue("a".localizedStandardContains("A"))
expectTrue("A".localizedStandardContains("a"))
expectTrue("a".localizedStandardContains("a\u{0301}"))
expectTrue("a\u{0301}".localizedStandardContains("a\u{0301}"))
expectTrue("a\u{0301}".localizedStandardContains("a"))
expectTrue("a\u{0301}".localizedStandardContains("\u{0301}"))
expectFalse("a".localizedStandardContains("\u{0301}"))
expectTrue("i".localizedStandardContains("I"))
expectTrue("I".localizedStandardContains("i"))
expectTrue("\u{0130}".localizedStandardContains("i"))
expectTrue("i".localizedStandardContains("\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectTrue("\u{0130}".localizedStandardContains("ı"))
}
}
}
NSStringAPIs.test("localizedStandardRange(of:)") {
if #available(OSX 10.11, iOS 9.0, *) {
func rangeOf(_ string: String, _ substring: String) -> Range<Int>? {
return toIntRange(
string, string.localizedStandardRange(of: substring))
}
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectNil(rangeOf("", ""))
expectNil(rangeOf("", "a"))
expectNil(rangeOf("a", ""))
expectNil(rangeOf("a", "b"))
expectEqual(0..<1, rangeOf("a", "a"))
expectEqual(0..<1, rangeOf("a", "A"))
expectEqual(0..<1, rangeOf("A", "a"))
expectEqual(0..<1, rangeOf("a", "a\u{0301}"))
expectEqual(0..<1, rangeOf("a\u{0301}", "a\u{0301}"))
expectEqual(0..<1, rangeOf("a\u{0301}", "a"))
do {
// FIXME: Indices that don't correspond to grapheme cluster boundaries.
let s = "a\u{0301}"
expectEqual(
"\u{0301}", s[s.localizedStandardRange(of: "\u{0301}")!])
}
expectNil(rangeOf("a", "\u{0301}"))
expectEqual(0..<1, rangeOf("i", "I"))
expectEqual(0..<1, rangeOf("I", "i"))
expectEqual(0..<1, rangeOf("\u{0130}", "i"))
expectEqual(0..<1, rangeOf("i", "\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectEqual(0..<1, rangeOf("\u{0130}", "ı"))
}
}
}
NSStringAPIs.test("smallestEncoding") {
let availableEncodings: [String.Encoding] = String.availableStringEncodings
expectTrue(availableEncodings.contains("abc".smallestEncoding))
}
func getHomeDir() -> String {
#if os(macOS)
return String(cString: getpwuid(getuid()).pointee.pw_dir)
#elseif canImport(Darwin)
// getpwuid() returns null in sandboxed apps under iOS simulator.
return NSHomeDirectory()
#else
preconditionFailed("implement")
#endif
}
NSStringAPIs.test("addingPercentEncoding(withAllowedCharacters:)") {
expectEqual(
"abcd1234",
"abcd1234".addingPercentEncoding(withAllowedCharacters: .alphanumerics))
expectEqual(
"abcd%20%D0%B0%D0%B1%D0%B2%D0%B3",
"abcd абвг".addingPercentEncoding(withAllowedCharacters: .alphanumerics))
}
NSStringAPIs.test("appendingFormat(_:_:...)") {
expectEqual("", "".appendingFormat(""))
expectEqual("a", "a".appendingFormat(""))
expectEqual(
"abc абв \u{0001F60A}",
"abc абв \u{0001F60A}".appendingFormat(""))
let formatArg: NSString = "привет мир \u{0001F60A}"
expectEqual(
"abc абв \u{0001F60A}def привет мир \u{0001F60A} 42",
"abc абв \u{0001F60A}"
.appendingFormat("def %@ %ld", formatArg, 42))
}
NSStringAPIs.test("appending(_:)") {
expectEqual("", "".appending(""))
expectEqual("a", "a".appending(""))
expectEqual("a", "".appending("a"))
expectEqual("さ\u{3099}", "さ".appending("\u{3099}"))
}
NSStringAPIs.test("folding(options:locale:)") {
func fwo(
_ s: String, _ options: String.CompareOptions
) -> (Locale?) -> String {
return { loc in s.folding(options: options, locale: loc) }
}
expectLocalizedEquality("abcd", fwo("abCD", .caseInsensitive), "en")
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectLocalizedEquality(
"\u{0069}\u{0307}", fwo("\u{0130}", .caseInsensitive), "en")
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
expectLocalizedEquality(
"\u{0069}", fwo("\u{0130}", .caseInsensitive), "tr")
expectLocalizedEquality(
"example123", fwo("example123", .widthInsensitive), "en")
}
NSStringAPIs.test("padding(toLength:withPad:startingAtIndex:)") {
expectEqual(
"abc абв \u{0001F60A}",
"abc абв \u{0001F60A}".padding(
toLength: 10, withPad: "XYZ", startingAt: 0))
expectEqual(
"abc абв \u{0001F60A}XYZXY",
"abc абв \u{0001F60A}".padding(
toLength: 15, withPad: "XYZ", startingAt: 0))
expectEqual(
"abc абв \u{0001F60A}YZXYZ",
"abc абв \u{0001F60A}".padding(
toLength: 15, withPad: "XYZ", startingAt: 1))
}
NSStringAPIs.test("replacingCharacters(in:with:)") {
do {
let empty = ""
expectEqual("", empty.replacingCharacters(
in: empty.startIndex..<empty.startIndex, with: ""))
}
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual(s, s.replacingCharacters(
in: s.startIndex..<s.startIndex, with: ""))
expectEqual(s, s.replacingCharacters(
in: s.endIndex..<s.endIndex, with: ""))
expectEqual("zzz" + s, s.replacingCharacters(
in: s.startIndex..<s.startIndex, with: "zzz"))
expectEqual(s + "zzz", s.replacingCharacters(
in: s.endIndex..<s.endIndex, with: "zzz"))
expectEqual(
"す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.startIndex..<s.index(s.startIndex, offsetBy: 7), with: ""))
expectEqual(
"zzzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.startIndex..<s.index(s.startIndex, offsetBy: 7), with: "zzz"))
expectEqual(
"\u{1F602}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.startIndex..<s.index(s.startIndex, offsetBy: 7), with: "\u{1F602}"))
expectEqual("\u{1F601}", s.replacingCharacters(
in: s.index(after: s.startIndex)..<s.endIndex, with: ""))
expectEqual("\u{1F601}zzz", s.replacingCharacters(
in: s.index(after: s.startIndex)..<s.endIndex, with: "zzz"))
expectEqual("\u{1F601}\u{1F602}", s.replacingCharacters(
in: s.index(after: s.startIndex)..<s.endIndex, with: "\u{1F602}"))
expectEqual(
"\u{1F601}aす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.index(s.startIndex, offsetBy: 2)..<s.index(s.startIndex, offsetBy: 7), with: ""))
expectEqual(
"\u{1F601}azzzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.index(s.startIndex, offsetBy: 2)..<s.index(s.startIndex, offsetBy: 7), with: "zzz"))
expectEqual(
"\u{1F601}a\u{1F602}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.index(s.startIndex, offsetBy: 2)..<s.index(s.startIndex, offsetBy: 7),
with: "\u{1F602}"))
}
NSStringAPIs.test("replacingOccurrences(of:with:options:range:)") {
do {
let empty = ""
expectEqual("", empty.replacingOccurrences(
of: "", with: ""))
expectEqual("", empty.replacingOccurrences(
of: "", with: "xyz"))
expectEqual("", empty.replacingOccurrences(
of: "abc", with: "xyz"))
}
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual(s, s.replacingOccurrences(of: "", with: "xyz"))
expectEqual(s, s.replacingOccurrences(of: "xyz", with: ""))
expectEqual("", s.replacingOccurrences(of: s, with: ""))
expectEqual(
"\u{1F601}xyzbc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(of: "a", with: "xyz"))
expectEqual(
"\u{1F602}\u{1F603}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}"))
expectEqual(
"\u{1F601}abc さ\u{3099}xyzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "し\u{3099}", with: "xyz"))
expectEqual(
"\u{1F601}abc さ\u{3099}xyzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "し\u{3099}", with: "xyz"))
expectEqual(
"\u{1F601}abc さ\u{3099}xyzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{3058}", with: "xyz"))
//
// Use non-default 'options:'
//
expectEqual(
"\u{1F602}\u{1F603}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}",
options: String.CompareOptions.literal))
expectEqual(s, s.replacingOccurrences(
of: "\u{3058}", with: "xyz",
options: String.CompareOptions.literal))
//
// Use non-default 'range:'
//
expectEqual(
"\u{1F602}\u{1F603}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}",
options: String.CompareOptions.literal,
range: s.startIndex..<s.index(s.startIndex, offsetBy: 1)))
expectEqual(s, s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}",
options: String.CompareOptions.literal,
range: s.index(s.startIndex, offsetBy: 1)..<s.index(s.startIndex, offsetBy: 3)))
}
NSStringAPIs.test("removingPercentEncoding") {
expectEqual(
"abcd абвг",
"abcd абвг".removingPercentEncoding)
expectEqual(
"abcd абвг\u{0000}\u{0001}",
"abcd абвг%00%01".removingPercentEncoding)
expectEqual(
"abcd абвг",
"%61%62%63%64%20%D0%B0%D0%B1%D0%B2%D0%B3".removingPercentEncoding)
expectEqual(
"abcd абвг",
"ab%63d %D0%B0%D0%B1%D0%B2%D0%B3".removingPercentEncoding)
expectNil("%ED%B0".removingPercentEncoding)
expectNil("%zz".removingPercentEncoding)
expectNil("abcd%FF".removingPercentEncoding)
expectNil("%".removingPercentEncoding)
}
NSStringAPIs.test("removingPercentEncoding/OSX 10.9")
.xfail(.osxMinor(10, 9, reason: "looks like a bug in Foundation in OS X 10.9"))
.xfail(.iOSMajor(7, reason: "same bug in Foundation in iOS 7.*"))
.skip(.iOSSimulatorAny("same bug in Foundation in iOS Simulator 7.*"))
.code {
expectEqual("", "".removingPercentEncoding)
}
NSStringAPIs.test("trimmingCharacters(in:)") {
expectEqual("", "".trimmingCharacters(
in: CharacterSet.decimalDigits))
expectEqual("abc", "abc".trimmingCharacters(
in: CharacterSet.decimalDigits))
expectEqual("", "123".trimmingCharacters(
in: CharacterSet.decimalDigits))
expectEqual("abc", "123abc789".trimmingCharacters(
in: CharacterSet.decimalDigits))
// Performs Unicode scalar comparison.
expectEqual(
"し\u{3099}abc",
"し\u{3099}abc".trimmingCharacters(
in: CharacterSet(charactersIn: "\u{3058}")))
}
NSStringAPIs.test("NSString.stringsByAppendingPaths(_:)") {
expectEqual([] as [NSString], ("" as NSString).strings(byAppendingPaths: []) as [NSString])
expectEqual(
[ "/tmp/foo", "/tmp/bar" ] as [NSString],
("/tmp" as NSString).strings(byAppendingPaths: [ "foo", "bar" ]) as [NSString])
}
NSStringAPIs.test("substring(from:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual(s, s.substring(from: s.startIndex))
expectEqual("せ\u{3099}そ\u{3099}",
s.substring(from: s.index(s.startIndex, offsetBy: 8)))
expectEqual("", s.substring(from: s.index(s.startIndex, offsetBy: 10)))
}
NSStringAPIs.test("substring(to:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual("", s.substring(to: s.startIndex))
expectEqual("\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}",
s.substring(to: s.index(s.startIndex, offsetBy: 8)))
expectEqual(s, s.substring(to: s.index(s.startIndex, offsetBy: 10)))
}
NSStringAPIs.test("substring(with:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual("", s.substring(with: s.startIndex..<s.startIndex))
expectEqual(
"",
s.substring(with: s.index(s.startIndex, offsetBy: 1)..<s.index(s.startIndex, offsetBy: 1)))
expectEqual("", s.substring(with: s.endIndex..<s.endIndex))
expectEqual(s, s.substring(with: s.startIndex..<s.endIndex))
expectEqual(
"さ\u{3099}し\u{3099}す\u{3099}",
s.substring(with: s.index(s.startIndex, offsetBy: 5)..<s.index(s.startIndex, offsetBy: 8)))
}
NSStringAPIs.test("localizedUppercase") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") {
expectEqual("ABCD", "abCD".localizedUppercase)
}
withOverriddenLocaleCurrentLocale("en") {
expectEqual("АБВГ", "абВГ".localizedUppercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("АБВГ", "абВГ".localizedUppercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("たちつてと", "たちつてと".localizedUppercase)
}
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
withOverriddenLocaleCurrentLocale("en") {
expectEqual("\u{0049}", "\u{0069}".localizedUppercase)
}
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0130}", "\u{0069}".localizedUppercase)
}
// U+00DF LATIN SMALL LETTER SHARP S
// to upper case:
// U+0053 LATIN CAPITAL LETTER S
// U+0073 LATIN SMALL LETTER S
// But because the whole string is converted to uppercase, we just get two
// U+0053.
withOverriddenLocaleCurrentLocale("en") {
expectEqual("\u{0053}\u{0053}", "\u{00df}".localizedUppercase)
}
// U+FB01 LATIN SMALL LIGATURE FI
// to upper case:
// U+0046 LATIN CAPITAL LETTER F
// U+0069 LATIN SMALL LETTER I
// But because the whole string is converted to uppercase, we get U+0049
// LATIN CAPITAL LETTER I.
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("\u{0046}\u{0049}", "\u{fb01}".localizedUppercase)
}
}
}
NSStringAPIs.test("uppercased(with:)") {
expectLocalizedEquality("ABCD", { loc in "abCD".uppercased(with: loc) }, "en")
expectLocalizedEquality("АБВГ", { loc in "абВГ".uppercased(with: loc) }, "en")
expectLocalizedEquality("АБВГ", { loc in "абВГ".uppercased(with: loc) }, "ru")
expectLocalizedEquality("たちつてと", { loc in "たちつてと".uppercased(with: loc) }, "ru")
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
expectLocalizedEquality("\u{0049}", { loc in "\u{0069}".uppercased(with: loc) }, "en")
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
expectLocalizedEquality("\u{0130}", { loc in "\u{0069}".uppercased(with: loc) }, "tr")
// U+00DF LATIN SMALL LETTER SHARP S
// to upper case:
// U+0053 LATIN CAPITAL LETTER S
// U+0073 LATIN SMALL LETTER S
// But because the whole string is converted to uppercase, we just get two
// U+0053.
expectLocalizedEquality("\u{0053}\u{0053}", { loc in "\u{00df}".uppercased(with: loc) }, "en")
// U+FB01 LATIN SMALL LIGATURE FI
// to upper case:
// U+0046 LATIN CAPITAL LETTER F
// U+0069 LATIN SMALL LETTER I
// But because the whole string is converted to uppercase, we get U+0049
// LATIN CAPITAL LETTER I.
expectLocalizedEquality("\u{0046}\u{0049}", { loc in "\u{fb01}".uppercased(with: loc) }, "ru")
}
NSStringAPIs.test("write(toFile:atomically:encoding:error:)") {
let (_, nonExistentPath) = createNSStringTemporaryFile()
do {
let s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
try s.write(
toFile: nonExistentPath, atomically: false, encoding: .ascii)
let content = try String(
contentsOfFile: nonExistentPath, encoding: .ascii)
expectEqual(s, content)
} catch {
expectUnreachableCatch(error)
}
}
NSStringAPIs.test("write(to:atomically:encoding:error:)") {
let (_, nonExistentPath) = createNSStringTemporaryFile()
let nonExistentURL = URL(string: "file://" + nonExistentPath)!
do {
let s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
try s.write(
to: nonExistentURL, atomically: false, encoding: .ascii)
let content = try String(
contentsOfFile: nonExistentPath, encoding: .ascii)
expectEqual(s, content)
} catch {
expectUnreachableCatch(error)
}
}
NSStringAPIs.test("applyingTransform(_:reverse:)") {
if #available(OSX 10.11, iOS 9.0, *) {
do {
let source = "tre\u{300}s k\u{fc}hl"
expectEqual(
"tres kuhl",
source.applyingTransform(.stripDiacritics, reverse: false))
}
do {
let source = "hiragana"
expectEqual(
"ひらがな",
source.applyingTransform(.latinToHiragana, reverse: false))
}
do {
let source = "ひらがな"
expectEqual(
"hiragana",
source.applyingTransform(.latinToHiragana, reverse: true))
}
}
}
NSStringAPIs.test("SameTypeComparisons") {
// U+0323 COMBINING DOT BELOW
// U+0307 COMBINING DOT ABOVE
// U+1E63 LATIN SMALL LETTER S WITH DOT BELOW
let xs = "\u{1e69}"
expectTrue(xs == "s\u{323}\u{307}")
expectFalse(xs != "s\u{323}\u{307}")
expectTrue("s\u{323}\u{307}" == xs)
expectFalse("s\u{323}\u{307}" != xs)
expectTrue("\u{1e69}" == "s\u{323}\u{307}")
expectFalse("\u{1e69}" != "s\u{323}\u{307}")
expectTrue(xs == xs)
expectFalse(xs != xs)
}
NSStringAPIs.test("MixedTypeComparisons") {
// U+0323 COMBINING DOT BELOW
// U+0307 COMBINING DOT ABOVE
// U+1E63 LATIN SMALL LETTER S WITH DOT BELOW
// NSString does not decompose characters, so the two strings will be (==) in
// swift but not in Foundation.
let xs = "\u{1e69}"
let ys: NSString = "s\u{323}\u{307}"
expectFalse(ys == "\u{1e69}")
expectTrue(ys != "\u{1e69}")
expectFalse("\u{1e69}" == ys)
expectTrue("\u{1e69}" != ys)
expectFalse(xs as NSString == ys)
expectTrue(xs as NSString != ys)
expectTrue(ys == ys)
expectFalse(ys != ys)
}
NSStringAPIs.test("CompareStringsWithUnpairedSurrogates")
.xfail(
.custom({ true },
reason: "<rdar://problem/18029104> Strings referring to underlying " +
"storage with unpaired surrogates compare unequal"))
.code {
let donor = "abcdef"
let acceptor = "\u{1f601}\u{1f602}\u{1f603}"
expectEqual("\u{fffd}\u{1f602}\u{fffd}",
acceptor[donor.index(donor.startIndex, offsetBy: 1)..<donor.index(donor.startIndex, offsetBy: 5)])
}
NSStringAPIs.test("copy construction") {
let expected = "abcd"
let x = NSString(string: expected as NSString)
expectEqual(expected, x as String)
let y = NSMutableString(string: expected as NSString)
expectEqual(expected, y as String)
}
runAllTests()
| apache-2.0 |
markedwardmurray/Starlight | Starlight/Starlight/Controllers/LeftMenuTableViewController.swift | 1 | 1744 | //
// LeftMenuTableViewController.swift
// Starlight
//
// Created by Mark Murray on 12/2/16.
// Copyright © 2016 Mark Murray. All rights reserved.
//
import UIKit
class LeftMenuTableViewController: UITableViewController {
var mainRevealController: MainRevealViewController {
return self.revealViewController() as! MainRevealViewController
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let row: Int = self.mainRevealController.revealIndex.rawValue
let indexPath = IndexPath(row: row, section: 0)
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .top)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let selectionColor = UIView() as UIView
selectionColor.layer.borderWidth = 1
selectionColor.layer.borderColor = UIColor.init(hex: "0000ff").cgColor
selectionColor.backgroundColor = UIColor.init(hex: "0000ff")
cell.selectedBackgroundView = selectionColor
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
self.mainRevealController.pushUpcomingBillsTVC()
case 1:
self.mainRevealController.pushLegislatorsTVC()
case 2:
self.mainRevealController.pushAboutTVC()
default:
break
}
}
}
| mit |
apple/swift-corelibs-foundation | Sources/Foundation/Port.swift | 1 | 45670 | // 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
//
@_implementationOnly import CoreFoundation
// MARK: Port and related types
public typealias SocketNativeHandle = Int32
extension Port {
public static let didBecomeInvalidNotification = NSNotification.Name(rawValue: "NSPortDidBecomeInvalidNotification")
}
open class Port : NSObject, NSCopying {
@available(*, deprecated, message: "On Darwin, you can invoke Port() directly to produce a MessagePort. Since MessagePort's functionality is not available in swift-corelibs-foundation, you should not invoke this initializer directly. Subclasses of Port can delegate to this initializer safely.")
public override init() {
if type(of: self) == Port.self {
NSRequiresConcreteImplementation()
}
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
open func invalidate() {
NSRequiresConcreteImplementation()
}
open var isValid: Bool {
NSRequiresConcreteImplementation()
}
open func setDelegate(_ anObject: PortDelegate?) {
NSRequiresConcreteImplementation()
}
open func delegate() -> PortDelegate? {
NSRequiresConcreteImplementation()
}
// These two methods should be implemented by subclasses
// to setup monitoring of the port when added to a run loop,
// and stop monitoring if needed when removed;
// These methods should not be called directly!
open func schedule(in runLoop: RunLoop, forMode mode: RunLoop.Mode) {
NSRequiresConcreteImplementation()
}
open func remove(from runLoop: RunLoop, forMode mode: RunLoop.Mode) {
NSRequiresConcreteImplementation()
}
open var reservedSpaceLength: Int {
return 0
}
open func send(before limitDate: Date, components: NSMutableArray?, from receivePort: Port?, reserved headerSpaceReserved: Int) -> Bool {
NSRequiresConcreteImplementation()
}
open func send(before limitDate: Date, msgid msgID: Int, components: NSMutableArray?, from receivePort: Port?, reserved headerSpaceReserved: Int) -> Bool {
return send(before: limitDate, components: components, from: receivePort, reserved: headerSpaceReserved)
}
}
@available(*, unavailable, message: "MessagePort is not available in swift-corelibs-foundation.")
open class MessagePort: Port {}
@available(*, unavailable, message: "NSMachPort is not available in swift-corelibs-foundation.")
open class NSMachPort: Port {}
extension PortDelegate {
func handle(_ message: PortMessage) { }
}
public protocol PortDelegate: AnyObject {
func handle(_ message: PortMessage)
}
#if canImport(Glibc) && !os(Android) && !os(OpenBSD)
import Glibc
fileprivate let SOCK_STREAM = Int32(Glibc.SOCK_STREAM.rawValue)
fileprivate let SOCK_DGRAM = Int32(Glibc.SOCK_DGRAM.rawValue)
fileprivate let IPPROTO_TCP = Int32(Glibc.IPPROTO_TCP)
#endif
#if canImport(Glibc) && os(Android) || os(OpenBSD)
import Glibc
fileprivate let SOCK_STREAM = Int32(Glibc.SOCK_STREAM)
fileprivate let SOCK_DGRAM = Int32(Glibc.SOCK_DGRAM)
fileprivate let IPPROTO_TCP = Int32(Glibc.IPPROTO_TCP)
fileprivate let INADDR_ANY: in_addr_t = 0
#if os(OpenBSD)
fileprivate let INADDR_LOOPBACK = 0x7f000001
#endif
#endif
#if canImport(WinSDK)
import WinSDK
/*
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-sockaddr_in
typedef struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
} SOCKADDR_IN, *PSOCKADDR_IN, *LPSOCKADDR_IN;
*/
fileprivate typealias sa_family_t = ADDRESS_FAMILY
fileprivate typealias in_port_t = USHORT
fileprivate typealias in_addr_t = UInt32
fileprivate let IPPROTO_TCP = Int32(WinSDK.IPPROTO_TCP.rawValue)
#endif
// MARK: Darwin representation of socket addresses
/*
===== YOU ARE ABOUT TO ENTER THE SADNESS ZONE =====
SocketPort transmits ports by sending _Darwin_ sockaddr values serialized over the wire. (Yeah.)
This means that whatever the platform, we need to be able to send Darwin sockaddrs and figure them out on the other side of the wire.
Now, the vast majority of the intreresting ports that may be sent is AF_INET and AF_INET6 — other sockets aren't uncommon, but they are generally local to their host (eg. AF_UNIX). So, we make the following tactical choice:
- swift-corelibs-foundation clients across all platforms can interoperate between themselves and with Darwin as long as all the ports that are sent through SocketPort are AF_INET or AF_INET6;
- otherwise, it is the implementor and deployer's responsibility to make sure all the clients are on the same platform. For sockets that do not leave the machine, like AF_UNIX, this is trivial.
This allows us to special-case sockaddr_in and sockaddr_in6; when we transmit them, we will transmit them in a way that's binary-compatible with Darwin's version of those structure, and then we translate them into whatever version your platform uses, with the one exception that we assume that in_addr is always representable as 4 contiguous bytes, and similarly in6_addr as 16 contiguous bytes.
Addresses are internally represented as LocalAddress enum cases; we use DarwinAddress as a type to denote a block of bytes that we type as being a sockaddr produced by Darwin or a Darwin-mimicking source; and the extensions on sockaddr_in and sockaddr_in6 paper over some platform differences and provide translations back and forth into DarwinAddresses for their specific types.
Note that all address parameters and properties that are public are the data representation of a sockaddr generated starting from the current platform's sockaddrs, not a DarwinAddress. No code that's a client of SocketPort should be able to see the Darwin version of the data we generate internally.
*/
fileprivate let darwinAfInet: UInt8 = 2
fileprivate let darwinAfInet6: UInt8 = 30
fileprivate let darwinSockaddrInSize: UInt8 = 16
fileprivate let darwinSockaddrIn6Size: UInt8 = 28
fileprivate typealias DarwinIn6Addr =
(UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) // 16 contiguous bytes
fileprivate let darwinIn6AddrSize = 16
fileprivate extension sockaddr_in {
// Not all platforms have a sin_len field. This is like init(), but also sets that field if it exists.
init(settingLength: ()) {
self.init()
#if canImport(Darwin) || os(FreeBSD)
self.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
#endif
}
init?(_ address: DarwinAddress) {
let data = address.data
guard data.count == darwinSockaddrInSize,
data[offset: 0] == darwinSockaddrInSize,
data[offset: 1] == darwinAfInet else { return nil }
var port: UInt16 = 0
var inAddr: UInt32 = 0
data.withUnsafeBytes { (buffer) -> Void in
withUnsafeMutableBytes(of: &port) {
$0.copyMemory(from: UnsafeRawBufferPointer(rebasing: buffer[2..<4]))
}
withUnsafeMutableBytes(of: &inAddr) {
$0.copyMemory(from: UnsafeRawBufferPointer(rebasing: buffer[4..<8]))
}
}
self.init(settingLength: ())
self.sin_family = sa_family_t(AF_INET)
self.sin_port = in_port_t(port)
withUnsafeMutableBytes(of: &self.sin_addr) { (buffer) in
withUnsafeBytes(of: inAddr) { buffer.copyMemory(from: $0) }
}
}
var darwinAddress: DarwinAddress {
var data = Data()
withUnsafeBytes(of: darwinSockaddrInSize) { data.append(contentsOf: $0) }
withUnsafeBytes(of: darwinAfInet) { data.append(contentsOf: $0) }
withUnsafeBytes(of: UInt16(sin_port)) { data.append(contentsOf: $0) }
withUnsafeBytes(of: sin_addr) { data.append(contentsOf: $0) }
let padding: (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8) =
(0, 0, 0, 0, 0, 0, 0, 0)
withUnsafeBytes(of: padding) { data.append(contentsOf: $0) }
return DarwinAddress(data)
}
}
fileprivate extension sockaddr_in6 {
init(settingLength: ()) {
self.init()
#if canImport(Darwin) || os(FreeBSD)
self.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
#endif
}
init?(_ address: DarwinAddress) {
let data = address.data
guard data.count == darwinSockaddrIn6Size,
data[offset: 0] == darwinSockaddrIn6Size,
data[offset: 1] == darwinAfInet6 else { return nil }
var port: UInt16 = 0
var flowInfo: UInt32 = 0
var in6Addr: DarwinIn6Addr =
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
var scopeId: UInt32 = 0
data.withUnsafeBytes { (buffer) -> Void in
withUnsafeMutableBytes(of: &port) {
$0.copyMemory(from: UnsafeRawBufferPointer(rebasing: buffer[2..<4]))
}
withUnsafeMutableBytes(of: &flowInfo) {
$0.copyMemory(from: UnsafeRawBufferPointer(rebasing: buffer[4..<8]))
}
withUnsafeMutableBytes(of: &in6Addr) {
$0.copyMemory(from: UnsafeRawBufferPointer(rebasing: buffer[8..<24]))
}
withUnsafeMutableBytes(of: &scopeId) {
$0.copyMemory(from: UnsafeRawBufferPointer(rebasing: buffer[24..<28]))
}
}
self.init(settingLength: ())
self.sin6_family = sa_family_t(AF_INET6)
self.sin6_port = in_port_t(port)
#if os(Windows)
self.sin6_flowinfo = ULONG(flowInfo)
#else
self.sin6_flowinfo = flowInfo
#endif
withUnsafeMutableBytes(of: &self.sin6_addr) { (buffer) in
withUnsafeBytes(of: in6Addr) { buffer.copyMemory(from: $0) }
}
#if !os(Windows)
self.sin6_scope_id = scopeId
#endif
}
var darwinAddress: DarwinAddress {
var data = Data()
withUnsafeBytes(of: darwinSockaddrIn6Size) { data.append(contentsOf: $0) }
withUnsafeBytes(of: darwinAfInet6) { data.append(contentsOf: $0) }
withUnsafeBytes(of: UInt16(sin6_port)) { data.append(contentsOf: $0) }
withUnsafeBytes(of: UInt32(sin6_flowinfo)) { data.append(contentsOf: $0) }
withUnsafeBytes(of: sin6_addr) { data.append(contentsOf: $0) }
#if os(Windows)
withUnsafeBytes(of: UInt32(0)) { data.append(contentsOf: $0) }
#else
withUnsafeBytes(of: UInt32(sin6_scope_id)) { data.append(contentsOf: $0) }
#endif
return DarwinAddress(data)
}
}
enum LocalAddress: Hashable {
case ipv4(sockaddr_in)
case ipv6(sockaddr_in6)
case other(Data)
init(_ data: Data) {
if data.count == MemoryLayout<sockaddr_in>.size {
let sinAddr = data.withUnsafeBytes { $0.baseAddress!.load(as: sockaddr_in.self) }
if sinAddr.sin_family == sa_family_t(AF_INET) {
self = .ipv4(sinAddr)
return
}
}
if data.count == MemoryLayout<sockaddr_in6>.size {
let sinAddr = data.withUnsafeBytes { $0.baseAddress!.load(as: sockaddr_in6.self) }
if sinAddr.sin6_family == sa_family_t(AF_INET6) {
self = .ipv6(sinAddr)
return
}
}
self = .other(data)
}
init(_ darwinAddress: DarwinAddress) {
let data = Data(darwinAddress.data)
if data[offset: 1] == UInt8(AF_INET), let sinAddr = sockaddr_in(darwinAddress) {
self = .ipv4(sinAddr); return
}
if data[offset: 1] == UInt8(AF_INET6), let sinAddr = sockaddr_in6(darwinAddress) {
self = .ipv6(sinAddr); return
}
self = .other(darwinAddress.data)
}
var data: Data {
switch self {
case .ipv4(let sinAddr):
return withUnsafeBytes(of: sinAddr) { Data($0) }
case .ipv6(let sinAddr):
return withUnsafeBytes(of: sinAddr) { Data($0) }
case .other(let data):
return data
}
}
func hash(into hasher: inout Hasher) {
data.hash(into: &hasher)
}
static func ==(_ lhs: LocalAddress, _ rhs: LocalAddress) -> Bool {
return lhs.data == rhs.data
}
}
struct DarwinAddress: Hashable {
var data: Data
init(_ data: Data) {
self.data = data
}
init(_ localAddress: LocalAddress) {
switch localAddress {
case .ipv4(let sinAddr):
self = sinAddr.darwinAddress
case .ipv6(let sinAddr):
self = sinAddr.darwinAddress
case .other(let data):
self.data = data
}
}
}
// MARK: SocketPort
// A subclass of Port which can be used for remote
// message sending on all platforms.
fileprivate func __NSFireSocketAccept(_ socket: CFSocket?, _ type: CFSocketCallBackType, _ address: CFData?, _ data: UnsafeRawPointer?, _ info: UnsafeMutableRawPointer?) {
guard let nonoptionalInfo = info else {
return
}
let me = Unmanaged<SocketPort>.fromOpaque(nonoptionalInfo).takeUnretainedValue()
me.socketDidAccept(socket, type, address, data)
}
fileprivate func __NSFireSocketData(_ socket: CFSocket?, _ type: CFSocketCallBackType, _ address: CFData?, _ data: UnsafeRawPointer?, _ info: UnsafeMutableRawPointer?) {
guard let nonoptionalInfo = info else {
return
}
let me = Unmanaged<SocketPort>.fromOpaque(nonoptionalInfo).takeUnretainedValue()
me.socketDidReceiveData(socket, type, address, data)
}
fileprivate func __NSFireSocketDatagram(_ socket: CFSocket?, _ type: CFSocketCallBackType, _ address: CFData?, _ data: UnsafeRawPointer?, _ info: UnsafeMutableRawPointer?) {
guard let nonoptionalInfo = info else {
return
}
let me = Unmanaged<SocketPort>.fromOpaque(nonoptionalInfo).takeUnretainedValue()
me.socketDidReceiveDatagram(socket, type, address, data)
}
open class SocketPort : Port {
struct SocketKind: Hashable {
var protocolFamily: Int32
var socketType: Int32
var `protocol`: Int32
}
struct Signature: Hashable {
var address: LocalAddress
var protocolFamily: Int32
var socketType: Int32
var `protocol`: Int32
var socketKind: SocketKind {
get {
return SocketKind(protocolFamily: protocolFamily, socketType: socketType, protocol: `protocol`)
}
set {
self.protocolFamily = newValue.protocolFamily
self.socketType = newValue.socketType
self.protocol = newValue.protocol
}
}
var darwinCompatibleDataRepresentation: Data? {
var data = Data()
let address = DarwinAddress(self.address).data
guard let protocolFamilyByte = UInt8(exactly: protocolFamily),
let socketTypeByte = UInt8(exactly: socketType),
let protocolByte = UInt8(exactly: `protocol`),
let addressCountByte = UInt8(exactly: address.count) else {
return nil
}
// TODO: Fixup namelen in Unix socket name.
data.append(protocolFamilyByte)
data.append(socketTypeByte)
data.append(protocolByte)
data.append(addressCountByte)
data.append(contentsOf: address)
return data
}
init(address: LocalAddress, protocolFamily: Int32, socketType: Int32, protocol: Int32) {
self.address = address
self.protocolFamily = protocolFamily
self.socketType = socketType
self.protocol = `protocol`
}
init?(darwinCompatibleDataRepresentation data: Data) {
guard data.count > 3 else { return nil }
let addressCountByte = data[offset: 3]
guard data.count == addressCountByte + 4 else { return nil }
self.protocolFamily = Int32(data[offset: 0])
self.socketType = Int32(data[offset: 1])
self.protocol = Int32(data[offset: 2])
// data[3] is addressCountByte, handled above.
self.address = LocalAddress(DarwinAddress(data[offset: 4...]))
}
}
class Core {
fileprivate let isUniqued: Bool
fileprivate var signature: Signature!
fileprivate let lock = NSLock()
fileprivate var connectors: [Signature: CFSocket] = [:]
fileprivate var loops: [ObjectIdentifier: (runLoop: CFRunLoop, modes: Set<RunLoop.Mode>)] = [:]
fileprivate var receiver: CFSocket?
fileprivate var data: [ObjectIdentifier: Data] = [:]
init(isUniqued: Bool) { self.isUniqued = isUniqued }
}
private var core: Core!
public convenience override init() {
self.init(tcpPort: 0)!
}
public convenience init?(tcpPort port: UInt16) {
var address = sockaddr_in(settingLength: ())
address.sin_family = sa_family_t(AF_INET)
address.sin_port = in_port_t(port).bigEndian
withUnsafeMutableBytes(of: &address.sin_addr) { (buffer) in
withUnsafeBytes(of: in_addr_t(INADDR_ANY).bigEndian) { buffer.copyMemory(from: $0) }
}
let data = withUnsafeBytes(of: address) { Data($0) }
self.init(protocolFamily: PF_INET, socketType: SOCK_STREAM, protocol: IPPROTO_TCP, address: data)
}
private final func createNonuniquedCore(from socket: CFSocket, protocolFamily family: Int32, socketType type: Int32, protocol: Int32) {
self.core = Core(isUniqued: false)
let address = CFSocketCopyAddress(socket)._swiftObject
core.signature = Signature(address: LocalAddress(address), protocolFamily: family, socketType: type, protocol: `protocol`)
core.receiver = socket
}
public init?(protocolFamily family: Int32, socketType type: Int32, protocol: Int32, address: Data) {
super.init()
var context = CFSocketContext()
context.info = Unmanaged.passUnretained(self).toOpaque()
var s: CFSocket
if type == SOCK_STREAM {
s = CFSocketCreate(nil, family, type, `protocol`, CFOptionFlags(kCFSocketAcceptCallBack), __NSFireSocketAccept, &context)
} else {
s = CFSocketCreate(nil, family, type, `protocol`, CFOptionFlags(kCFSocketDataCallBack), __NSFireSocketDatagram, &context)
}
if CFSocketSetAddress(s, address._cfObject) != CFSocketError(0) {
return nil
}
createNonuniquedCore(from: s, protocolFamily: family, socketType: type, protocol: `protocol`)
}
public init?(protocolFamily family: Int32, socketType type: Int32, protocol: Int32, socket sock: SocketNativeHandle) {
super.init()
var context = CFSocketContext()
context.info = Unmanaged.passUnretained(self).toOpaque()
var s: CFSocket
if type == SOCK_STREAM {
s = CFSocketCreateWithNative(nil, CFSocketNativeHandle(sock), CFOptionFlags(kCFSocketAcceptCallBack), __NSFireSocketAccept, &context)
} else {
s = CFSocketCreateWithNative(nil, CFSocketNativeHandle(sock), CFOptionFlags(kCFSocketDataCallBack), __NSFireSocketDatagram, &context)
}
createNonuniquedCore(from: s, protocolFamily: family, socketType: type, protocol: `protocol`)
}
public convenience init?(remoteWithTCPPort port: UInt16, host hostName: String?) {
let host = Host(name: hostName?.isEmpty == true ? nil : hostName)
var addresses: [String] = hostName == nil ? [] : [hostName!]
addresses.append(contentsOf: host.addresses)
// Prefer IPv4 addresses, as Darwin does:
for address in addresses {
var inAddr = in_addr()
if inet_pton(AF_INET, address, &inAddr) == 1 {
var sinAddr = sockaddr_in(settingLength: ())
sinAddr.sin_family = sa_family_t(AF_INET)
sinAddr.sin_port = port.bigEndian
sinAddr.sin_addr = inAddr
let data = withUnsafeBytes(of: sinAddr) { Data($0) }
self.init(remoteWithProtocolFamily: PF_INET, socketType: SOCK_STREAM, protocol: IPPROTO_TCP, address: data)
return
}
}
for address in addresses {
var in6Addr = in6_addr()
if inet_pton(AF_INET6, address, &in6Addr) == 1 {
var sinAddr = sockaddr_in6(settingLength: ())
sinAddr.sin6_family = sa_family_t(AF_INET6)
sinAddr.sin6_port = port.bigEndian
sinAddr.sin6_addr = in6Addr
let data = withUnsafeBytes(of: sinAddr) { Data($0) }
self.init(remoteWithProtocolFamily: PF_INET, socketType: SOCK_STREAM, protocol: IPPROTO_TCP, address: data)
return
}
}
if hostName != nil {
return nil
}
// Lookup on local host.
var sinAddr = sockaddr_in(settingLength: ())
sinAddr.sin_family = sa_family_t(AF_INET)
sinAddr.sin_port = port.bigEndian
withUnsafeMutableBytes(of: &sinAddr.sin_addr) { (buffer) in
withUnsafeBytes(of: in_addr_t(INADDR_LOOPBACK).bigEndian) { buffer.copyMemory(from: $0) }
}
let data = withUnsafeBytes(of: sinAddr) { Data($0) }
self.init(remoteWithProtocolFamily: PF_INET, socketType: SOCK_STREAM, protocol: IPPROTO_TCP, address: data)
}
private static let remoteSocketCoresLock = NSLock()
private static var remoteSocketCores: [Signature: Core] = [:]
static private func retainedCore(for signature: Signature) -> Core {
return SocketPort.remoteSocketCoresLock.synchronized {
if let core = SocketPort.remoteSocketCores[signature] {
return core
} else {
let core = Core(isUniqued: true)
core.signature = signature
SocketPort.remoteSocketCores[signature] = core
return core
}
}
}
public init(remoteWithProtocolFamily family: Int32, socketType type: Int32, protocol: Int32, address: Data) {
let signature = Signature(address: LocalAddress(address), protocolFamily: family, socketType: type, protocol: `protocol`)
self.core = SocketPort.retainedCore(for: signature)
}
private init(remoteWithSignature signature: Signature) {
self.core = SocketPort.retainedCore(for: signature)
}
deinit {
// On Darwin, .invalidate() is invoked on the _last_ release, immediately before deinit; we cannot do that here.
invalidate()
}
open override func invalidate() {
guard var core = core else { return }
self.core = nil
var signatureToRemove: Signature?
if core.isUniqued {
if isKnownUniquelyReferenced(&core) {
signatureToRemove = core.signature // No need to lock here — this is the only reference to the core.
} else {
return // Do not clean up the contents of this core yet.
}
}
if let receiver = core.receiver, CFSocketIsValid(receiver) {
for connector in core.connectors.values {
CFSocketInvalidate(connector)
}
CFSocketInvalidate(receiver)
// Invalidation notifications are only sent for local (receiver != nil) ports.
NotificationCenter.default.post(name: Port.didBecomeInvalidNotification, object: self)
}
if let signatureToRemove = signatureToRemove {
SocketPort.remoteSocketCoresLock.synchronized {
_ = SocketPort.remoteSocketCores.removeValue(forKey: signatureToRemove)
}
}
}
open override var isValid: Bool {
return core != nil
}
weak var _delegate: PortDelegate?
open override func setDelegate(_ anObject: PortDelegate?) {
_delegate = anObject
}
open override func delegate() -> PortDelegate? {
return _delegate
}
open var protocolFamily: Int32 {
return core.signature.protocolFamily
}
open var socketType: Int32 {
return core.signature.socketType
}
open var `protocol`: Int32 {
return core.signature.protocol
}
open var address: Data {
return core.signature.address.data
}
open var socket: SocketNativeHandle {
return SocketNativeHandle(CFSocketGetNative(core.receiver))
}
open override func schedule(in runLoop: RunLoop, forMode mode: RunLoop.Mode) {
let loop = runLoop.currentCFRunLoop
let loopKey = ObjectIdentifier(loop)
core.lock.synchronized {
guard let receiver = core.receiver, CFSocketIsValid(receiver) else { return }
var modes = core.loops[loopKey]?.modes ?? []
guard !modes.contains(mode) else { return }
modes.insert(mode)
core.loops[loopKey] = (loop, modes)
if let source = CFSocketCreateRunLoopSource(nil, receiver, 600) {
CFRunLoopAddSource(loop, source, mode.rawValue._cfObject)
}
for socket in core.connectors.values {
if let source = CFSocketCreateRunLoopSource(nil, socket, 600) {
CFRunLoopAddSource(loop, source, mode.rawValue._cfObject)
}
}
}
}
open override func remove(from runLoop: RunLoop, forMode mode: RunLoop.Mode) {
let loop = runLoop.currentCFRunLoop
let loopKey = ObjectIdentifier(loop)
core.lock.synchronized {
guard let receiver = core.receiver, CFSocketIsValid(receiver) else { return }
let modes = core.loops[loopKey]?.modes ?? []
guard modes.contains(mode) else { return }
if modes.count == 1 {
core.loops.removeValue(forKey: loopKey)
} else {
core.loops[loopKey]?.modes.remove(mode)
}
if let source = CFSocketCreateRunLoopSource(nil, receiver, 600) {
CFRunLoopRemoveSource(loop, source, mode.rawValue._cfObject)
}
for socket in core.connectors.values {
if let source = CFSocketCreateRunLoopSource(nil, socket, 600) {
CFRunLoopRemoveSource(loop, source, mode.rawValue._cfObject)
}
}
}
}
// On Darwin/ObjC Foundation, invoking initRemote… will return an existing SocketPort from a factory initializer if a port with that signature already exists.
// We cannot do that in Swift; we return instead different objects that share a 'core' (their state), so that invoking methods on either will affect the other. To keep maintain a better illusion, unlike Darwin, we redefine equality so that s1 == s2 for objects that have the same core, even though s1 !== s2 (this we cannot fix).
// This allows e.g. collections where SocketPorts are keys or entries to continue working the same way they do on Darwin when remote socket ports are encountered.
open override var hash: Int {
var hasher = Hasher()
ObjectIdentifier(core).hash(into: &hasher)
return hasher.finalize()
}
open override func isEqual(_ object: Any?) -> Bool {
guard let socketPort = object as? SocketPort else { return false }
return core === socketPort.core
}
// Sending and receiving:
fileprivate final func socketDidAccept(_ socket: CFSocket?, _ type: CFSocketCallBackType, _ address: CFData?, _ data: UnsafeRawPointer?) {
guard let handle = data?.assumingMemoryBound(to: SocketNativeHandle.self),
let address = address else {
return
}
var context = CFSocketContext()
context.info = Unmanaged.passUnretained(self).toOpaque()
guard let child = CFSocketCreateWithNative(nil, CFSocketNativeHandle(handle.pointee), CFOptionFlags(kCFSocketDataCallBack), __NSFireSocketData, &context) else {
return
}
var signature = core.signature!
signature.address = LocalAddress(address._swiftObject)
core.lock.synchronized {
core.connectors[signature] = child
addToLoopsAssumingLockHeld(child)
}
}
private final func addToLoopsAssumingLockHeld(_ socket: CFSocket) {
guard let source = CFSocketCreateRunLoopSource(nil, socket, 600) else {
return
}
for loop in core.loops.values {
for mode in loop.modes {
CFRunLoopAddSource(loop.runLoop, source, mode.rawValue._cfObject)
}
}
}
private static let magicNumber: UInt32 = 0xD0CF50C0
private enum ComponentType: UInt32 {
case data = 1
case port = 2
}
fileprivate final func socketDidReceiveData(_ socket: CFSocket?, _ type: CFSocketCallBackType, _ address: CFData?, _ dataPointer: UnsafeRawPointer?) {
guard let socket = socket,
let dataPointer = dataPointer else { return }
let socketKey = ObjectIdentifier(socket)
let peerAddress = CFSocketCopyPeerAddress(socket)._swiftObject
let lock = core.lock
lock.lock() // We may briefly release the lock during the loop below, and it's unlocked at the end ⬇
let data = Unmanaged<CFData>.fromOpaque(dataPointer).takeUnretainedValue()._swiftObject
if data.count == 0 {
core.data.removeValue(forKey: socketKey)
let keysToRemove = core.connectors.keys.filter { core.connectors[$0] === socket }
for key in keysToRemove {
core.connectors.removeValue(forKey: key)
}
} else {
var storedData: Data
if let currentData = core.data[socketKey] {
storedData = currentData
storedData.append(contentsOf: data)
} else {
storedData = data
}
var keepGoing = true
while keepGoing && storedData.count > 8 {
let preamble = storedData.withUnsafeBytes { $0.load(fromByteOffset: 0, as: UInt32.self) }.bigEndian
let messageLength = storedData.withUnsafeBytes { $0.load(fromByteOffset: 4, as: UInt32.self) }.bigEndian
if preamble == SocketPort.magicNumber && messageLength > 8 {
if storedData.count >= messageLength {
let messageEndIndex = storedData.index(storedData.startIndex, offsetBy: Int(messageLength))
let toStore = storedData[offset: messageEndIndex...]
if toStore.isEmpty {
core.data.removeValue(forKey: socketKey)
} else {
core.data[socketKey] = toStore
}
storedData.removeSubrange(messageEndIndex...)
lock.unlock() // Briefly release the lock ⬆
handleMessage(storedData, from: peerAddress, socket: socket)
lock.lock() // Retake for the remainder ⬇
if let newStoredData = core.data[socketKey] {
storedData = newStoredData
} else {
keepGoing = false
}
} else {
keepGoing = false
}
} else {
// Got message without proper header; delete it.
core.data.removeValue(forKey: socketKey)
keepGoing = false
}
}
}
lock.unlock() // Release lock from above ⬆
}
fileprivate final func socketDidReceiveDatagram(_ socket: CFSocket?, _ type: CFSocketCallBackType, _ address: CFData?, _ data: UnsafeRawPointer?) {
guard let address = address?._swiftObject,
let data = data else {
return
}
let actualData = Unmanaged<CFData>.fromOpaque(data).takeUnretainedValue()._swiftObject
self.handleMessage(actualData, from: address, socket: nil)
}
private enum Structure {
static let offsetOfMagicNumber = 0 // a UInt32
static let offsetOfMessageLength = 4 // a UInt32
static let offsetOfMsgId = 8 // a UInt32
static let offsetOfSignature = 12
static let sizeOfSignatureHeader = 4
static let offsetOfSignatureAddressLength = 15
}
private final func handleMessage(_ message: Data, from address: Data, socket: CFSocket?) {
guard message.count > 24, let delegate = delegate() else { return }
let portMessage = message.withUnsafeBytes { (messageBuffer) -> PortMessage? in
guard SocketPort.magicNumber == messageBuffer.load(fromByteOffset: Structure.offsetOfMagicNumber, as: UInt32.self).bigEndian,
message.count == messageBuffer.load(fromByteOffset: Structure.offsetOfMessageLength, as: UInt32.self).bigEndian else {
return nil
}
let msgId = messageBuffer.load(fromByteOffset: Structure.offsetOfMsgId, as: UInt32.self).bigEndian
let signatureLength = Int(messageBuffer[Structure.offsetOfSignatureAddressLength]) + Structure.sizeOfSignatureHeader // corresponds to the sin_len/sin6_len field inside the signature.
var signatureBytes = Data(UnsafeRawBufferPointer(rebasing: messageBuffer[12 ..< min(12 + signatureLength, message.count - 20)]))
if signatureBytes.count >= 12 && signatureBytes[offset: 5] == AF_INET && address.count >= 8 {
if address[offset: 1] == AF_INET {
signatureBytes.withUnsafeMutableBytes { (mutableSignatureBuffer) in
address.withUnsafeBytes { (address) in
mutableSignatureBuffer.baseAddress?.advanced(by: 8).copyMemory(from: address.baseAddress!.advanced(by: 4), byteCount: 4)
}
}
}
} else if signatureBytes.count >= 32 && signatureBytes[offset: 5] == AF_INET6 && address.count >= 28 {
if address[offset: 1] == AF_INET6 {
signatureBytes.withUnsafeMutableBytes { (mutableSignatureBuffer) in
address.withUnsafeBytes { (address) in
mutableSignatureBuffer.baseAddress?.advanced(by: 8).copyMemory(from: address.baseAddress!.advanced(by: 4), byteCount: 24)
}
}
}
}
guard let signature = Signature(darwinCompatibleDataRepresentation: signatureBytes) else {
return nil
}
if let socket = socket {
core.lock.synchronized {
if let existing = core.connectors[signature], CFSocketIsValid(existing) {
core.connectors[signature] = socket
}
}
}
let sender = SocketPort(remoteWithSignature: signature)
var index = messageBuffer.startIndex + signatureBytes.count + 20
var components: [AnyObject] = []
while index < messageBuffer.endIndex {
var word1: UInt32 = 0
var word2: UInt32 = 0
// The amount of data prior to this point may mean that these reads are unaligned; copy instead.
withUnsafeMutableBytes(of: &word1) { (destination) -> Void in
messageBuffer.copyBytes(to: destination, from: Int(index - 8) ..< Int(index - 4))
}
withUnsafeMutableBytes(of: &word2) { (destination) -> Void in
messageBuffer.copyBytes(to: destination, from: Int(index - 4) ..< Int(index))
}
let componentType = word1.bigEndian
let componentLength = word2.bigEndian
let componentEndIndex = min(index + Int(componentLength), messageBuffer.endIndex)
let componentData = Data(messageBuffer[index ..< componentEndIndex])
if let type = ComponentType(rawValue: componentType) {
switch type {
case .data:
components.append(componentData._nsObject)
case .port:
if let signature = Signature(darwinCompatibleDataRepresentation: componentData) {
components.append(SocketPort(remoteWithSignature: signature))
}
}
}
guard messageBuffer.formIndex(&index, offsetBy: componentData.count + 8, limitedBy: messageBuffer.endIndex) else {
break
}
}
let message = PortMessage(sendPort: sender, receivePort: self, components: components)
message.msgid = msgId
return message
}
if let portMessage = portMessage {
delegate.handle(portMessage)
}
}
open override func send(before limitDate: Date, components: NSMutableArray?, from receivePort: Port?, reserved headerSpaceReserved: Int) -> Bool {
send(before: limitDate, msgid: 0, components: components, from: receivePort, reserved: headerSpaceReserved)
}
open override func send(before limitDate: Date, msgid msgID: Int, components: NSMutableArray?, from receivePort: Port?, reserved headerSpaceReserved: Int) -> Bool {
guard let sender = sendingSocket(for: self, before: limitDate.timeIntervalSinceReferenceDate),
let signature = core.signature.darwinCompatibleDataRepresentation else {
return false
}
let magicNumber: UInt32 = SocketPort.magicNumber.bigEndian
var outLength: UInt32 = 0
let messageNumber = UInt32(msgID).bigEndian
var data = Data()
withUnsafeBytes(of: magicNumber) { data.append(contentsOf: $0) }
withUnsafeBytes(of: outLength) { data.append(contentsOf: $0) } // Reserve space for it.
withUnsafeBytes(of: messageNumber) { data.append(contentsOf: $0) }
data.append(contentsOf: signature)
for component in components?.allObjects ?? [] {
var componentData: Data
var componentType: ComponentType
switch component {
case let component as Data:
componentData = component
componentType = .data
case let component as NSData:
componentData = component._swiftObject
componentType = .data
case let component as SocketPort:
guard let signature = component.core.signature.darwinCompatibleDataRepresentation else {
return false
}
componentData = signature
componentType = .port
default:
return false
}
var componentLength = UInt32(componentData.count).bigEndian
var componentTypeRawValue = UInt32(componentType.rawValue).bigEndian
withUnsafeBytes(of: &componentTypeRawValue) { data.append(contentsOf: $0) }
withUnsafeBytes(of: &componentLength) { data.append(contentsOf: $0) }
data.append(contentsOf: componentData)
}
outLength = UInt32(data.count).bigEndian
withUnsafeBytes(of: outLength) { (lengthBytes) -> Void in
data.withUnsafeMutableBytes { (bytes) -> Void in
bytes.baseAddress!.advanced(by: 4).copyMemory(from: lengthBytes.baseAddress!, byteCount: lengthBytes.count)
}
}
let result = CFSocketSendData(sender, self.address._cfObject, data._cfObject, limitDate.timeIntervalSinceNow)
switch result {
case kCFSocketSuccess:
return true
case kCFSocketError: fallthrough
case kCFSocketTimeout:
return false
default:
fatalError("Unknown result of sending through a socket: \(result)")
}
}
private static let maximumTimeout: TimeInterval = 86400
private static let sendingSocketsLock = NSLock()
private static var sendingSockets: [SocketKind: CFSocket] = [:]
private final func sendingSocket(for port: SocketPort, before time: TimeInterval) -> CFSocket? {
let signature = port.core.signature!
let socketKind = signature.socketKind
var context = CFSocketContext()
context.info = Unmanaged.passUnretained(self).toOpaque()
return core.lock.synchronized {
if let connector = core.connectors[signature], CFSocketIsValid(connector) {
return connector
} else {
if signature.socketType == SOCK_STREAM {
if let connector = CFSocketCreate(nil, socketKind.protocolFamily, socketKind.socketType, socketKind.protocol, CFOptionFlags(kCFSocketDataCallBack), __NSFireSocketData, &context), CFSocketIsValid(connector) {
var timeout = time - Date.timeIntervalSinceReferenceDate
if timeout < 0 || timeout >= SocketPort.maximumTimeout {
timeout = 0
}
if CFSocketIsValid(connector) && CFSocketConnectToAddress(connector, address._cfObject, timeout) == CFSocketError(0) {
core.connectors[signature] = connector
self.addToLoopsAssumingLockHeld(connector)
return connector
} else {
CFSocketInvalidate(connector)
}
}
} else {
return SocketPort.sendingSocketsLock.synchronized {
var result: CFSocket?
if signature.socketKind == core.signature.socketKind,
let receiver = core.receiver, CFSocketIsValid(receiver) {
result = receiver
} else if let socket = SocketPort.sendingSockets[socketKind], CFSocketIsValid(socket) {
result = socket
}
if result == nil,
let sender = CFSocketCreate(nil, socketKind.protocolFamily, socketKind.socketType, socketKind.protocol, CFOptionFlags(kCFSocketNoCallBack), nil, &context), CFSocketIsValid(sender) {
SocketPort.sendingSockets[socketKind] = sender
result = sender
}
return result
}
}
}
return nil
}
}
}
fileprivate extension Data {
subscript(offset value: Int) -> Data.Element {
return self[self.index(self.startIndex, offsetBy: value)]
}
subscript(offset range: Range<Int>) -> Data.SubSequence {
return self[self.index(self.startIndex, offsetBy: range.lowerBound) ..< self.index(self.startIndex, offsetBy: range.upperBound)]
}
subscript(offset range: ClosedRange<Int>) -> Data.SubSequence {
return self[self.index(self.startIndex, offsetBy: range.lowerBound) ... self.index(self.startIndex, offsetBy: range.upperBound)]
}
subscript(offset range: PartialRangeFrom<Int>) -> Data.SubSequence {
return self[self.index(self.startIndex, offsetBy: range.lowerBound)...]
}
subscript(offset range: PartialRangeUpTo<Int>) -> Data.SubSequence {
return self[...self.index(self.startIndex, offsetBy: range.upperBound)]
}
}
| apache-2.0 |
practicalswift/swift | test/Generics/requirement_inference.swift | 2 | 14502 | // RUN: %target-typecheck-verify-swift -typecheck -verify
// RUN: %target-typecheck-verify-swift -typecheck -debug-generic-signatures > %t.dump 2>&1
// RUN: %FileCheck %s < %t.dump
protocol P1 {
func p1()
}
protocol P2 : P1 { }
struct X1<T : P1> {
func getT() -> T { }
}
class X2<T : P1> {
func getT() -> T { }
}
class X3 { }
struct X4<T : X3> {
func getT() -> T { }
}
struct X5<T : P2> { }
// Infer protocol requirements from the parameter type of a generic function.
func inferFromParameterType<T>(_ x: X1<T>) {
x.getT().p1()
}
// Infer protocol requirements from the return type of a generic function.
func inferFromReturnType<T>(_ x: T) -> X1<T> {
x.p1()
}
// Infer protocol requirements from the superclass of a generic parameter.
func inferFromSuperclass<T, U : X2<T>>(_ t: T, u: U) -> T {
t.p1()
}
// Infer protocol requirements from the parameter type of a constructor.
struct InferFromConstructor {
init<T> (x : X1<T>) {
x.getT().p1()
}
}
// Don't infer requirements for outer generic parameters.
class Fox : P1 {
func p1() {}
}
class Box<T : Fox, U> {
func unpack(_ x: X1<T>) {}
func unpackFail(_ X: X1<U>) { } // expected-error{{type 'U' does not conform to protocol 'P1'}}
}
// ----------------------------------------------------------------------------
// Superclass requirements
// ----------------------------------------------------------------------------
// Compute meet of two superclass requirements correctly.
class Carnivora {}
class Canidae : Carnivora {}
struct U<T : Carnivora> {}
struct V<T : Canidae> {}
// CHECK-LABEL: .inferSuperclassRequirement1@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Canidae>
func inferSuperclassRequirement1<T : Carnivora>(
_ v: V<T>) {}
// CHECK-LABEL: .inferSuperclassRequirement2@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Canidae>
func inferSuperclassRequirement2<T : Canidae>(_ v: U<T>) {}
// ----------------------------------------------------------------------------
// Same-type requirements
// ----------------------------------------------------------------------------
protocol P3 {
associatedtype P3Assoc : P2 // expected-note{{declared here}}
}
protocol P4 {
associatedtype P4Assoc : P1
}
protocol PCommonAssoc1 {
associatedtype CommonAssoc
}
protocol PCommonAssoc2 {
associatedtype CommonAssoc
}
protocol PAssoc {
associatedtype Assoc
}
struct Model_P3_P4_Eq<T : P3, U : P4> where T.P3Assoc == U.P4Assoc {}
func inferSameType1<T, U>(_ x: Model_P3_P4_Eq<T, U>) {
let u: U.P4Assoc? = nil
let _: T.P3Assoc? = u!
}
func inferSameType2<T : P3, U : P4>(_: T, _: U) where U.P4Assoc : P2, T.P3Assoc == U.P4Assoc {}
// expected-warning@-1{{redundant conformance constraint 'T.P3Assoc': 'P2'}}
// expected-note@-2{{conformance constraint 'T.P3Assoc': 'P2' implied here}}
func inferSameType3<T : PCommonAssoc1>(_: T) where T.CommonAssoc : P1, T : PCommonAssoc2 {
}
protocol P5 {
associatedtype Element
}
protocol P6 {
associatedtype AssocP6 : P5
}
protocol P7 : P6 {
associatedtype AssocP7: P6
}
// CHECK-LABEL: P7@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P7, τ_0_0.AssocP6.Element : P6, τ_0_0.AssocP6.Element == τ_0_0.AssocP7.AssocP6.Element>
extension P7 where AssocP6.Element : P6, // expected-note{{conformance constraint 'Self.AssocP6.Element': 'P6' written here}}
AssocP7.AssocP6.Element : P6, // expected-warning{{redundant conformance constraint 'Self.AssocP6.Element': 'P6'}}
AssocP6.Element == AssocP7.AssocP6.Element {
func nestedSameType1() { }
}
protocol P8 {
associatedtype A
associatedtype B
}
protocol P9 : P8 {
associatedtype A
associatedtype B
}
protocol P10 {
associatedtype A
associatedtype C
}
// CHECK-LABEL: sameTypeConcrete1@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P10, τ_0_0 : P9, τ_0_0.A == X3, τ_0_0.B == Int, τ_0_0.C == Int>
func sameTypeConcrete1<T : P9 & P10>(_: T) where T.A == X3, T.C == T.B, T.C == Int { }
// CHECK-LABEL: sameTypeConcrete2@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P10, τ_0_0 : P9, τ_0_0.B == X3, τ_0_0.C == X3>
func sameTypeConcrete2<T : P9 & P10>(_: T) where T.B : X3, T.C == T.B, T.C == X3 { }
// expected-warning@-1{{redundant superclass constraint 'T.B' : 'X3'}}
// expected-note@-2{{same-type constraint 'T.C' == 'X3' written here}}
// Note: a standard-library-based stress test to make sure we don't inject
// any additional requirements.
// CHECK-LABEL: RangeReplaceableCollection
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : MutableCollection, τ_0_0 : RangeReplaceableCollection, τ_0_0.SubSequence == Slice<τ_0_0>>
extension RangeReplaceableCollection
where Self: MutableCollection, Self.SubSequence == Slice<Self>
{
func f() { }
}
// CHECK-LABEL: X14.recursiveConcreteSameType
// CHECK: Generic signature: <T, V where T == Range<Int>>
// CHECK-NEXT: Canonical generic signature: <τ_0_0, τ_1_0 where τ_0_0 == Range<Int>>
struct X14<T> where T.Iterator == IndexingIterator<T> {
func recursiveConcreteSameType<V>(_: V) where T == Range<Int> { }
}
// rdar://problem/30478915
protocol P11 {
associatedtype A
}
protocol P12 {
associatedtype B: P11
}
struct X6 { }
struct X7 : P11 {
typealias A = X6
}
struct X8 : P12 {
typealias B = X7
}
struct X9<T: P12, U: P12> where T.B == U.B {
// CHECK-LABEL: X9.upperSameTypeConstraint
// CHECK: Generic signature: <T, U, V where T == X8, U : P12, U.B == X8.B>
// CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 == X8, τ_0_1 : P12, τ_0_1.B == X7>
func upperSameTypeConstraint<V>(_: V) where T == X8 { }
}
protocol P13 {
associatedtype C: P11
}
struct X10: P11, P12 {
typealias A = X10
typealias B = X10
}
struct X11<T: P12, U: P12> where T.B == U.B.A {
// CHECK-LABEL: X11.upperSameTypeConstraint
// CHECK: Generic signature: <T, U, V where T : P12, U == X10, T.B == X10.A>
// CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 : P12, τ_0_1 == X10, τ_0_0.B == X10>
func upperSameTypeConstraint<V>(_: V) where U == X10 { }
}
#if _runtime(_ObjC)
// rdar://problem/30610428
@objc protocol P14 { }
class X12<S: AnyObject> {
func bar<V>(v: V) where S == P14 {
}
}
@objc protocol P15: P14 { }
class X13<S: P14> {
func bar<V>(v: V) where S == P15 {
}
}
#endif
protocol P16 {
associatedtype A
}
struct X15 { }
struct X16<X, Y> : P16 {
typealias A = (X, Y)
}
// CHECK-LABEL: .X17.bar@
// CHECK: Generic signature: <S, T, U, V where S == X16<X3, X15>, T == X3, U == X15>
struct X17<S: P16, T, U> where S.A == (T, U) {
func bar<V>(_: V) where S == X16<X3, X15> { }
}
// Same-type constraints that are self-derived via a parent need to be
// suppressed in the resulting signature.
protocol P17 { }
protocol P18 {
associatedtype A: P17
}
struct X18: P18, P17 {
typealias A = X18
}
// CHECK-LABEL: .X19.foo@
// CHECK: Generic signature: <T, U where T == X18>
struct X19<T: P18> where T == T.A {
func foo<U>(_: U) where T == X18 { }
}
// rdar://problem/31520386
protocol P20 { }
struct X20<T: P20> { }
// CHECK-LABEL: .X21.f@
// CHECK: Generic signature: <T, U, V where T : P20, U == X20<T>>
// CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 : P20, τ_0_1 == X20<τ_0_0>>
struct X21<T, U> {
func f<V>(_: V) where U == X20<T> { }
}
struct X22<T, U> {
func g<V>(_: V) where T: P20,
U == X20<T> { }
}
// CHECK: Generic signature: <Self where Self : P22>
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P22>
// CHECK: Protocol requirement signature:
// CHECK: .P22@
// CHECK-NEXT: Requirement signature: <Self where Self.A == X20<Self.B>, Self.B : P20>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X20<τ_0_0.B>, τ_0_0.B : P20>
protocol P22 {
associatedtype A
associatedtype B: P20 where A == X20<B>
}
// CHECK: Generic signature: <Self where Self : P23>
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P23>
// CHECK: Protocol requirement signature:
// CHECK: .P23@
// CHECK-NEXT: Requirement signature: <Self where Self.A == X20<Self.B>, Self.B : P20>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X20<τ_0_0.B>, τ_0_0.B : P20>
protocol P23 {
associatedtype A
associatedtype B: P20
where A == X20<B>
}
protocol P24 {
associatedtype C: P20
}
struct X24<T: P20> : P24 {
typealias C = T
}
// CHECK-LABEL: .P25a@
// CHECK-NEXT: Requirement signature: <Self where Self.A == X24<Self.B>, Self.B : P20>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X24<τ_0_0.B>, τ_0_0.B : P20>
protocol P25a {
associatedtype A: P24 // expected-warning{{redundant conformance constraint 'Self.A': 'P24'}}
associatedtype B: P20 where A == X24<B> // expected-note{{conformance constraint 'Self.A': 'P24' implied here}}
}
// CHECK-LABEL: .P25b@
// CHECK-NEXT: Requirement signature: <Self where Self.A == X24<Self.B>, Self.B : P20>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X24<τ_0_0.B>, τ_0_0.B : P20>
protocol P25b {
associatedtype A
associatedtype B: P20 where A == X24<B>
}
protocol P25c {
associatedtype A: P24
associatedtype B where A == X<B> // expected-error{{use of undeclared type 'X'}}
}
protocol P25d {
associatedtype A
associatedtype B where A == X24<B> // expected-error{{type 'Self.B' does not conform to protocol 'P20'}}
}
// Similar to the above, but with superclass constraints.
protocol P26 {
associatedtype C: X3
}
struct X26<T: X3> : P26 {
typealias C = T
}
// CHECK-LABEL: .P27a@
// CHECK-NEXT: Requirement signature: <Self where Self.A == X26<Self.B>, Self.B : X3>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X26<τ_0_0.B>, τ_0_0.B : X3>
protocol P27a {
associatedtype A: P26 // expected-warning{{redundant conformance constraint 'Self.A': 'P26'}}
associatedtype B: X3 where A == X26<B> // expected-note{{conformance constraint 'Self.A': 'P26' implied here}}
}
// CHECK-LABEL: .P27b@
// CHECK-NEXT: Requirement signature: <Self where Self.A == X26<Self.B>, Self.B : X3>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X26<τ_0_0.B>, τ_0_0.B : X3>
protocol P27b {
associatedtype A
associatedtype B: X3 where A == X26<B>
}
// ----------------------------------------------------------------------------
// Inference of associated type relationships within a protocol hierarchy
// ----------------------------------------------------------------------------
struct X28 : P2 {
func p1() { }
}
// CHECK-LABEL: .P28@
// CHECK-NEXT: Requirement signature: <Self where Self : P3, Self.P3Assoc == X28>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : P3, τ_0_0.P3Assoc == X28>
protocol P28: P3 {
typealias P3Assoc = X28 // expected-warning{{typealias overriding associated type}}
}
// ----------------------------------------------------------------------------
// Inference of associated types by name match
// ----------------------------------------------------------------------------
protocol P29 {
associatedtype X
}
protocol P30 {
associatedtype X
}
protocol P31 { }
// CHECK-LABEL: .sameTypeNameMatch1@
// CHECK: Generic signature: <T where T : P29, T : P30, T.X : P31>
func sameTypeNameMatch1<T: P29 & P30>(_: T) where T.X: P31 { }
// ----------------------------------------------------------------------------
// Infer requirements from conditional conformances
// ----------------------------------------------------------------------------
protocol P32 {}
protocol P33 {
associatedtype A: P32
}
protocol P34 {}
struct Foo<T> {}
extension Foo: P32 where T: P34 {}
// Inference chain: U.A: P32 => Foo<V>: P32 => V: P34
// CHECK-LABEL: conditionalConformance1@
// CHECK: Generic signature: <U, V where U : P33, V : P34, U.A == Foo<V>>
// CHECK: Canonical generic signature: <τ_0_0, τ_0_1 where τ_0_0 : P33, τ_0_1 : P34, τ_0_0.A == Foo<τ_0_1>>
func conditionalConformance1<U: P33, V>(_: U) where U.A == Foo<V> {}
struct Bar<U: P32> {}
// CHECK-LABEL: conditionalConformance2@
// CHECK: Generic signature: <V where V : P34>
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P34>
func conditionalConformance2<V>(_: Bar<Foo<V>>) {}
// Mentioning a nested type that is conditional should infer that requirement (SR 6850)
protocol P35 {}
protocol P36 {
func foo()
}
struct ConditionalNested<T> {}
extension ConditionalNested where T: P35 {
struct Inner {}
}
// CHECK: Generic signature: <T where T : P35, T : P36>
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P35, τ_0_0 : P36>
extension ConditionalNested.Inner: P36 where T: P36 {
func foo() {}
struct Inner2 {}
}
// CHECK-LABEL: conditionalNested1@
// CHECK: Generic signature: <U where U : P35>
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P35>
func conditionalNested1<U>(_: [ConditionalNested<U>.Inner?]) {}
// CHECK-LABEL: conditionalNested2@
// CHECK: Generic signature: <U where U : P35, U : P36>
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P35, τ_0_0 : P36>
func conditionalNested2<U>(_: [ConditionalNested<U>.Inner.Inner2?]) {}
//
// Generate typalias adds requirements that can be inferred
//
typealias X1WithP2<T: P2> = X1<T>
// Inferred requirement T: P2 from the typealias
func testX1WithP2<T>(_: X1WithP2<T>) {
_ = X5<T>() // requires P2
}
// Overload based on the inferred requirement.
func testX1WithP2Overloading<T>(_: X1<T>) {
_ = X5<T>() // expected-error{{type 'T' does not conform to protocol 'P2'}}
}
func testX1WithP2Overloading<T>(_: X1WithP2<T>) {
_ = X5<T>() // requires P2
}
// Extend using the inferred requirement.
extension X1WithP2 {
func f() {
_ = X5<T>() // okay: inferred T: P2 from generic typealias
}
}
extension X1: P1 {
func p1() { }
}
typealias X1WithP2Changed<T: P2> = X1<X1<T>>
typealias X1WithP2MoreArgs<T: P2, U> = X1<T>
extension X1WithP2Changed {
func bad1() {
_ = X5<T>() // expected-error{{type 'T' does not conform to protocol 'P2'}}
}
}
extension X1WithP2MoreArgs {
func bad2() {
_ = X5<T>() // expected-error{{type 'T' does not conform to protocol 'P2'}}
}
}
// Inference from protocol inheritance clauses.
typealias ExistentialP4WithP2Assoc<T: P4> = P4 where T.P4Assoc : P2
protocol P37 : ExistentialP4WithP2Assoc<Self> { }
extension P37 {
func f() {
_ = X5<P4Assoc>() // requires P2
}
}
| apache-2.0 |
sajeel/AutoScout | AutoScout/Models & View Models/Protocols/ViewModelOutput.swift | 1 | 283 | //
// CarsViewModelOutput.swift
// AutoScout
//
// Created by Sajjeel Khilji on 5/21/17.
// Copyright © 2017 Saj. All rights reserved.
//
import Foundation
public protocol ViewModelOutput: class
{
func viewModelDidUpdate()
func viewModelLoadingDidFail(error: Error)
}
| gpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/Network/Sources/NetworkKit/Extensions/URLRequestExtensions.swift | 1 | 221 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
extension URLRequest {
init(url: URL, method: HTTPMethod) {
self.init(url: url)
httpMethod = method.rawValue
}
}
| lgpl-3.0 |
ashfurrow/eidolon | Kiosk/App/Models/GenericError.swift | 2 | 767 | import Foundation
import SwiftyJSON
final class GenericError: NSObject, JSONAbleType {
let detail: [String:AnyObject]
let message: String
let type: String
init(type: String, message: String, detail: [String:AnyObject]) {
self.detail = detail
self.message = message
self.type = type
}
static func fromJSON(_ json:[String: Any]) -> GenericError {
let json = JSON(json)
let type = json["type"].stringValue
let message = json["message"].stringValue
var detailDictionary = json["detail"].object as? [String: AnyObject]
detailDictionary = detailDictionary ?? [:]
return GenericError(type: type, message: message, detail: detailDictionary!)
}
}
| mit |
JaSpa/swift | test/SourceKit/Indexing/index.swift | 7 | 2590 | // RUN: %sourcekitd-test -req=index %s -- -serialize-diagnostics-path %t.dia %s | %sed_clean > %t.response
// RUN: diff -u %s.response %t.response
var globV: Int
class CC {
init() {}
var instV: CC
func meth() {}
func instanceFunc0(_ a: Int, b: Float) -> Int {
return 0
}
func instanceFunc1(a x: Int, b y: Float) -> Int {
return 0
}
class func smeth() {}
}
func +(a : CC, b: CC) -> CC {
return a
}
struct S {
func meth() {}
static func smeth() {}
}
enum E {
case EElem
}
protocol Prot {
func protMeth(_ a: Prot)
}
func foo(_ a: CC, b: inout E) {
globV = 0
a + a.instV
a.meth()
CC.smeth()
b = E.EElem
var local: CC
class LocalCC {}
var local2: LocalCC
}
typealias CCAlias = CC
extension CC : Prot {
func meth2(_ x: CCAlias) {}
func protMeth(_ a: Prot) {}
var extV : Int { return 0 }
}
class SubCC : CC, Prot {}
var globV2: SubCC
class ComputedProperty {
var value : Int {
get {
var result = 0
return result
}
set(newVal) {
// completely ignore it!
}
}
var readOnly : Int { return 0 }
}
class BC2 {
func protMeth(_ a: Prot) {}
}
class SubC2 : BC2, Prot {
override func protMeth(_ a: Prot) {}
}
class CC2 {
subscript (i : Int) -> Int {
get {
return i
}
set(v) {
v+1
}
}
}
func test1(_ cp: ComputedProperty, sub: CC2) {
var x = cp.value
x = cp.readOnly
cp.value = x
++cp.value
x = sub[0]
sub[0] = x
++sub[0]
}
struct S2 {
func sfoo() {}
}
var globReadOnly : S2 {
get {
return S2();
}
}
func test2() {
globReadOnly.sfoo()
}
class B1 {
func foo() {}
}
class SB1 : B1 {
override func foo() {
foo()
self.foo()
super.foo()
}
}
func test3(_ c: SB1, s: S2) {
test2()
c.foo()
s.sfoo()
}
extension Undeclared {
func meth() {}
}
class CC4 {
convenience init(x: Int) {
self.init(x:0)
}
}
class SubCC4 : CC4 {
init(x: Int) {
super.init(x:0)
}
}
class Observing {
init() {}
var globObserving : Int {
willSet {
test2()
}
didSet {
test2()
}
}
}
// <rdar://problem/18640140> :: Crash in swift::Mangle::Mangler::mangleIdentifier()
class rdar18640140 {
// didSet is not compatible with set/get
var S1: Int {
get {
return 1
}
set {
}
didSet {
}
}
}
protocol rdar18640140Protocol {
var S1: Int {
get
set
get
}
}
@available(*, unavailable)
class AlwaysUnavailableClass {
}
@available(iOS 99.99, *)
class ConditionalUnavailableClass1{
}
@available(OSX 99.99, *)
class ConditionalUnavailableClass2{
}
| apache-2.0 |
peteratseneca/dps923winter2015 | Week_12/ShapesV1/NewShapes/Shape.swift | 1 | 2286 | //
// Shape.swift
// NewShapes
//
// Created by Peter McIntyre on 2015-04-05.
// Copyright (c) 2015 Seneca College. All rights reserved.
//
import UIKit
class Shape: UIView {
// MARK: - Class members
var shapeType: NSString!
var shapeColor: CGColorRef!
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
// This is necessary (leave it out and you'll see why)
self.backgroundColor = UIColor.clearColor()
}
// The Xcode editor and compiler required this method to be added
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// This method MUST be implemented in a UIView subclass like this
override func drawRect(rect: CGRect) {
// Get the graphics context
let context = UIGraphicsGetCurrentContext()
// Configure the drawing settings with the passed-in color
CGContextSetLineWidth(context, 1.0);
CGContextSetStrokeColorWithColor(context, shapeColor);
CGContextSetFillColorWithColor(context, shapeColor);
// Draw the shape's word/name inside the passed-in rectangle
switch self.shapeType {
case "Square", "Rectangle":
// ...AddRect... can draw both squares and rectangles
CGContextAddRect(context, rect);
CGContextFillRect(context, rect);
case "Circle", "Ellipse":
// ...AddEllipse... can draw both circles and ellipses
CGContextAddEllipseInRect(context, rect);
CGContextFillEllipseInRect(context, rect);
default:
break
}
// Position the shape's word/name a little better
// This is a hacky way to do it, but it keeps the lines of code to a minimum
shapeType = "\n\(shapeType)"
let centerTextStyle = NSMutableParagraphStyle()
centerTextStyle.alignment = NSTextAlignment.Center
// Draw the shape's word/name on the shape
shapeType.drawInRect(rect, withAttributes: [NSFontAttributeName : UIFont.systemFontOfSize(20), NSParagraphStyleAttributeName : centerTextStyle])
}
}
| mit |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Gemini/Gemini/GeminiCell.swift | 2 | 281 | import UIKit
open class GeminiCell: UICollectionViewCell {
override open func prepareForReuse() {
super.prepareForReuse()
adjustAnchorPoint()
layer.transform = CATransform3DIdentity
}
open var shadowView: UIView? {
return nil
}
}
| mit |
googlearchive/science-journal-ios | ScienceJournal/Extensions/UICollectionView+PerformChanges.swift | 1 | 2248 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
/// A type of change for a collection view. Used to describe a batch of changes.
///
/// - reloadData: A full reload of all data.
/// - insert: Inserts the associated index paths.
/// - insertSections: Inserts the associated sections.
/// - delete: Deletes the associated index paths.
/// - deleteSections: Deletes the associated sections.
/// - reload: Reloads the associated index paths.
/// - reloadSections: Reloads the associated sections.
enum CollectionViewChange {
case reloadData
case insert([IndexPath])
case insertSections(IndexSet)
case delete([IndexPath])
case deleteSections(IndexSet)
case reload([IndexPath])
case reloadSections(IndexSet)
}
extension UICollectionView {
/// Performs the given changes.
///
/// - Parameter changes: An array of changes.
func performChanges(_ changes: [CollectionViewChange], completion: ((Bool) -> Void)? = nil) {
performBatchUpdates({
changeLoop: for change in changes {
switch change {
case .insert(let indexPaths):
self.insertItems(at: indexPaths)
case .insertSections(let indexSet):
self.insertSections(indexSet)
case .delete(let indexPaths):
self.deleteItems(at: indexPaths)
case .deleteSections(let indexSet):
self.deleteSections(indexSet)
case .reload(let indexPaths):
self.reloadItems(at: indexPaths)
case .reloadSections(let indexSet):
self.reloadSections(indexSet)
case .reloadData:
self.reloadData()
break changeLoop
}
}
}, completion: completion)
}
}
| apache-2.0 |
czak/triangulator | Triangulator/MainWindowController.swift | 1 | 2376 | //
// MainWindowController.swift
// Triangulator
//
// Created by Łukasz Adamczak on 19.06.2015.
// Copyright (c) 2015 Łukasz Adamczak.
//
// Triangulator is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
import Cocoa
class MainWindowController: NSWindowController {
// MARK: - Outlets
@IBOutlet weak var palettePopUpButton: NSPopUpButton!
@IBOutlet weak var backgroundView: NSView!
// MARK: - Properties
var pattern: Pattern = Pattern(width: 640, height: 400, cellSize: 40, variance: 0.5, palette: Palette.defaultPalettes[0])
// MARK: - Window setup
override var windowNibName: String {
return "MainWindowController"
}
override func windowDidLoad() {
super.windowDidLoad()
// White background under the image
backgroundView.layer!.backgroundColor = CGColorCreateGenericGray(1, 1)
populatePalettesPopup()
}
func populatePalettesPopup() {
let menu = palettePopUpButton.menu!
for palette in Palette.defaultPalettes {
let item = NSMenuItem()
item.title = ""
item.representedObject = palette
item.image = palette.swatchImageForSize(NSSize(width: 110, height: 13))
menu.addItem(item)
}
}
// MARK: - Actions
@IBAction func changePalette(sender: NSPopUpButton) {
pattern.palette = sender.selectedItem!.representedObject as! Palette
}
// MARK: - Saving
func saveDocument(sender: AnyObject) {
let panel = NSSavePanel()
panel.allowedFileTypes = ["png"]
panel.beginSheetModalForWindow(window!, completionHandler: { button in
if button == NSFileHandlingPanelCancelButton { return }
if let url = panel.URL, data = self.pattern.dataForPNG {
data.writeToURL(url, atomically: true)
}
else {
let alert = NSAlert()
alert.messageText = "Unable to save image"
alert.beginSheetModalForWindow(self.window!, completionHandler: nil)
}
})
}
}
| gpl-3.0 |
gitgitcode/LearnSwift | Calculator/Caiculator/Caiculator/AppDelegate.swift | 1 | 2139 | //
// AppDelegate.swift
// Caiculator
//
// Created by xuthus on 15/6/14.
// Copyright (c) 2015年 xuthus. All rights reserved.
//
import UIKit
@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:.
}
}
| apache-2.0 |
chrisjmendez/swift-exercises | Video/MediaPlayer/MediaPlayer/AppDelegate.swift | 1 | 2148 | //
// AppDelegate.swift
// MediaPlayer
//
// Created by Tommy Trojan on 10/2/15.
// Copyright © 2015 Chris Mendez. All rights reserved.
//
import UIKit
@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:.
}
}
| mit |
JerrySir/YCOA | YCOA/Main/Contacts/Controller/ContactsStructTableViewController.swift | 1 | 16401 | //
// ContactsStructTableViewController.swift
// YCOA
//
// Created by Jerry on 2017/2/5.
// Copyright © 2017年 com.baochunsteel. All rights reserved.
//
import UIKit
import Alamofire
import MJRefresh
class ContactsStructTableViewController: UITableViewController {
var dataSource : [groupNode]? //数据源
var selectedItems: NSSet = NSSet() //已经选择的
var tap: ((_ ids: [String], _ names: [String]) -> Void)?
/// 配置选择列表
///
/// - Parameters:
/// - selectedItems: 已经选择了的数据节点ID
/// - tap: 控制器返回或者确定的监听,返回已经选择的数据
func configure(selectedItems: [String]?, tap: ((_ ids: [String], _ names: [String]) -> Void)?) {
if(selectedItems != nil){
self.selectedItems = NSSet(array: selectedItems!)
}
self.tap = tap
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "组织结构"
/*
let rightBarButtonItem = UIBarButtonItem(title: "完成", style: .plain, target: nil, action: nil)
rightBarButtonItem.actionBlock = {(sender) -> Void in
var ids : [String] = []
var names: [String] = []
for item in self.dataSource! {
//是否根节点处全选
if(item.isSelectedAll){
ids.append(item.groupID)
names.append(item.groupTitle)
continue
}else{
//从子节点处检查被选中的
guard item.subNode != nil && item.subNode!.count > 0 else {continue}
for subNodeItem in item.subNode! {
if(subNodeItem.isSelected){
ids.append(subNodeItem.subNodeID)
names.append(subNodeItem.uName)
}
}
}
}
NSLog("选中了:\((names as NSArray).componentsJoined(by: ","))")
//检查是pop还是dismiss
if (self.navigationController?.topViewController == self)
{
self.navigationController!.popViewController(animated: true)
if(self.tap != nil){
self.tap!(ids, names)
}
}
else
{
self.dismiss(animated: true, completion: { () -> Void in
if(self.tap != nil){
self.tap!(ids, names)
}
})
}
}
self.navigationItem.rightBarButtonItem = rightBarButtonItem
*/
// self.tableView.allowsMultipleSelection = true
self.tableView.register(ContactsStructItemTableViewCell.self, forCellReuseIdentifier: "cell")
}
deinit {
NSLog("卧槽,竟然释放了")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(reloadData))
self.tableView.mj_header.beginRefreshing()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func reloadData() {
guard UserCenter.shareInstance().isLogin else {
self.view.jrShow(withTitle: "未登录!")
self.tableView.mj_header.endRefreshing()
return
}
let parameters: Parameters = ["adminid": UserCenter.shareInstance().uid!,
"timekey": NSDate.nowTimeToTimeStamp(),
"token": UserCenter.shareInstance().token!,
"cfrom": "appiphone",
"appapikey": UserCenter.shareInstance().apikey!]
guard let url = URL.JRURLEnCoding(string: YCOA_REQUEST_URL.appending("/index.php?d=taskrun&m=user|appapi&a=getdeptadmin&ajaxbool=true")) else {
self.tableView.mj_header.endRefreshing()
return
}
Alamofire.request(url, parameters: parameters).responseJSON(completionHandler: { (response) in
self.tableView.mj_header.endRefreshing()
guard response.result.isSuccess else{
self.view.jrShow(withTitle: "网络错误")
return
}
guard let returnValue : NSDictionary = response.result.value as? NSDictionary else{
self.view.jrShow(withTitle: "服务器错误")
return
}
guard returnValue.value(forKey: "code") as! Int == 200 else{
self.view.jrShow(withTitle: "\(returnValue.value(forKey: "msg")!)")
return
}
guard let data : [NSDictionary] = returnValue.value(forKey: "data") as? [NSDictionary] else{
self.view.jrShow(withTitle: "服务器故障")
return
}
guard let dataArr : [NSDictionary] = data[0]["children"] as? [NSDictionary] else{
self.view.jrShow(withTitle: "暂无数据")
return
}
//同步数据
self.dataSource = []
for dataGroupItem in dataArr {
let groupName = dataGroupItem["name"] as? String
let groupID = dataGroupItem["id"] as? String
guard let dataSubNodeArr : [NSDictionary] = dataGroupItem["children"] as? [NSDictionary] else{continue}
var subNodes : [(icon: String, showName: String, uName: String, subNodeID: String, isSelected: Bool)] = []
for dataSubNodeItem in dataSubNodeArr {
let subNodeID = dataSubNodeItem["id"] as! String
let subNodeName = dataSubNodeItem["name"] as! String
let subNodeDeptname = dataSubNodeItem["deptname"] as! String
let subNodeRanking = dataSubNodeItem["ranking"] as! String
let subNodeIcon = dataSubNodeItem["face"] as! String
let subNode = ("\(YCOA_REQUEST_URL)/\(subNodeIcon)",
"\(subNodeName) (\(subNodeDeptname) \(subNodeRanking))",
"\(subNodeName)",
subNodeID,
self.selectedItems.contains(subNodeID))
subNodes.append(subNode)
}
self.dataSource!.append(groupNode(groupTitle: groupName!, groupID: groupID!, subNode: subNodes))
}
//循环遍历根节点的选择状态
for index in 0..<self.dataSource!.count {
self.dataSource![index].isSelectedAll = self.selectedItems.contains(self.dataSource![index].groupID)
if(self.dataSource![index].isSelectedAll){
//如果是选择了部门,则选中所有子节点
self.setGroupSelectAll(groupIndex: index, isSelectAll: true)
}
}
self.tableView.reloadData()
})
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
guard self.dataSource != nil else {return 0}
return self.dataSource!.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(self.dataSource![section].isFold){ //是否折叠
return 0
}
guard self.dataSource![section].subNode != nil else {return 0}
return self.dataSource![section].subNode!.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ContactsStructItemTableViewCell
cell.configure(icon: self.dataSource![indexPath.section].subNode![indexPath.row].icon,
title: self.dataSource![indexPath.section].subNode![indexPath.row].showName,
isSelected: self.dataSource![indexPath.section].subNode![indexPath.row].isSelected)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return makeSectionHeader(groupTitle: self.dataSource![section].groupTitle,
groupID: self.dataSource![section].groupID,
numberOfSubNode: (self.dataSource![section].subNode?.count)!,
isFold: self.dataSource![section].isFold,
isSelectedAll: self.dataSource![section].isSelectedAll,
didFoldTap: { (groupID) in
NSLog("did fold action \(groupID)")
self.dataSource![section].isFold = !(self.dataSource![section].isFold)
self.tableView.reloadData()
},
selectedAllTap: { (groupID) in
// NSLog("selected all action \(groupID)")
// if(self.dataSource![section].isSelectedAll){
// self.setGroupSelectAll(groupIndex: section, isSelectAll: false)
// self.dataSource![section].isSelectedAll = false
// }else{
// self.setGroupSelectAll(groupIndex: section, isSelectAll: true)
// self.dataSource![section].isSelectedAll = true
// }
// self.tableView.reloadData()
})
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50.0
}
/*
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.dataSource![indexPath.section].subNode![indexPath.row].isSelected =
!self.dataSource![indexPath.section].subNode![indexPath.row].isSelected
self.dataSource![indexPath.section].isSelectedAll = self.isGroupSelectedAll(group: self.dataSource![indexPath.section])
self.tableView.reloadData()
}
*/
//创建Section View
private func makeSectionHeader(groupTitle: String, groupID: String, numberOfSubNode: Int, isFold: Bool, isSelectedAll: Bool, didFoldTap: @escaping (_ groupID: String) -> Void, selectedAllTap: @escaping (_ groupID: String) -> Void) -> UIView {
let viewHeight : CGFloat = 50.0
let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: JRSCREEN_WIDTH, height: viewHeight))
view.backgroundColor = UIColor.groupTableViewBackground
let foldIcon = UIImageView(frame: CGRect(x: 16, y: 16, width: viewHeight - 32, height: viewHeight - 32))
view.addSubview(foldIcon)
foldIcon.image = #imageLiteral(resourceName: "cell_fold_right_icon.png")
if(isFold){
//默认可以不处理
}else{
let angle = Double(1) * M_PI_2
foldIcon.transform = CGAffineTransform(rotationAngle: CGFloat(angle))
}
let groupTitleLabel = UILabel(frame: CGRect(x: viewHeight, y: 8, width: JRSCREEN_WIDTH - viewHeight - 16 - viewHeight, height: viewHeight - 16))
view.addSubview(groupTitleLabel)
groupTitleLabel.text = "\(groupTitle) (\(numberOfSubNode))"
// let selectAllButton : UIButton = UIButton(frame: CGRect(x: JRSCREEN_WIDTH - viewHeight, y: 8, width: viewHeight - 16, height: viewHeight - 16))
// if(isSelectedAll){
// selectAllButton.setImage(#imageLiteral(resourceName: "cell_selected_icon.png"), for: .normal)
// }else{
// selectAllButton.setImage(#imageLiteral(resourceName: "cell_unselect_icon.png"), for: .normal)
// }
// view.addSubview(selectAllButton)
//Action
view.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer { (sender) in
didFoldTap(groupID)
}
view.addGestureRecognizer(tapGestureRecognizer)
// selectAllButton.addBlock(for: .touchUpInside) { (sender) in
// selectedAllTap(groupID)
// }
return view
}
//全选的相关方法
//组是否已经全选
func isGroupSelectedAll (group: groupNode) -> Bool {
if(group.subNode != nil && group.subNode!.count > 0){
var returnValue = true
for item in group.subNode! {
returnValue = returnValue && item.isSelected
}
return returnValue
}else{
return false
}
}
//设置组全选
func setGroupSelectAll (groupIndex: Int, isSelectAll: Bool) {
if(self.dataSource![groupIndex].subNode != nil && self.dataSource![groupIndex].subNode!.count > 0){
for index in 0..<self.dataSource![groupIndex].subNode!.count {
self.dataSource![groupIndex].subNode![index].isSelected = isSelectAll
}
}
}
}
//联系人选择Cell 高度:50
class ContactsStructItemTableViewCell: UITableViewCell {
private let CellHeight: CGFloat = 50.0
private var iconImageView: UIImageView?
private var titleLabel: UILabel?
private var selectImageView: UIImageView?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.iconImageView = UIImageView(frame: CGRect(x: 18,
y: 8,
width: CellHeight - 8 - 8,
height: CellHeight - 8 - 8))
self.titleLabel = UILabel(frame: CGRect(x: CellHeight + 10,
y: 8,
width: JRSCREEN_WIDTH - 2 * CellHeight + 5,
height: CellHeight - 8 - 8))
self.selectImageView = UIImageView(frame: CGRect(x: JRSCREEN_WIDTH - CellHeight,
y: 8,
width: CellHeight - 16,
height: CellHeight - 16))
self.contentView.addSubview(self.iconImageView!)
self.contentView.addSubview(self.titleLabel!)
self.contentView.addSubview(self.selectImageView!)
self.selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(icon: String?, title: String?, isSelected: Bool){
if(icon != nil){
self.iconImageView?.sd_setImage(with: URL(string: icon!),
placeholderImage: #imageLiteral(resourceName: "imagePlaceHolder"),
options: .lowPriority)
}
self.titleLabel?.text = title
// if(isSelected){
// self.selectImageView?.image = #imageLiteral(resourceName: "cell_selected_icon.png")
// }else{
// self.selectImageView?.image = #imageLiteral(resourceName: "cell_unselect_icon.png")
// }
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
//逗逼才会在这里图片替换逻辑 -. -!
}
}
| mit |
sseitov/v-Chess-Swift | v-Chess/MemberCell.swift | 1 | 1049 | //
// MemberCell.swift
// v-Chess
//
// Created by Сергей Сейтов on 13.03.17.
// Copyright © 2017 V-Channel. All rights reserved.
//
import UIKit
import SDWebImage
class MemberCell: UITableViewCell {
@IBOutlet weak var memberView: UIImageView!
@IBOutlet weak var memberName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
var member:AppUser? {
didSet {
if member!.avatar != nil, let data = member!.avatar as Data?, let image = UIImage(data: data) {
memberView.image = image.withSize(memberView.frame.size).inCircle()
} else if member!.avatarURL != nil, let url = URL(string: member!.avatarURL!) {
memberView.sd_setImage(with: url)
}
if member!.name != nil && !member!.name!.isEmpty {
memberName.text = member!.name
} else {
memberName.text = member!.email
}
memberName.textColor = MainColor
}
}
}
| gpl-3.0 |
GianniCarlo/Audiobook-Player | BookPlayer/Library/Protocols/ItemListActions.swift | 1 | 1168 | //
// ItemListActions.swift
// BookPlayer
//
// Created by Gianni Carlo on 12/11/18.
// Copyright © 2018 Tortuga Power. All rights reserved.
//
import BookPlayerKit
import UIKit
protocol ItemListActions: ItemList {
func sort(by sortType: PlayListSortOrder)
func delete(_ items: [LibraryItem], mode: DeleteMode) throws
func move(_ items: [LibraryItem], to folder: Folder) throws
}
extension ItemListActions {
func delete(_ items: [LibraryItem], mode: DeleteMode) throws {
try DataManager.delete(items, library: self.library, mode: mode)
self.reloadData()
}
func move(_ items: [LibraryItem], to folder: Folder) throws {
try DataManager.moveItems(items, into: folder)
self.reloadData()
}
func createExportController(_ item: LibraryItem) -> UIViewController? {
guard let book = item as? Book else { return nil }
let bookProvider = BookActivityItemProvider(book)
let shareController = UIActivityViewController(activityItems: [bookProvider], applicationActivities: nil)
shareController.excludedActivityTypes = [.copyToPasteboard]
return shareController
}
}
| gpl-3.0 |
volendavidov/NagBar | NagBar/FilterTableViewDatasource.swift | 1 | 360 | //
// FilterTableViewDatasource.swift
// NagBar
//
// Created by Volen Davidov on 15.01.16.
// Copyright © 2016 Volen Davidov. All rights reserved.
//
import Foundation
import Cocoa
class FilterTableViewDatasource : NSObject, NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return FilterItems().count()
}
}
| apache-2.0 |
robbdimitrov/pixelgram-ios | PixelGram/Classes/Shared/Extensions/ImageNetworking.swift | 1 | 460 | //
// ImageNetworking.swift
// PixelGram
//
// Created by Robert Dimitrov on 10/29/17.
// Copyright © 2017 Robert Dimitrov. All rights reserved.
//
import UIKit
import SDWebImage
extension UIImageView {
func setImage(with url: URL) {
if let manager = SDWebImageManager.shared().imageDownloader {
manager.setValue(Session.shared.token, forHTTPHeaderField: "X-Access-Token")
}
sd_setImage(with: url)
}
}
| mit |
simonbengtsson/realmfire-swift | RealmFire/TypeHandler.swift | 1 | 2506 | import Foundation
import RealmSwift
class TypeHandler {
static var syncTypes = [String: SyncObject.Type]()
static var dataTypes = [String: DataObject.Type]()
static func getSyncType(className: String) -> SyncObject.Type {
if let type = syncTypes[className] {
return type
} else {
fatalError("The type \(className) is not managed by RealmFire")
}
}
static func getType(className: String) -> DataObject.Type? {
return dataTypes[className]
}
static func isSyncType(className: String) -> Bool {
return syncTypes[className] != nil
}
static func isDataType(className: String) -> Bool {
return dataTypes[className] != nil
}
fileprivate static func addSyncType(className: String, type: SyncObject.Type) {
syncTypes[className] = type
}
fileprivate static func addDataType(className: String, type: DataObject.Type) {
dataTypes[className] = type
}
}
extension Object {
/*open override class func initialize() {
super.initialize()
guard self.className() != SyncObject.className() else { return }
// Add all classes that should be observed and synced
//TypeHandler.addSyncType(className: self.className(), type: self)
}*/
}
extension DataObject {
/*open override class func initialize() {
super.initialize()
guard self.className() != DataObject.className() else { return }
guard self.className() != SyncObject.className() else { return }
// Add all classes that should be observed and synced
TypeHandler.addDataType(className: self.className(), type: self)
}*/
}
extension SyncObject {
/*open override class func initialize() {
//super.initialize()
guard self.className() != SyncObject.className() else { return }
// Add all classes that should be observed and synced
TypeHandler.addSyncType(className: self.className(), type: self)
validateClass()
}*/
private class func validateClass() {
if self.primaryKey() == nil {
fatalError("primaryKey() has to be overriden by SyncObject subclasses")
}
if self.collectionName().isEmpty {
fatalError("collectionName cannot be empty")
}
if self.uploadedAtAttribute().isEmpty {
fatalError("uploadedAtAttribute cannot be empty")
}
}
}
| mit |
apple/swift-llbuild | examples/swift-bindings/core/basic.swift | 1 | 2449 | import llbuild
typealias Compute = ([Int]) -> Int
class SimpleTask: Task {
let inputs: [Key]
var values: [Int]
let compute: Compute
init(_ inputs: [Key], compute: @escaping Compute) {
self.inputs = inputs
values = [Int](repeating: 0, count: inputs.count)
self.compute = compute
}
func start(_ engine: TaskBuildEngine) {
for (idx, input) in inputs.enumerated() {
engine.taskNeedsInput(input, inputID: idx)
}
}
func provideValue(_ engine: TaskBuildEngine, inputID: Int, value: Value) {
values[inputID] = Int(value.toString())!
}
func inputsAvailable(_ engine: TaskBuildEngine) {
let result = compute(values)
engine.taskIsComplete(Value("\(result)"), forceChange: false)
}
}
class SimpleBuildEngineDelegate: BuildEngineDelegate {
var builtKeys = [Key]()
func lookupRule(_ key: Key) -> Rule {
switch key.toString() {
case "A":
return SimpleRule([]) { arr in
precondition(self.builtKeys.isEmpty)
self.builtKeys.append(key)
return 2
}
case "B":
return SimpleRule([]) { arr in
precondition(self.builtKeys.count == 1)
self.builtKeys.append(key)
return 3
}
case "C":
return SimpleRule([Key("A"), Key("B")]) { arr in
precondition(self.builtKeys.count == 2)
precondition(self.builtKeys[0].toString() == "A")
precondition(self.builtKeys[1].toString() == "B")
self.builtKeys.append(key)
return arr[0] * arr[1]
}
default: fatalError("Unexpected key \(key) lookup")
}
}
}
class SimpleRule: Rule {
let inputs: [Key]
let compute: Compute
init(_ inputs: [Key], compute: @escaping Compute) {
self.inputs = inputs
self.compute = compute
}
func createTask() -> Task {
return SimpleTask(inputs, compute: compute)
}
}
let delegate = SimpleBuildEngineDelegate()
var engine = BuildEngine(delegate: delegate)
// C depends on A and B
var result = engine.build(key: Key("C"))
print("\(result.toString())")
precondition(result.toString() == "6")
// Make sure building already built keys do not re-compute.
delegate.builtKeys.removeAll()
precondition(delegate.builtKeys.isEmpty)
result = engine.build(key: Key("A"))
precondition(result.toString() == "2")
precondition(delegate.builtKeys.isEmpty)
result = engine.build(key: Key("B"))
precondition(result.toString() == "3")
precondition(delegate.builtKeys.isEmpty)
| apache-2.0 |
ZhiQiang-Yang/pppt | v2exProject 2/Pods/Alamofire/Source/Alamofire.swift | 271 | 12335 | // Alamofire.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 Foundation
// MARK: - URLStringConvertible
/**
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to
construct URL requests.
*/
public protocol URLStringConvertible {
/**
A URL that conforms to RFC 2396.
Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808.
See https://tools.ietf.org/html/rfc2396
See https://tools.ietf.org/html/rfc1738
See https://tools.ietf.org/html/rfc1808
*/
var URLString: String { get }
}
extension String: URLStringConvertible {
public var URLString: String {
return self
}
}
extension NSURL: URLStringConvertible {
public var URLString: String {
return absoluteString
}
}
extension NSURLComponents: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
}
extension NSURLRequest: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
}
// MARK: - URLRequestConvertible
/**
Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
*/
public protocol URLRequestConvertible {
/// The URL request.
var URLRequest: NSMutableURLRequest { get }
}
extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSMutableURLRequest {
return self.mutableCopy() as! NSMutableURLRequest
}
}
// MARK: - Convenience
func URLRequest(
method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil)
-> NSMutableURLRequest
{
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
mutableURLRequest.HTTPMethod = method.rawValue
if let headers = headers {
for (headerField, headerValue) in headers {
mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField)
}
}
return mutableURLRequest
}
// MARK: - Request Methods
/**
Creates a request using the shared manager instance for the specified method, URL string, parameters, and
parameter encoding.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter parameters: The parameters. `nil` by default.
- parameter encoding: The parameter encoding. `.URL` by default.
- parameter headers: The HTTP headers. `nil` by default.
- returns: The created request.
*/
public func request(
method: Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
encoding: ParameterEncoding = .URL,
headers: [String: String]? = nil)
-> Request
{
return Manager.sharedInstance.request(
method,
URLString,
parameters: parameters,
encoding: encoding,
headers: headers
)
}
/**
Creates a request using the shared manager instance for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request
- returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
return Manager.sharedInstance.request(URLRequest.URLRequest)
}
// MARK: - Upload Methods
// MARK: File
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and file.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter file: The file to upload.
- returns: The created upload request.
*/
public func upload(
method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
file: NSURL)
-> Request
{
return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and file.
- parameter URLRequest: The URL request.
- parameter file: The file to upload.
- returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(URLRequest, file: file)
}
// MARK: Data
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and data.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter data: The data to upload.
- returns: The created upload request.
*/
public func upload(
method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
data: NSData)
-> Request
{
return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and data.
- parameter URLRequest: The URL request.
- parameter data: The data to upload.
- returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(URLRequest, data: data)
}
// MARK: Stream
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter stream: The stream to upload.
- returns: The created upload request.
*/
public func upload(
method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
stream: NSInputStream)
-> Request
{
return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and stream.
- parameter URLRequest: The URL request.
- parameter stream: The stream to upload.
- returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(URLRequest, stream: stream)
}
// MARK: MultipartFormData
/**
Creates an upload request using the shared manager instance for the specified method and URL string.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
`MultipartFormDataEncodingMemoryThreshold` by default.
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
*/
public func upload(
method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
multipartFormData: MultipartFormData -> Void,
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)
{
return Manager.sharedInstance.upload(
method,
URLString,
headers: headers,
multipartFormData: multipartFormData,
encodingMemoryThreshold: encodingMemoryThreshold,
encodingCompletion: encodingCompletion
)
}
/**
Creates an upload request using the shared manager instance for the specified method and URL string.
- parameter URLRequest: The URL request.
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
`MultipartFormDataEncodingMemoryThreshold` by default.
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
*/
public func upload(
URLRequest: URLRequestConvertible,
multipartFormData: MultipartFormData -> Void,
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)
{
return Manager.sharedInstance.upload(
URLRequest,
multipartFormData: multipartFormData,
encodingMemoryThreshold: encodingMemoryThreshold,
encodingCompletion: encodingCompletion
)
}
// MARK: - Download Methods
// MARK: URL Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter parameters: The parameters. `nil` by default.
- parameter encoding: The parameter encoding. `.URL` by default.
- parameter headers: The HTTP headers. `nil` by default.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The created download request.
*/
public func download(
method: Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
encoding: ParameterEncoding = .URL,
headers: [String: String]? = nil,
destination: Request.DownloadFileDestination)
-> Request
{
return Manager.sharedInstance.download(
method,
URLString,
parameters: parameters,
encoding: encoding,
headers: headers,
destination: destination
)
}
/**
Creates a download request using the shared manager instance for the specified URL request.
- parameter URLRequest: The URL request.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(URLRequest, destination: destination)
}
// MARK: Resume Data
/**
Creates a request using the shared manager instance for downloading from the resume data produced from a
previous request cancellation.
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional
information.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The created download request.
*/
public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(data, destination: destination)
}
| apache-2.0 |
hacktoolkit/hacktoolkit-ios_lib | Hacktoolkit/dataStructures/DataStructures.swift | 1 | 635 | //
// DataStructures.swift
//
// Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai)
// Copyright (c) 2014 Hacktoolkit. All rights reserved.
//
import Foundation
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
func peek() -> T? {
return items.last
}
}
struct Queue<T> {
var items = [T]()
mutating func enqueue(item: T) {
items.append(item)
}
mutating func dequeue() -> T {
return items.removeAtIndex(0)
}
}
| mit |
mathmatrix828/WeatherIcons_swift | WeatherIcons_swift/Classes/WeatherIconsEnum.swift | 1 | 8157 | //
// WeatherIconsEnum.swift
// WeatherIconsEnum
// Pods
//
// Created by Mason Phillips on 4May16.
//
//
public enum WeatherIcons: String {
case day_sunny = "\u{00d}"
case day_cloudy = "\u{002}"
case day_cloudy_gusts = "\u{000}"
case day_cloudy_windy = "\u{001}"
case day_fog = "\u{003}"
case day_hail = "\u{004}"
case day_haze = "\u{0b6}"
case day_lightning = "\u{005}"
case day_rain = "\u{008}"
case day_rain_mix = "\u{006}"
case day_rain_wind = "\u{007}"
case day_showers = "\u{009}"
case day_sleet = "\u{0b2}"
case day_sleet_storm = "\u{068}"
case day_snow = "\u{00a}"
case day_snow_thunderstorm = "\u{06b}"
case day_snow_wind = "\u{065}"
case day_sprinkle = "\u{00b}"
case day_storm_showers = "\u{00e}"
case day_sunny_overcast = "\u{00c}"
case day_thunderstorm = "\u{010}"
case day_windy = "\u{085}"
case solar_eclipse = "\u{06e}"
case hot = "\u{072}"
case day_cloudy_high = "\u{07d}"
case day_light_wind = "\u{0c4}"
case night_clear = "\u{02e}"
case night_alt_cloudy = "\u{086}"
case night_alt_cloudy_gusts = "\u{022}"
case night_alt_cloudy_windy = "\u{023}"
case night_alt_hail = "\u{024}"
case night_alt_lightning = "\u{025}"
case night_alt_rain = "\u{028}"
case night_alt_rain_mix = "\u{026}"
case night_alt_rain_wind = "\u{027}"
case night_alt_showers = "\u{029}"
case night_alt_sleet = "\u{0b4}"
case night_alt_sleet_storm = "\u{06a}"
case night_alt_snow = "\u{02a}"
case night_alt_snow_thunderstorm = "\u{06d}"
case night_alt_snow_wind = "\u{067}"
case night_alt_sprinkle = "\u{02b}"
case night_alt_storm_showers = "\u{02c}"
case night_alt_thunderstorm = "\u{02d}"
case night_cloudy = "\u{031}"
case night_cloudy_gusts = "\u{02f}"
case night_cloudy_windy = "\u{030}"
case night_fog = "\u{04a}"
case night_hail = "\u{032}"
case night_lightning = "\u{033}"
case night_partly_cloudy = "\u{083}"
case night_rain = "\u{036}"
case night_rain_mix = "\u{034}"
case night_rain_wind = "\u{035}"
case night_showers = "\u{037}"
case night_sleet = "\u{0b3}"
case night_sleet_storm = "\u{069}"
case night_snow = "\u{038}"
case night_snow_thunderstorm = "\u{06c}"
case night_snow_wind = "\u{066}"
case night_sprinkle = "\u{039}"
case night_storm_showers = "\u{03a}"
case night_thunderstorm = "\u{03b}"
case lunar_eclipse = "\u{070}"
case stars = "\u{077}"
case storm_showers = "\u{01d}"
case thunderstorm = "\u{01e}"
case night_alt_cloudy_high = "\u{07e}"
case night_cloudy_high = "\u{080}"
case night_alt_partly_cloudy = "\u{081}"
case cloud = "\u{041}"
case cloudy = "\u{013}"
case cloudy_gusts = "\u{011}"
case cloudy_windy = "\u{012}"
case fog = "\u{014}"
case hail = "\u{015}"
case rain = "\u{019}"
case rain_mix = "\u{017}"
case rain_wind = "\u{018}"
case showers = "\u{01a}"
case sleet = "\u{0b5}"
case snow = "\u{01b}"
case sprinkle = "\u{01c}"
case snow_wind = "\u{064}"
case smog = "\u{074}"
case smoke = "\u{062}"
case lightning = "\u{016}"
case raindrops = "\u{04e}"
case raindrop = "\u{078}"
case dust = "\u{063}"
case snowflake_cold = "\u{076}"
case windy = "\u{021}"
case strong_wind = "\u{050}"
case sandstorm = "\u{082}"
case earthquake = "\u{0c6}"
case fire = "\u{0c7}"
case flood = "\u{07c}"
case meteor = "\u{071}"
case tsunami = "\u{0c5}"
case volcano = "\u{0c8}"
case hurricane = "\u{073}"
case tornado = "\u{056}"
case small_craft_advisory = "\u{0cc}"
case gale_warning = "\u{0cd}"
case storm_warning = "\u{0ce}"
case hurricane_warning = "\u{0cf}"
case wind_direction = "\u{0b1}"
case alien = "\u{075}"
case celsius = "\u{03c}"
case fahrenheit = "\u{045}"
case degrees = "\u{042}"
case thermometer = "\u{055}"
case thermometer_exterior = "\u{053}"
case thermometer_internal = "\u{054}"
case cloud_down = "\u{03d}"
case cloud_up = "\u{040}"
case cloud_refresh = "\u{03e}"
case horizon = "\u{047}"
case horizon_alt = "\u{046}"
case sunrise = "\u{051}"
case sunset = "\u{052}"
case moonrise = "\u{0c9}"
case moonset = "\u{0ca}"
case refresh = "\u{04c}"
case refresh_alt = "\u{04b}"
case umbrella = "\u{084}"
case barometer = "\u{079}"
case humidity = "\u{07a}"
case na = "\u{07b}"
case train = "\u{0cb}"
case moon_new = "\u{095}"
case moon_waxing_crescent_1 = "\u{096}"
case moon_waxing_crescent_2 = "\u{097}"
case moon_waxing_crescent_3 = "\u{098}"
case moon_waxing_crescent_4 = "\u{099}"
case moon_waxing_crescent_5 = "\u{09a}"
case moon_waxing_crescent_6 = "\u{09b}"
case moon_first_quarter = "\u{09c}"
case moon_waxing_gibbous_1 = "\u{09d}"
case moon_waxing_gibbous_2 = "\u{09e}"
case moon_waxing_gibbous_3 = "\u{09f}"
case moon_waxing_gibbous_4 = "\u{0a0}"
case moon_waxing_gibbous_5 = "\u{0a1}"
case moon_waxing_gibbous_6 = "\u{0a2}"
case moon_full = "\u{0a3}"
case moon_waning_gibbous_1 = "\u{0a4}"
case moon_waning_gibbous_2 = "\u{0a5}"
case moon_waning_gibbous_3 = "\u{0a6}"
case moon_waning_gibbous_4 = "\u{0a7}"
case moon_waning_gibbous_5 = "\u{0a8}"
case moon_waning_gibbous_6 = "\u{0a9}"
case moon_third_quarter = "\u{0aa}"
case moon_waning_crescent_1 = "\u{0ab}"
case moon_waning_crescent_2 = "\u{0ac}"
case moon_waning_crescent_3 = "\u{0ad}"
case moon_waning_crescent_4 = "\u{0ae}"
case moon_waning_crescent_5 = "\u{0af}"
case moon_waning_crescent_6 = "\u{0b0}"
case moon_alt_new = "\u{0eb}"
case moon_alt_waxing_crescent_1 = "\u{0d0}"
case moon_alt_waxing_crescent_2 = "\u{0d1}"
case moon_alt_waxing_crescent_3 = "\u{0d2}"
case moon_alt_waxing_crescent_4 = "\u{0d3}"
case moon_alt_waxing_crescent_5 = "\u{0d4}"
case moon_alt_waxing_crescent_6 = "\u{0d5}"
case moon_alt_first_quarter = "\u{0d6}"
case moon_alt_waxing_gibbous_1 = "\u{0d7}"
case moon_alt_waxing_gibbous_2 = "\u{0d8}"
case moon_alt_waxing_gibbous_3 = "\u{0d9}"
case moon_alt_waxing_gibbous_4 = "\u{0da}"
case moon_alt_waxing_gibbous_5 = "\u{0db}"
case moon_alt_waxing_gibbous_6 = "\u{0dc}"
case moon_alt_full = "\u{0dd}"
case moon_alt_waning_gibbous_1 = "\u{0de}"
case moon_alt_waning_gibbous_2 = "\u{0df}"
case moon_alt_waning_gibbous_3 = "\u{0e0}"
case moon_alt_waning_gibbous_4 = "\u{0e1}"
case moon_alt_waning_gibbous_5 = "\u{0e2}"
case moon_alt_waning_gibbous_6 = "\u{0e3}"
case moon_alt_third_quarter = "\u{0e4}"
case moon_alt_waning_crescent_1 = "\u{0e5}"
case moon_alt_waning_crescent_2 = "\u{0e6}"
case moon_alt_waning_crescent_3 = "\u{0e7}"
case moon_alt_waning_crescent_4 = "\u{0e8}"
case moon_alt_waning_crescent_5 = "\u{0e9}"
case moon_alt_waning_crescent_6 = "\u{0ea}"
case time_1 = "\u{08a}"
case time_2 = "\u{08b}"
case time_3 = "\u{08c}"
case time_4 = "\u{08d}"
case time_5 = "\u{08e}"
case time_6 = "\u{08f}"
case time_7 = "\u{090}"
case time_8 = "\u{091}"
case time_9 = "\u{092}"
case time_10 = "\u{093}"
case time_11 = "\u{094}"
case time_12 = "\u{089}"
case direction_up = "\u{058}"
case direction_up_right = "\u{057}"
case direction_right = "\u{04d}"
case direction_down_right = "\u{088}"
case direction_down = "\u{044}"
case direction_down_left = "\u{043}"
case direction_left = "\u{048}"
case direction_up_left = "\u{087}"
case wind_beaufort_0 = "\u{0b7}"
case wind_beaufort_1 = "\u{0b8}"
case wind_beaufort_2 = "\u{0b9}"
case wind_beaufort_3 = "\u{0ba}"
case wind_beaufort_4 = "\u{0bb}"
case wind_beaufort_5 = "\u{0bc}"
case wind_beaufort_6 = "\u{0bd}"
case wind_beaufort_7 = "\u{0be}"
case wind_beaufort_8 = "\u{0bf}"
case wind_beaufort_9 = "\u{0c0}"
case wind_beaufort_10 = "\u{0c1}"
case wind_beaufort_11 = "\u{0c2}"
case wind_beaufort_12 = "\u{0c3}"
} | mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/15893-swift-sourcemanager-getmessage.swift | 11 | 228 | // 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 g {
n(
let {
struct A {
let a {
enum A {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/16538-no-stacktrace.swift | 11 | 228 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct c
{
var b = [ {
func a {
let a {
for {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/11927-swift-inflightdiagnostic.swift | 11 | 245 | // 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 < {
{
case
{
class A {
class
case ,
let start ( ) {
{
( {
{
{
{
{
: A"
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.