repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gtranchedone/NFYU | refs/heads/master | NFYU/Services/APIClient.swift | mit | 1 | //
// APIClient.swift
// NFYU
//
// Created by Gianluca Tranchedone on 05/11/2015.
// Copyright © 2015 Gianluca Tranchedone. All rights reserved.
//
import Foundation
import CoreLocation
protocol APIRequestSerializer {
func buildURLRequestToFetchForecastsForLocationWithCoordinate(_ coordinate: CLLocationCoordinate2D) -> URLRequest
}
typealias SerializedAPIResponse = (error: NSError?, forecasts: [Forecast]?, locationInfo: LocationInfo?)
protocol APIResponseSerializer {
func parseForecastsAPIResponseData(_ data: Data) -> SerializedAPIResponse
}
class APIClient: AnyObject {
var session = URLSession.shared
let requestSerializer: APIRequestSerializer
let responseSerializer: APIResponseSerializer
init(requestSerializer: APIRequestSerializer, responseSerializer: APIResponseSerializer) {
self.requestSerializer = requestSerializer
self.responseSerializer = responseSerializer
}
// The completion block is always called on the main queue
func fetchForecastsForLocationWithCoordinate(_ coordinate: CLLocationCoordinate2D, completionBlock: @escaping (NSError?, [Forecast]?, LocationInfo?) -> ()) {
let request = requestSerializer.buildURLRequestToFetchForecastsForLocationWithCoordinate(coordinate)
let task = session.dataTask(with: request, completionHandler: { [weak self] (data, response, error) -> Void in
var locationInfo: LocationInfo?
var forecasts: [Forecast]?
var finalError = error
if let data = data {
let parsedResponse = self?.responseSerializer.parseForecastsAPIResponseData(data)
locationInfo = parsedResponse?.locationInfo
forecasts = parsedResponse?.forecasts
finalError = parsedResponse?.error
}
self?.logResponse(response, error: finalError as NSError?, forecasts: forecasts, locationInfo: locationInfo)
OperationQueue.main.addOperation({ () -> Void in
completionBlock(finalError as NSError?, forecasts, locationInfo)
})
})
logRequest(request)
task.resume()
}
fileprivate func logRequest(_ request: URLRequest) {
// use print instead of debugPrint for pretty printing
print("Performing \(request.httpMethod!) request to \(request.url!)", terminator: "\n\n")
}
fileprivate func logResponse(_ response: URLResponse?, error: NSError?, forecasts: [Forecast]?, locationInfo: LocationInfo?) {
// use print instead of debugPrint for pretty printing
print("Received response for URL \(response?.url) with error -> \(error)\nlocationInfo -> \(locationInfo)\nforecasts -> \(forecasts)", terminator: "\n\n")
}
}
| 21957d180f98d7e6f84bba020214c5f6 | 39.57971 | 162 | 0.69 | false | false | false | false |
CJGitH/QQMusic | refs/heads/master | QQMusic/Classes/Other/Tool/QQTimeTool.swift | mit | 1 | //
// QQTimeTool.swift
// QQMusic
//
// Created by chen on 16/5/17.
// Copyright © 2016年 chen. All rights reserved.
//
import UIKit
class QQTimeTool: NSObject {
class func getFormatTime(time: NSTimeInterval) -> String {
// time 123
// 03:12
let min = Int(time / 60)
let sec = Int(time) % 60
let resultStr = String(format: "%02d:%02d", min, sec)
return resultStr
}
class func getTimeInterval(formatTime: String) -> NSTimeInterval {
// 00:00.89 -> 多少秒
let minAndSec = formatTime.componentsSeparatedByString(":")
if minAndSec.count == 2 {
// 分钟
let min = NSTimeInterval(minAndSec[0]) ?? 0
// 秒数
let sec = NSTimeInterval(minAndSec[1]) ?? 0
return min * 60 + sec
}
return 0
}
}
| 96c9a830db6aea6419380ddc79d6a97a | 18.215686 | 70 | 0.47449 | false | false | false | false |
tbergmen/TableViewModel | refs/heads/master | Example/TableViewModel/FeedExample/FeedCell.swift | mit | 1 | /*
Copyright (c) 2016 Tunca Bergmen <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
import UIKit
class FeedCell: UITableViewCell {
@IBOutlet var profileImageView: UIImageView!
@IBOutlet var nameLabel: UILabel!
@IBOutlet var timeLabel: UILabel!
@IBOutlet var commentTextView: UITextView!
@IBOutlet var likeButton: UIButton!
@IBOutlet var shareButton: UIButton!
var cellHeight: Float = 0
var onLike: ((FeedItem) -> ())?
var onShare: ((FeedItem) -> ())?
override func awakeFromNib() {
profileImageView.layer.cornerRadius = 4
}
@IBAction func likeAction() {
onLike?(feedItem)
}
@IBAction func shareAction() {
onShare?(feedItem)
}
var feedItem: FeedItem! {
didSet {
nameLabel.text = feedItem.user.name
profileImageView.image = feedItem.user.profilePicture
timeLabel.text = feedItem.time
commentTextView.text = feedItem.comment
calculateCellHeight()
}
}
func calculateCellHeight() {
if let feedItem = self.feedItem {
let baseHeight: Float = 70
let commentViewHeight = textViewHeight(feedItem.comment, width: 256, font: UIFont.systemFontOfSize(13))
cellHeight = baseHeight + commentViewHeight
}
}
func textViewHeight(text: String, width: Float, font: UIFont) -> Float {
let attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName: font])
let textViewMargin: Float = 10
let size = attributedText.boundingRectWithSize(CGSizeMake(CGFloat(width - textViewMargin), CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
context: nil)
return Float(size.height)
}
}
| 7b49373e6a3529ca33b4a499dded2df7 | 34.734177 | 115 | 0.704215 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | refs/heads/main | PayTests/Mocks/MockPayment.swift | mit | 1 | //
// MockPayment.swift
// PayTests
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if canImport(PassKit)
import Foundation
import PassKit
class MockPayment: PKPayment {
override var token: PKPaymentToken {
return self._token
}
override var billingContact: PKContact? {
return self._billingContact
}
override var shippingContact: PKContact? {
return self._shippingContact
}
override var shippingMethod: PKShippingMethod? {
return self._shippingMethod
}
let _token: MockPaymentToken
let _billingContact: PKContact?
let _shippingContact: PKContact?
let _shippingMethod: PKShippingMethod?
// ----------------------------------
// MARK: - Init -
//
init(token: MockPaymentToken, billingContact: PKContact? = nil, shippingContact: PKContact? = nil, shippingMethod: PKShippingMethod? = nil) {
self._token = token
self._billingContact = billingContact
self._shippingContact = shippingContact
self._shippingMethod = shippingMethod
}
}
#endif
| 7c520cc9b2fec2ddd6bf8786b2321d7e | 33.19697 | 145 | 0.688082 | false | false | false | false |
Sahilberi/ImageTextField | refs/heads/master | Source/ImageTextField.swift | mit | 1 | //
// ImageTextField.swift
// ImageTextField
//
// Created by Sahil on 22/02/17.
// Copyright © 2017 SahilBeri. All rights reserved.
//
import UIKit
@IBDesignable
class ImageTextField: UITextField {
var textFieldBorderStyle: UITextBorderStyle = .roundedRect
// Provides left padding for image
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.leftViewRect(forBounds: bounds)
textRect.origin.x += padding
return textRect
}
// Provides right padding for image
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.rightViewRect(forBounds: bounds)
textRect.origin.x -= padding
return textRect
}
@IBInspectable var fieldImage: UIImage? = nil {
didSet {
updateView()
}
}
@IBInspectable var padding: CGFloat = 0
@IBInspectable var color: UIColor = UIColor.gray {
didSet {
updateView()
}
}
@IBInspectable var bottomColor: UIColor = UIColor.clear {
didSet {
if bottomColor == UIColor.clear {
self.borderStyle = .roundedRect
} else {
self.borderStyle = .bezel
}
self.setNeedsDisplay()
}
}
func updateView() {
if let image = fieldImage {
leftViewMode = UITextFieldViewMode.always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
imageView.image = image
// Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
imageView.tintColor = color
leftView = imageView
} else {
leftViewMode = UITextFieldViewMode.never
leftView = nil
}
// Placeholder text color
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSForegroundColorAttributeName: color])
}
override func draw(_ rect: CGRect) {
let path = UIBezierPath()
path.move(to: CGPoint(x: self.bounds.origin.x, y: self.bounds.height
- 0.5))
path.addLine(to: CGPoint(x: self.bounds.size.width, y: self.bounds.height
- 0.5))
path.lineWidth = 0.5
self.bottomColor.setStroke()
path.stroke()
}
}
| 273f6b526f087a3a764bfc620b36a047 | 26.790123 | 170 | 0.666371 | false | false | false | false |
AgaKhanFoundation/WCF-iOS | refs/heads/main | Demo/Pods/Nimble/Sources/Nimble/Expectation.swift | bsd-3-clause | 2 | internal func execute<T>(_ expression: Expression<T>, _ style: ExpectationStyle, _ predicate: Predicate<T>, to: String, description: String?, captureExceptions: Bool = true) -> (Bool, FailureMessage) {
func run() -> (Bool, FailureMessage) {
let msg = FailureMessage()
msg.userDescription = description
msg.to = to
do {
let result = try predicate.satisfies(expression)
result.message.update(failureMessage: msg)
if msg.actualValue == "" {
msg.actualValue = "<\(stringify(try expression.evaluate()))>"
}
return (result.toBoolean(expectation: style), msg)
} catch let error {
msg.stringValue = "unexpected error thrown: <\(error)>"
return (false, msg)
}
}
var result: (Bool, FailureMessage) = (false, FailureMessage())
if captureExceptions {
let capture = NMBExceptionCapture(handler: ({ exception -> Void in
let msg = FailureMessage()
msg.stringValue = "unexpected exception raised: \(exception)"
result = (false, msg)
}), finally: nil)
capture.tryBlock {
result = run()
}
} else {
result = run()
}
return result
}
public struct Expectation<T> {
public let expression: Expression<T>
public init(expression: Expression<T>) {
self.expression = expression
}
public func verify(_ pass: Bool, _ message: FailureMessage) {
let handler = NimbleEnvironment.activeInstance.assertionHandler
handler.assert(pass, message: message, location: expression.location)
}
/// Tests the actual value using a matcher to match.
@discardableResult
public func to(_ predicate: Predicate<T>, description: String? = nil) -> Self {
let (pass, msg) = execute(expression, .toMatch, predicate, to: "to", description: description)
verify(pass, msg)
return self
}
/// Tests the actual value using a matcher to not match.
@discardableResult
public func toNot(_ predicate: Predicate<T>, description: String? = nil) -> Self {
let (pass, msg) = execute(expression, .toNotMatch, predicate, to: "to not", description: description)
verify(pass, msg)
return self
}
/// Tests the actual value using a matcher to not match.
///
/// Alias to toNot().
@discardableResult
public func notTo(_ predicate: Predicate<T>, description: String? = nil) -> Self {
return toNot(predicate, description: description)
}
// see:
// - `async` for extension
// - NMBExpectation for Objective-C interface
}
| 85c1639a9993e310a834264ebfb845ff | 34.328947 | 201 | 0.612663 | false | false | false | false |
immustard/MSTTools_Swift | refs/heads/master | MSTTools_Swift/Categories/UILabelMST.swift | mit | 1 | //
// UILabelMST.swift
// MSTTools_Swift
//
// Created by 张宇豪 on 2017/6/7.
// Copyright © 2017年 张宇豪. All rights reserved.
//
import UIKit
extension UILabel {
public func mst_addLongPressCopyMenu() {
isUserInteractionEnabled = true
let longPress: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(mp_showCopyMenu))
addGestureRecognizer(longPress)
}
@objc private func mp_showCopyMenu() {
becomeFirstResponder()
UIMenuController.shared.setTargetRect(frame, in: superview!)
UIMenuController.shared.setMenuVisible(self.isFirstResponder, animated: true)
}
open override var canBecomeFocused: Bool {
return true
}
// 可以响应的方法
open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(UIResponderStandardEditActions.copy(_:))
}
// 针对于响应方法的实现
open override func copy(_ sender: Any?) {
UIPasteboard.general.string = text
}
}
| cafcd28423995d81b27781dcbe59f20e | 26.717949 | 132 | 0.66235 | false | false | false | false |
coach-plus/ios | refs/heads/master | CoachPlus/helperclasses/DropdownAlert.swift | mit | 1 | //
// DropdownAlert.swift
// CoachPlus
//
// Created by Breit, Maurice on 26.03.17.
// Copyright © 2017 Mathandoro GbR. All rights reserved.
//
import Foundation
import NotificationBannerSwift
class DropdownAlert {
static let errorBgColor = UIColor.red
static let errorTextColor = UIColor.white
static let errorTitle = L10n.error
static let errorTime = 3
static let successTitle = L10n.success
static func error(message: String) {
let msg = message.localize()
let banner = NotificationBanner(title: self.errorTitle, subtitle: msg, style: .danger)
banner.show()
}
static func success(message: String) {
let banner = NotificationBanner(title: self.successTitle, subtitle: message, style: .success)
banner.show()
}
}
| 693113f2a95dce3c8d116e7dc597da1e | 24.030303 | 101 | 0.664649 | false | false | false | false |
vnu/Flickz | refs/heads/master | Flickz/Movie.swift | mit | 1 | //
// Movie.swift
// Flickz
//
// Created by Vinu Charanya on 2/5/16.
// Copyright © 2016 vnu. All rights reserved.
//
import UIKit
/* Sample Data
{
poster_path: "/k1QUCjNAkfRpWfm1dVJGUmVHzGv.jpg",
adult: false,
overview: "Based upon Marvel Comics’ most unconventional anti-hero, DEADPOOL tells the origin story of former Special Forces operative turned mercenary Wade Wilson, who after being subjected to a rogue experiment that leaves him with accelerated healing powers, adopts the alter ego Deadpool. Armed with his new abilities and a dark, twisted sense of humor, Deadpool hunts down the man who nearly destroyed his life.",
release_date: "2016-02-09",
genre_ids: [
35,
12,
28,
878
],
id: 293660,
original_title: "Deadpool",
original_language: "en",
title: "Deadpool",
backdrop_path: "/n1y094tVDFATSzkTnFxoGZ1qNsG.jpg",
popularity: 20.322214,
vote_count: 131,
video: false,
vote_average: 6.05
}
*/
import Foundation
import UIKit
class Movie {
// MARK: Properties
var posterPath: String?
var adult: Bool
var overview: String
var releaseDate: String
var genreIds: Array<Int>
var ID: Int
var originalTitle: String
var originalLanguage: String
var title: String
var backdropPath: String?
var popularity: Double
var voteCount: Int
var video: Bool
var voteAverage: Double
// MARK: Initialization
init(posterPath: String, adult: Bool, overview: String, releaseDate: String, genreIds: Array<Int>, ID: Int, originalTitle: String, originalLanguage: String, title: String, backdropPath: String, popularity: Double, voteCount: Int, video: Bool, voteAverage: Double) {
// Initialize stored properties.
self.posterPath = posterPath
self.adult = adult
self.overview = overview
self.releaseDate = releaseDate
self.genreIds = genreIds
self.ID = ID
self.originalTitle = originalTitle
self.originalLanguage = originalLanguage
self.title = title
self.backdropPath = backdropPath
self.popularity = popularity
self.voteCount = voteCount
self.video = video
self.voteAverage = voteAverage
}
init(jsonResult: NSDictionary) {
// Initialize stored properties.
self.posterPath = jsonResult["poster_path"] as? String
self.adult = jsonResult["adult"] as! Bool
self.overview = jsonResult["overview"] as! String
self.releaseDate = jsonResult["release_date"] as! String
self.genreIds = jsonResult["genre_ids"] as! Array<Int>
self.ID = jsonResult["id"] as! Int
self.originalTitle = jsonResult["original_title"] as! String
self.originalLanguage = jsonResult["original_language"] as! String
self.title = jsonResult["title"] as! String
self.backdropPath = jsonResult["backdrop_path"] as? String
self.popularity = jsonResult["popularity"] as! Double
self.voteCount = jsonResult["vote_count"] as! Int
self.video = jsonResult["video"] as! Bool
self.voteAverage = jsonResult["vote_average"] as! Double
}
func lowResPosterURL() -> NSURL?{
let baseUrl = "https://image.tmdb.org/t/p/w92"
if let posterPath = self.posterPath{
return NSURL(string:"\(baseUrl)\(posterPath)")!
}
return nil
}
func highResPosterURL() -> NSURL?{
let baseUrl = "https://image.tmdb.org/t/p/original"
if let posterPath = self.posterPath{
return NSURL(string:"\(baseUrl)\(posterPath)")!
}
return nil
}
func movieReleaseDate() -> String{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let movieDate = dateFormatter.dateFromString(self.releaseDate) {
dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
return dateFormatter.stringFromDate(movieDate)
}
return "--"
}
}
| 6a73ff00398cea76d0ee8e2e89eaac77 | 30.88 | 418 | 0.661731 | false | false | false | false |
material-components/material-components-ios | refs/heads/develop | components/AppBar/tests/unit/AppBarNavigationControllerTests.swift | apache-2.0 | 2 | // Copyright 2018-present the Material Components for iOS 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.
import XCTest
import MaterialComponents.MaterialAppBar
private class MockAppBarNavigationControllerDelegate:
NSObject, MDCAppBarNavigationControllerDelegate
{
var trackingScrollView: UIScrollView?
func appBarNavigationController(
_ navigationController: MDCAppBarNavigationController,
trackingScrollViewFor trackingScrollViewForViewController: UIViewController,
suggestedTrackingScrollView: UIScrollView?
) -> UIScrollView? {
return trackingScrollView
}
}
class AppBarNavigationControllerTests: XCTestCase {
var navigationController: MDCAppBarNavigationController!
override func setUp() {
super.setUp()
navigationController = MDCAppBarNavigationController()
}
override func tearDown() {
navigationController = nil
super.tearDown()
}
// MARK: - AppBar injection
func testInitializingWithRootViewControllerInjectsAnAppBar() {
// Given
let viewController = UIViewController()
// When
let navigationController = MDCAppBarNavigationController(rootViewController: viewController)
// Then
XCTAssertEqual(
viewController.children.count, 1,
"Expected there to be exactly one child view controller added to the view"
+ " controller.")
XCTAssertEqual(
navigationController.topViewController, viewController,
"The navigation controller's top view controller is supposed to be the pushed"
+ " view controller, but it is \(viewController).")
XCTAssertTrue(
viewController.children.first is MDCFlexibleHeaderViewController,
"The injected view controller is not a flexible header view controller, it is"
+ "\(String(describing: viewController.children.first)) instead.")
if let headerViewController = viewController.children.first as? MDCFlexibleHeaderViewController
{
XCTAssertEqual(
headerViewController.headerView.frame.height,
headerViewController.headerView.maximumHeight)
}
}
func testPushingAViewControllerInjectsAnAppBar() {
// Given
let viewController = UIViewController()
// When
navigationController.pushViewController(viewController, animated: false)
// Then
XCTAssertEqual(
viewController.children.count, 1,
"Expected there to be exactly one child view controller added to the view"
+ " controller.")
XCTAssertEqual(
navigationController.topViewController, viewController,
"The navigation controller's top view controller is supposed to be the pushed"
+ " view controller, but it is \(viewController).")
XCTAssertTrue(
viewController.children.first is MDCFlexibleHeaderViewController,
"The injected view controller is not a flexible header view controller, it is"
+ "\(String(describing: viewController.children.first)) instead.")
if let headerViewController = viewController.children.first as? MDCFlexibleHeaderViewController
{
XCTAssertEqual(
headerViewController.headerView.frame.height,
headerViewController.headerView.maximumHeight)
}
}
func testPushingAnAppBarContainerViewControllerDoesNotInjectAnAppBar() {
// Given
let viewController = UIViewController()
let container = MDCAppBarContainerViewController(contentViewController: viewController)
// When
navigationController.pushViewController(container, animated: false)
// Then
XCTAssertEqual(
container.children.count, 2,
"An App Bar container view controller should have exactly two child view"
+ " controllers. A failure of this assertion implies that the navigation"
+ " controller may have injected another App Bar.")
}
func testPushingAContainedAppBarContainerViewControllerDoesNotInjectAnAppBar() {
// Given
let viewController = UIViewController()
let container = MDCAppBarContainerViewController(contentViewController: viewController)
let nestedContainer = UIViewController()
nestedContainer.addChild(container)
nestedContainer.view.addSubview(container.view)
container.didMove(toParent: nestedContainer)
// When
navigationController.pushViewController(nestedContainer, animated: false)
// Then
XCTAssertEqual(
nestedContainer.children.count, 1,
"The view controller hierarchy already has one app bar view controller, but it"
+ " appears to have possibly added another.")
}
func testPushingAViewControllerWithAFlexibleHeaderDoesNotInjectAnAppBar() {
// Given
let viewController = UIViewController()
let fhvc = MDCFlexibleHeaderViewController()
viewController.addChild(fhvc)
viewController.view.addSubview(fhvc.view)
fhvc.didMove(toParent: viewController)
// When
navigationController.pushViewController(viewController, animated: false)
// Then
XCTAssertEqual(
viewController.children.count, 1,
"The navigation controller may have injected another App Bar when it shouldn't"
+ " have.")
}
// MARK: - traitCollectionDidChangeBlock support
func testInitializingWithRootViewControllerDoesNotSetTraitCollectionDidChangeBlock() {
// Given
let viewController = UIViewController()
// When
let _ = MDCAppBarNavigationController(rootViewController: viewController)
// Then
let injectedAppBarViewController = viewController.children.first as! MDCAppBarViewController
XCTAssertNotNil(injectedAppBarViewController)
XCTAssertNil(injectedAppBarViewController.traitCollectionDidChangeBlock)
}
func testPushingAViewControllerAssignsTraitCollectionDidChangeBlock() {
// Given
let viewController = UIViewController()
let block: ((MDCFlexibleHeaderViewController, UITraitCollection?) -> Void)? = { _, _ in }
navigationController.traitCollectionDidChangeBlockForAppBarController = block
// When
navigationController.pushViewController(viewController, animated: false)
// Then
let injectedAppBarViewController = viewController.children.first as! MDCAppBarViewController
XCTAssertNotNil(injectedAppBarViewController)
XCTAssertNotNil(injectedAppBarViewController.traitCollectionDidChangeBlock)
}
func testPushingAnAppBarContainerViewControllerDoesNotAssignTraitCollectionDidChangeBlock() {
// Given
let viewController = UIViewController()
let container = MDCAppBarContainerViewController(contentViewController: viewController)
var blockSemaphore = false
let block: ((MDCFlexibleHeaderViewController, UITraitCollection?) -> Void)? =
{ _, _ in
blockSemaphore = true
}
container.appBarViewController.traitCollectionDidChangeBlock = block
// When
navigationController.pushViewController(container, animated: false)
container.appBarViewController.traitCollectionDidChange(nil)
// Then
XCTAssertTrue(blockSemaphore)
}
func
testPushingAContainedAppBarContainerViewControllerDoesNotAssignTraitCollectionDidChangeBlock()
{
// Given
let viewController = UIViewController()
let container = MDCAppBarContainerViewController(contentViewController: viewController)
let nestedContainer = UIViewController()
nestedContainer.addChild(container)
nestedContainer.view.addSubview(container.view)
container.didMove(toParent: nestedContainer)
var blockSemaphore = false
let block: ((MDCFlexibleHeaderViewController, UITraitCollection?) -> Void)? =
{ _, _ in
blockSemaphore = true
}
container.appBarViewController.traitCollectionDidChangeBlock = block
// When
navigationController.pushViewController(nestedContainer, animated: false)
container.appBarViewController.traitCollectionDidChange(nil)
// Then
XCTAssertTrue(blockSemaphore)
}
// MARK: - The rest
func testStatusBarStyleIsFetchedFromFlexibleHeaderViewController() {
// Given
let viewController = UIViewController()
// When
navigationController.pushViewController(viewController, animated: false)
// Then
let appBar = navigationController.appBar(for: viewController)
XCTAssertNotNil(appBar, "Could not retrieve the injected App Bar.")
if let appBar = appBar {
XCTAssertEqual(
navigationController.childForStatusBarStyle,
appBar.headerViewController,
"The navigation controller should be using the injected app bar's flexible"
+ "header view controller for status bar style updates.")
}
}
func testInfersFirstTrackingScrollViewByDefault() {
// Given
let viewController = UIViewController()
let scrollView1 = UIScrollView()
viewController.view.addSubview(scrollView1)
let scrollView2 = UIScrollView()
viewController.view.addSubview(scrollView2)
// When
navigationController.pushViewController(viewController, animated: false)
// Then
guard let appBarViewController = navigationController.appBarViewController(for: viewController)
else {
XCTFail("No app bar view controller found.")
return
}
XCTAssertEqual(appBarViewController.headerView.trackingScrollView, scrollView1)
}
func testDelegateCanReturnNilTrackingScrollView() {
// Given
let viewController = UIViewController()
let scrollView1 = UIScrollView()
viewController.view.addSubview(scrollView1)
let scrollView2 = UIScrollView()
viewController.view.addSubview(scrollView2)
let delegate = MockAppBarNavigationControllerDelegate()
navigationController.delegate = delegate
// When
delegate.trackingScrollView = nil
navigationController.pushViewController(viewController, animated: false)
// Then
guard let appBarViewController = navigationController.appBarViewController(for: viewController)
else {
XCTFail("No app bar view controller found.")
return
}
XCTAssertNil(appBarViewController.headerView.trackingScrollView)
}
func testDelegateCanPickDifferentTrackingScrollView() {
// Given
let viewController = UIViewController()
let scrollView1 = UIScrollView()
viewController.view.addSubview(scrollView1)
let scrollView2 = UIScrollView()
viewController.view.addSubview(scrollView2)
let delegate = MockAppBarNavigationControllerDelegate()
navigationController.delegate = delegate
// When
delegate.trackingScrollView = scrollView2
navigationController.pushViewController(viewController, animated: false)
// Then
guard let appBarViewController = navigationController.appBarViewController(for: viewController)
else {
XCTFail("No app bar view controller found.")
return
}
XCTAssertEqual(appBarViewController.headerView.trackingScrollView, scrollView2)
}
}
| c38779fd5fa530472549866846de98a9 | 33.95679 | 99 | 0.752693 | false | false | false | false |
Ossey/WeiBo | refs/heads/master | XYWeiBo/XYWeiBo/Classes/Tools/Extension/NSDate-Extension.swift | apache-2.0 | 1 | //
// NSDate-Extension.swift
// XYWeiBo
//
// Created by xiaomage on 16/4/8.
// Copyright © 2016年 sey. All rights reserved.
//
import UIKit
extension NSDate {
class func createDateString(createAtStr : String) -> String {
// 1.创建时间格式化对象
let fmt = DateFormatter()
fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
fmt.locale = NSLocale(localeIdentifier: "en") as Locale!
// 2.将字符串时间,转成NSDate类型
guard let createDate = fmt.date(from: createAtStr) else {
return ""
}
// 3.创建当前时间
let nowDate = NSDate()
// 4.计算创建时间和当前时间的时间差
let interval = Int(nowDate.timeIntervalSince(createDate))
// 5.对时间间隔处理
// 5.1.显示刚刚
if interval < 60 {
return "刚刚"
}
// 5.2.59分钟前
if interval < 60 * 60 {
return "\(interval / 60)分钟前"
}
// 5.3.11小时前
if interval < 60 * 60 * 24 {
return "\(interval / (60 * 60))小时前"
}
// 5.4.创建日历对象
let calendar = NSCalendar.current
// 5.5.处理昨天数据: 昨天 12:23
if calendar.isDateInYesterday(createDate) {
fmt.dateFormat = "昨天 HH:mm"
let timeStr = fmt.string(from: createDate)
return timeStr
}
// 5.6.处理一年之内: 02-22 12:22
let cmps = calendar.component(.year, from: createDate)
if cmps < 1 {
fmt.dateFormat = "MM-dd HH:mm"
let timeStr = fmt.string(from: createDate)
return timeStr
}
// 5.7.超过一年: 2014-02-12 13:22
fmt.dateFormat = "yyyy-MM-dd HH:mm"
let timeStr = fmt.string(from: createDate)
return timeStr
}
}
| 4685a9a66dcb828d35de077a2df7071c | 25.411765 | 65 | 0.504454 | false | false | false | false |
hooman/swift | refs/heads/main | stdlib/public/Concurrency/TaskGroup.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import _SwiftConcurrencyShims
// ==== TaskGroup --------------------------------------------------------------
/// Starts a new task group which provides a scope in which a dynamic number of
/// tasks may be spawned.
///
/// Tasks added to the group by `group.spawn()` will automatically be awaited on
/// when the scope exits. If the group exits by throwing, all added tasks will
/// be cancelled and their results discarded.
///
/// ### Implicit awaiting
/// When the group returns it will implicitly await for all spawned tasks to
/// complete. The tasks are only cancelled if `cancelAll()` was invoked before
/// returning, the groups' task was cancelled, or the group body has thrown.
///
/// When results of tasks added to the group need to be collected, one can
/// gather their results using the following pattern:
///
/// while let result = await group.next() {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// It is also possible to collect results from the group by using its
/// `AsyncSequence` conformance, which enables its use in an asynchronous for-loop,
/// like this:
///
/// for await result in group {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// ### Cancellation
/// If the task that the group is running in is cancelled, the group becomes
/// cancelled and all child tasks spawned in the group are cancelled as well.
///
/// Since the `withTaskGroup` provided group is specifically non-throwing,
/// child tasks (or the group) cannot react to cancellation by throwing a
/// `CancellationError`, however they may interrupt their work and e.g. return
/// some best-effort approximation of their work.
///
/// If throwing is a good option for the kinds of tasks spawned by the group,
/// consider using the `withThrowingTaskGroup` function instead.
///
/// Postcondition:
/// Once `withTaskGroup` returns it is guaranteed that the `group` is *empty*.
///
/// This is achieved in the following way:
/// - if the body returns normally:
/// - the group will await any not yet complete tasks,
/// - once the `withTaskGroup` returns the group is guaranteed to be empty.
@available(SwiftStdlib 5.5, *)
@inlinable
public func withTaskGroup<ChildTaskResult, GroupResult>(
of childTaskResultType: ChildTaskResult.Type,
returning returnType: GroupResult.Type = GroupResult.self,
body: (inout TaskGroup<ChildTaskResult>) async -> GroupResult
) async -> GroupResult {
#if compiler(>=5.5) && $BuiltinTaskGroupWithArgument
let _group = Builtin.createTaskGroup(ChildTaskResult.self)
var group = TaskGroup<ChildTaskResult>(group: _group)
// Run the withTaskGroup body.
let result = await body(&group)
await group.awaitAllRemainingTasks()
Builtin.destroyTaskGroup(_group)
return result
#else
fatalError("Swift compiler is incompatible with this SDK version")
#endif
}
/// Starts a new throwing task group which provides a scope in which a dynamic
/// number of tasks may be spawned.
///
/// Tasks added to the group by `group.spawn()` will automatically be awaited on
/// when the scope exits. If the group exits by throwing, all added tasks will
/// be cancelled and their results discarded.
///
/// ### Implicit awaiting
/// When the group returns it will implicitly await for all spawned tasks to
/// complete. The tasks are only cancelled if `cancelAll()` was invoked before
/// returning, the groups' task was cancelled, or the group body has thrown.
///
/// When results of tasks added to the group need to be collected, one can
/// gather their results using the following pattern:
///
/// while let result = await try group.next() {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// It is also possible to collect results from the group by using its
/// `AsyncSequence` conformance, which enables its use in an asynchronous for-loop,
/// like this:
///
/// for try await result in group {
/// // some accumulation logic (e.g. sum += result)
/// }
///
/// ### Thrown errors
/// When tasks are added to the group using the `group.spawn` function, they may
/// immediately begin executing. Even if their results are not collected explicitly
/// and such task throws, and was not yet cancelled, it may result in the `withTaskGroup`
/// throwing.
///
/// ### Cancellation
/// If the task that the group is running in is cancelled, the group becomes
/// cancelled and all child tasks spawned in the group are cancelled as well.
///
/// If an error is thrown out of the task group, all of its remaining tasks
/// will be cancelled and the `withTaskGroup` call will rethrow that error.
///
/// Individual tasks throwing results in their corresponding `try group.next()`
/// call throwing, giving a chance to handle individual errors or letting the
/// error be rethrown by the group.
///
/// Postcondition:
/// Once `withThrowingTaskGroup` returns it is guaranteed that the `group` is *empty*.
///
/// This is achieved in the following way:
/// - if the body returns normally:
/// - the group will await any not yet complete tasks,
/// - if any of those tasks throws, the remaining tasks will be cancelled,
/// - once the `withTaskGroup` returns the group is guaranteed to be empty.
/// - if the body throws:
/// - all tasks remaining in the group will be automatically cancelled.
@available(SwiftStdlib 5.5, *)
@inlinable
public func withThrowingTaskGroup<ChildTaskResult, GroupResult>(
of childTaskResultType: ChildTaskResult.Type,
returning returnType: GroupResult.Type = GroupResult.self,
body: (inout ThrowingTaskGroup<ChildTaskResult, Error>) async throws -> GroupResult
) async rethrows -> GroupResult {
#if compiler(>=5.5) && $BuiltinTaskGroupWithArgument
let _group = Builtin.createTaskGroup(ChildTaskResult.self)
var group = ThrowingTaskGroup<ChildTaskResult, Error>(group: _group)
do {
// Run the withTaskGroup body.
let result = try await body(&group)
await group.awaitAllRemainingTasks()
Builtin.destroyTaskGroup(_group)
return result
} catch {
group.cancelAll()
await group.awaitAllRemainingTasks()
Builtin.destroyTaskGroup(_group)
throw error
}
#else
fatalError("Swift compiler is incompatible with this SDK version")
#endif
}
/// A task group serves as storage for dynamically spawned tasks.
///
/// It is created by the `withTaskGroup` function.
@available(SwiftStdlib 5.5, *)
@frozen
public struct TaskGroup<ChildTaskResult: Sendable> {
/// Group task into which child tasks offer their results,
/// and the `next()` function polls those results from.
@usableFromInline
internal let _group: Builtin.RawPointer
/// No public initializers
@inlinable
init(group: Builtin.RawPointer) {
self._group = group
}
/// Add a child task to the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
@_alwaysEmitIntoClient
public mutating func addTask(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
let flags = taskCreateFlags(
priority: priority, isChildTask: true, copyTaskLocals: false,
inheritContext: false, enqueueJob: true,
addPendingGroupTaskUnconditionally: true
)
// Create the task in this group.
_ = Builtin.createAsyncTaskInGroup(flags, _group, operation)
#else
fatalError("Unsupported Swift compiler")
#endif
}
/// Add a child task to the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
@_alwaysEmitIntoClient
public mutating func addTaskUnlessCancelled(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) -> Bool {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false)
guard canAdd else {
// the group is cancelled and is not accepting any new work
return false
}
let flags = taskCreateFlags(
priority: priority, isChildTask: true, copyTaskLocals: false,
inheritContext: false, enqueueJob: true,
addPendingGroupTaskUnconditionally: false
)
// Create the task in this group.
_ = Builtin.createAsyncTaskInGroup(flags, _group, operation)
return true
#else
fatalError("Unsupported Swift compiler")
#endif
}
/// Wait for the a child task that was added to the group to complete,
/// and return (or rethrow) the value it completed with. If no tasks are
/// pending in the task group this function returns `nil`, allowing the
/// following convenient expressions to be written for awaiting for one
/// or all tasks to complete:
///
/// Await on a single completion:
///
/// if let first = try await group.next() {
/// return first
/// }
///
/// Wait and collect all group child task completions:
///
/// while let first = try await group.next() {
/// collected += value
/// }
/// return collected
///
/// Awaiting on an empty group results in the immediate return of a `nil`
/// value, without the group task having to suspend.
///
/// It is also possible to use `for await` to collect results of a task groups:
///
/// for await try value in group {
/// collected += value
/// }
///
/// ### Thread-safety
/// Please note that the `group` object MUST NOT escape into another task.
/// The `group.next()` MUST be awaited from the task that had originally
/// created the group. It is not allowed to escape the group reference.
///
/// Note also that this is generally prevented by Swift's type-system,
/// as the `add` operation is `mutating`, and those may not be performed
/// from concurrent execution contexts, such as child tasks.
///
/// ### Ordering
/// Order of values returned by next() is *completion order*, and not
/// submission order. I.e. if tasks are added to the group one after another:
///
/// group.spawn { 1 }
/// group.spawn { 2 }
///
/// print(await group.next())
/// /// Prints "1" OR "2"
///
/// ### Errors
/// If an operation added to the group throws, that error will be rethrown
/// by the next() call corresponding to that operation's completion.
///
/// It is possible to directly rethrow such error out of a `withTaskGroup` body
/// function's body, causing all remaining tasks to be implicitly cancelled.
public mutating func next() async -> ChildTaskResult? {
// try!-safe because this function only exists for Failure == Never,
// and as such, it is impossible to spawn a throwing child task.
return try! await _taskGroupWaitNext(group: _group)
}
/// Await all the remaining tasks on this group.
@usableFromInline
internal mutating func awaitAllRemainingTasks() async {
while let _ = await next() {}
}
/// Wait for all remaining tasks in the task group to complete before
/// returning.
@_alwaysEmitIntoClient
public mutating func waitForAll() async {
await awaitAllRemainingTasks()
}
/// Query whether the group has any remaining tasks.
///
/// Task groups are always empty upon entry to the `withTaskGroup` body, and
/// become empty again when `withTaskGroup` returns (either by awaiting on all
/// pending tasks or cancelling them).
///
/// - Returns: `true` if the group has no pending tasks, `false` otherwise.
public var isEmpty: Bool {
_taskGroupIsEmpty(_group)
}
/// Cancel all the remaining, and future, tasks in the group.
///
/// A cancelled group will not will create new tasks when the `asyncUnlessCancelled`,
/// function is used. It will, however, continue to create tasks when the plain `async`
/// function is used. Such tasks will be created yet immediately cancelled, allowing
/// the tasks to perform some short-cut implementation, if they are responsive to cancellation.
///
/// This function may be called even from within child (or any other) tasks,
/// and will reliably cause the group to become cancelled.
///
/// - SeeAlso: `Task.isCancelled`
/// - SeeAlso: `TaskGroup.isCancelled`
public func cancelAll() {
_taskGroupCancelAll(group: _group)
}
/// Returns `true` if the group was cancelled, e.g. by `cancelAll`.
///
/// If the task currently running this group was cancelled, the group will
/// also be implicitly cancelled, which will be reflected in the return
/// value of this function as well.
///
/// - Returns: `true` if the group (or its parent task) was cancelled,
/// `false` otherwise.
public var isCancelled: Bool {
return _taskGroupIsCancelled(group: _group)
}
}
// Implementation note:
// We are unable to just™ abstract over Failure == Error / Never because of the
// complicated relationship between `group.spawn` which dictates if `group.next`
// AND the AsyncSequence conformances would be throwing or not.
//
// We would be able to abstract over TaskGroup<..., Failure> equal to Never
// or Error, and specifically only add the `spawn` and `next` functions for
// those two cases. However, we are not able to conform to AsyncSequence "twice"
// depending on if the Failure is Error or Never, as we'll hit:
// conflicting conformance of 'TaskGroup<ChildTaskResult, Failure>' to protocol
// 'AsyncSequence'; there cannot be more than one conformance, even with
// different conditional bounds
// So, sadly we're forced to duplicate the entire implementation of TaskGroup
// to TaskGroup and ThrowingTaskGroup.
//
// The throwing task group is parameterized with failure only because of future
// proofing, in case we'd ever have typed errors, however unlikely this may be.
// Today the throwing task group failure is simply automatically bound to `Error`.
/// A task group serves as storage for dynamically spawned, potentially throwing,
/// child tasks.
///
/// It is created by the `withTaskGroup` function.
@available(SwiftStdlib 5.5, *)
@frozen
public struct ThrowingTaskGroup<ChildTaskResult: Sendable, Failure: Error> {
/// Group task into which child tasks offer their results,
/// and the `next()` function polls those results from.
@usableFromInline
internal let _group: Builtin.RawPointer
/// No public initializers
@inlinable
init(group: Builtin.RawPointer) {
self._group = group
}
/// Await all the remaining tasks on this group.
@usableFromInline
internal mutating func awaitAllRemainingTasks() async {
while true {
do {
guard let _ = try await next() else {
return
}
} catch {}
}
}
@usableFromInline
internal mutating func _waitForAll() async throws {
while let _ = try await next() { }
}
/// Wait for all remaining tasks in the task group to complete before
/// returning.
@_alwaysEmitIntoClient
public mutating func waitForAll() async throws {
while let _ = try await next() { }
}
/// Spawn, unconditionally, a child task in the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
@_alwaysEmitIntoClient
public mutating func addTask(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
let flags = taskCreateFlags(
priority: priority, isChildTask: true, copyTaskLocals: false,
inheritContext: false, enqueueJob: true,
addPendingGroupTaskUnconditionally: true
)
// Create the task in this group.
_ = Builtin.createAsyncTaskInGroup(flags, _group, operation)
#else
fatalError("Unsupported Swift compiler")
#endif
}
/// Add a child task to the group.
///
/// ### Error handling
/// Operations are allowed to `throw`, in which case the `try await next()`
/// invocation corresponding to the failed task will re-throw the given task.
///
/// The `add` function will never (re-)throw errors from the `operation`.
/// Instead, the corresponding `next()` call will throw the error when necessary.
///
/// - Parameters:
/// - overridingPriority: override priority of the operation task
/// - operation: operation to execute and add to the group
/// - Returns:
/// - `true` if the operation was added to the group successfully,
/// `false` otherwise (e.g. because the group `isCancelled`)
@_alwaysEmitIntoClient
public mutating func addTaskUnlessCancelled(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) -> Bool {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false)
guard canAdd else {
// the group is cancelled and is not accepting any new work
return false
}
let flags = taskCreateFlags(
priority: priority, isChildTask: true, copyTaskLocals: false,
inheritContext: false, enqueueJob: true,
addPendingGroupTaskUnconditionally: false
)
// Create the task in this group.
_ = Builtin.createAsyncTaskInGroup(flags, _group, operation)
return true
#else
fatalError("Unsupported Swift compiler")
#endif
}
/// Wait for the a child task that was added to the group to complete,
/// and return (or rethrow) the value it completed with. If no tasks are
/// pending in the task group this function returns `nil`, allowing the
/// following convenient expressions to be written for awaiting for one
/// or all tasks to complete:
///
/// Await on a single completion:
///
/// if let first = try await group.next() {
/// return first
/// }
///
/// Wait and collect all group child task completions:
///
/// while let first = try await group.next() {
/// collected += value
/// }
/// return collected
///
/// Awaiting on an empty group results in the immediate return of a `nil`
/// value, without the group task having to suspend.
///
/// It is also possible to use `for await` to collect results of a task groups:
///
/// for await try value in group {
/// collected += value
/// }
///
/// ### Thread-safety
/// Please note that the `group` object MUST NOT escape into another task.
/// The `group.next()` MUST be awaited from the task that had originally
/// created the group. It is not allowed to escape the group reference.
///
/// Note also that this is generally prevented by Swift's type-system,
/// as the `add` operation is `mutating`, and those may not be performed
/// from concurrent execution contexts, such as child tasks.
///
/// ### Ordering
/// Order of values returned by next() is *completion order*, and not
/// submission order. I.e. if tasks are added to the group one after another:
///
/// group.spawn { 1 }
/// group.spawn { 2 }
///
/// print(await group.next())
/// /// Prints "1" OR "2"
///
/// ### Errors
/// If an operation added to the group throws, that error will be rethrown
/// by the next() call corresponding to that operation's completion.
///
/// It is possible to directly rethrow such error out of a `withTaskGroup` body
/// function's body, causing all remaining tasks to be implicitly cancelled.
public mutating func next() async throws -> ChildTaskResult? {
return try await _taskGroupWaitNext(group: _group)
}
@_silgen_name("$sScg10nextResults0B0Oyxq_GSgyYaKF")
@usableFromInline
mutating func nextResultForABI() async throws -> Result<ChildTaskResult, Failure>? {
do {
guard let success: ChildTaskResult = try await _taskGroupWaitNext(group: _group) else {
return nil
}
return .success(success)
} catch {
return .failure(error as! Failure) // as!-safe, because we are only allowed to throw Failure (Error)
}
}
/// - SeeAlso: `next()`
@_alwaysEmitIntoClient
public mutating func nextResult() async -> Result<ChildTaskResult, Failure>? {
return try! await nextResultForABI()
}
/// Query whether the group has any remaining tasks.
///
/// Task groups are always empty upon entry to the `withTaskGroup` body, and
/// become empty again when `withTaskGroup` returns (either by awaiting on all
/// pending tasks or cancelling them).
///
/// - Returns: `true` if the group has no pending tasks, `false` otherwise.
public var isEmpty: Bool {
_taskGroupIsEmpty(_group)
}
/// Cancel all the remaining tasks in the group.
///
/// A cancelled group will not will NOT accept new tasks being added into it.
///
/// Any results, including errors thrown by tasks affected by this
/// cancellation, are silently discarded.
///
/// This function may be called even from within child (or any other) tasks,
/// and will reliably cause the group to become cancelled.
///
/// - SeeAlso: `Task.isCancelled`
/// - SeeAlso: `TaskGroup.isCancelled`
public func cancelAll() {
_taskGroupCancelAll(group: _group)
}
/// Returns `true` if the group was cancelled, e.g. by `cancelAll`.
///
/// If the task currently running this group was cancelled, the group will
/// also be implicitly cancelled, which will be reflected in the return
/// value of this function as well.
///
/// - Returns: `true` if the group (or its parent task) was cancelled,
/// `false` otherwise.
public var isCancelled: Bool {
return _taskGroupIsCancelled(group: _group)
}
}
/// ==== TaskGroup: AsyncSequence ----------------------------------------------
@available(SwiftStdlib 5.5, *)
extension TaskGroup: AsyncSequence {
public typealias AsyncIterator = Iterator
public typealias Element = ChildTaskResult
public func makeAsyncIterator() -> Iterator {
return Iterator(group: self)
}
/// Allows iterating over results of tasks added to the group.
///
/// The order of elements returned by this iterator is the same as manually
/// invoking the `group.next()` function in a loop, meaning that results
/// are returned in *completion order*.
///
/// This iterator terminates after all tasks have completed successfully, or
/// after any task completes by throwing an error.
///
/// - SeeAlso: `TaskGroup.next()`
@available(SwiftStdlib 5.5, *)
public struct Iterator: AsyncIteratorProtocol {
public typealias Element = ChildTaskResult
@usableFromInline
var group: TaskGroup<ChildTaskResult>
@usableFromInline
var finished: Bool = false
// no public constructors
init(group: TaskGroup<ChildTaskResult>) {
self.group = group
}
/// Once this function returns `nil` this specific iterator is guaranteed to
/// never produce more values.
/// - SeeAlso: `TaskGroup.next()` for a detailed discussion its semantics.
public mutating func next() async -> Element? {
guard !finished else { return nil }
guard let element = await group.next() else {
finished = true
return nil
}
return element
}
public mutating func cancel() {
finished = true
group.cancelAll()
}
}
}
@available(SwiftStdlib 5.5, *)
extension ThrowingTaskGroup: AsyncSequence {
public typealias AsyncIterator = Iterator
public typealias Element = ChildTaskResult
public func makeAsyncIterator() -> Iterator {
return Iterator(group: self)
}
/// Allows iterating over results of tasks added to the group.
///
/// The order of elements returned by this iterator is the same as manually
/// invoking the `group.next()` function in a loop, meaning that results
/// are returned in *completion order*.
///
/// This iterator terminates after all tasks have completed successfully, or
/// after any task completes by throwing an error. If a task completes by
/// throwing an error, no further task results are returned.
///
/// - SeeAlso: `ThrowingTaskGroup.next()`
@available(SwiftStdlib 5.5, *)
public struct Iterator: AsyncIteratorProtocol {
public typealias Element = ChildTaskResult
@usableFromInline
var group: ThrowingTaskGroup<ChildTaskResult, Failure>
@usableFromInline
var finished: Bool = false
// no public constructors
init(group: ThrowingTaskGroup<ChildTaskResult, Failure>) {
self.group = group
}
/// - SeeAlso: `ThrowingTaskGroup.next()` for a detailed discussion its semantics.
public mutating func next() async throws -> Element? {
guard !finished else { return nil }
do {
guard let element = try await group.next() else {
finished = true
return nil
}
return element
} catch {
finished = true
throw error
}
}
public mutating func cancel() {
finished = true
group.cancelAll()
}
}
}
/// ==== -----------------------------------------------------------------------
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_destroy")
func _taskGroupDestroy(group: __owned Builtin.RawPointer)
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_addPending")
@usableFromInline
func _taskGroupAddPendingTask(
group: Builtin.RawPointer,
unconditionally: Bool
) -> Bool
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_cancelAll")
func _taskGroupCancelAll(group: Builtin.RawPointer)
/// Checks ONLY if the group was specifically cancelled.
/// The task itself being cancelled must be checked separately.
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_isCancelled")
func _taskGroupIsCancelled(group: Builtin.RawPointer) -> Bool
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_wait_next_throwing")
func _taskGroupWaitNext<T>(group: Builtin.RawPointer) async throws -> T?
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_hasTaskGroupStatusRecord")
func _taskHasTaskGroupStatusRecord() -> Bool
@available(SwiftStdlib 5.5, *)
enum PollStatus: Int {
case empty = 0
case waiting = 1
case success = 2
case error = 3
}
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_taskGroup_isEmpty")
func _taskGroupIsEmpty(
_ group: Builtin.RawPointer
) -> Bool
| 93913a8542af14e174e6c7f58780cf8f | 34.919598 | 106 | 0.678896 | false | false | false | false |
instacrate/tapcrate-api | refs/heads/master | Sources/api/Stripe/Models/Invoice/LineItem.swift | mit | 1 | //
// LineItem.swift
// Stripe
//
// Created by Hakon Hanesand on 1/18/17.
//
//
import Node
import Foundation
public final class Period: NodeConvertible {
public let start: Date
public let end: Date
public init(node: Node) throws {
start = try node.extract("start")
end = try node.extract("end")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"start" : try start.makeNode(in: context),
"end" : try end.makeNode(in: context)
] as [String : Node])
}
}
public enum LineItemType: String, NodeConvertible {
case invoiceitem
case subscription
}
public final class LineItem: NodeConvertible {
static let type = "line_item"
public let id: String
public let amount: Int
public let currency: Currency
public let description: String?
public let discountable: Bool
public let livemode: Bool
public let metadata: Node
public let period: Period
public let plan: Plan
public let proration: Bool
public let quantity: Int
public let subscription: StripeSubscription
public let subscription_item: String
public let type: LineItemType
public init(node: Node) throws {
guard try node.extract("object") == LineItem.type else {
throw NodeError.unableToConvert(input: node, expectation: LineItem.type, path: ["object"])
}
id = try node.extract("id")
amount = try node.extract("amount")
currency = try node.extract("currency")
description = try? node.extract("description")
discountable = try node.extract("discountable")
livemode = try node.extract("livemode")
metadata = try node.extract("metadata")
period = try node.extract("period")
plan = try node.extract("plan")
proration = try node.extract("proration")
quantity = try node.extract("quantity")
subscription = try node.extract("subscription")
subscription_item = try node.extract("subscription_item")
type = try node.extract("type")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"id" : .string(id),
"amount" : .number(.int(amount)),
"currency" : try currency.makeNode(in: context),
"discountable" : .bool(discountable),
"livemode" : .bool(livemode),
"metadata" : metadata,
"period" : try period.makeNode(in: context),
"plan" : try plan.makeNode(in: context),
"proration" : .bool(proration),
"quantity" : .number(.int(quantity)),
"subscription" : try subscription.makeNode(in: context),
"subscription_item" : .string(subscription_item),
"type" : try type.makeNode(in: context)
] as [String : Node]).add(objects: [
"description" : description
])
}
}
| ad6d98d1c681ba86fc70f2378d97c356 | 30.715789 | 102 | 0.603053 | false | false | false | false |
L-Zephyr/Drafter | refs/heads/master | Sources/Drafter/Parser/OC/ObjcMessageParser.swift | mit | 1 | //
// ObjcMessageParser.swift
// drafterPackageDescription
//
// Created by LZephyr on 2017/11/8.
//
import Foundation
import SwiftyParse
class ObjcMessageParser: ConcreteParserType {
var parser: TokenParser<[MethodInvokeNode]> {
return messageSend.continuous.map({ (methods) -> [MethodInvokeNode] in
var result = methods
for method in methods {
result.append(contentsOf: method.params.reduce([]) { $0 + $1.invokes })
}
return result
})
}
}
// MARK: - Parser
extension ObjcMessageParser {
/// 解析一个方法调用
/**
message_send = '[' receiver param_selector ']'
*/
var messageSend: TokenParser<MethodInvokeNode> {
let msg = curry(MethodInvokeNode.ocInit)
<^> receiver
<*> paramSelector
return msg.between(token(.leftSquare), token(.rightSquare)) <?> "message_send解析失败"
}
/// 调用方
/**
receiver = message_send | NAME
*/
var receiver: TokenParser<MethodInvoker> {
return lazy(self.messageSend) => toMethodInvoker()
<|> token(.name) => toMethodInvoker()
<?> "receiver解析失败"
}
/// 参数列表
/**
param_selector = param_list | NAME
*/
var paramSelector: TokenParser<[InvokeParam]> {
return paramList
<|> { [InvokeParam(name: $0.text, invokes: [])] } <^> token(.name)
<?> "param_selector解析失败"
}
/// 带具体参数的列表
/**
param_list = (param)+
*/
var paramList: TokenParser<[InvokeParam]> {
return param.many1 <?> "param_list解析失败"
}
/// 参数
/**
param = NAME ':' param_body
*/
var param: TokenParser<InvokeParam> {
return curry(InvokeParam.init)
<^> (curry({ "\($0.text)\($1.text)" }) <^> token(.name) <*> token(.colon))
<*> paramBody
}
/// 解析具体参数内容,参数中的方法调用也解析出来
var paramBody: TokenParser<[MethodInvokeNode]> {
return { lazy(self.messageSend).continuous.run($0) ?? [] }
<^> anyOpenTokens(until: token(.rightSquare) <|> token(.name) *> token(.colon))
}
}
// MARK: - Helper
extension ObjcMessageParser {
func toMethodInvoker() -> (MethodInvokeNode) -> MethodInvoker {
return { invoke in
.method(invoke)
}
}
func toMethodInvoker() -> (Token) -> MethodInvoker {
return { token in
.name(token.text)
}
}
}
extension MethodInvokeNode {
static func ocInit(_ invoker: MethodInvoker, _ params: [InvokeParam]) -> MethodInvokeNode {
let invoke = MethodInvokeNode()
invoke.isSwift = false
invoke.invoker = invoker
invoke.params = params
return invoke
}
}
| 85775b2e2fd5c306a4ab7596a3165308 | 24.522936 | 95 | 0.558231 | false | false | false | false |
danielmartin/swift | refs/heads/master | stdlib/public/core/StringStorage.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Having @objc stuff in an extension creates an ObjC category, which we don't
// want.
#if _runtime(_ObjC)
internal protocol _AbstractStringStorage : _NSCopying {
var asString: String { get }
var count: Int { get }
var isASCII: Bool { get }
var start: UnsafePointer<UInt8> { get }
var length: Int { get } // In UTF16 code units.
}
internal let _cocoaASCIIEncoding:UInt = 1 /* NSASCIIStringEncoding */
internal let _cocoaUTF8Encoding:UInt = 4 /* NSUTF8StringEncoding */
@_effects(readonly)
private func _isNSString(_ str:AnyObject) -> UInt8 {
return _swift_stdlib_isNSString(str)
}
#else
internal protocol _AbstractStringStorage {
var asString: String { get }
var count: Int { get }
var isASCII: Bool { get }
var start: UnsafePointer<UInt8> { get }
}
#endif
extension _AbstractStringStorage {
// ObjC interfaces.
#if _runtime(_ObjC)
@inline(__always)
@_effects(releasenone)
internal func _getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, _ aRange: _SwiftNSRange
) {
_precondition(aRange.location >= 0 && aRange.length >= 0,
"Range out of bounds")
_precondition(aRange.location + aRange.length <= Int(count),
"Range out of bounds")
let range = Range(
uncheckedBounds: (aRange.location, aRange.location+aRange.length))
let str = asString
str._copyUTF16CodeUnits(
into: UnsafeMutableBufferPointer(start: buffer, count: range.count),
range: range)
}
@inline(__always)
@_effects(releasenone)
internal func _getCString(
_ outputPtr: UnsafeMutablePointer<UInt8>, _ maxLength: Int, _ encoding: UInt
) -> Int8 {
switch (encoding, isASCII) {
case (_cocoaASCIIEncoding, true):
fallthrough
case (_cocoaUTF8Encoding, _):
guard maxLength >= count + 1 else { return 0 }
let buffer =
UnsafeMutableBufferPointer(start: outputPtr, count: maxLength)
buffer.initialize(from: UnsafeBufferPointer(start: start, count: count))
buffer[count] = 0
return 1
default:
return _cocoaGetCStringTrampoline(self, outputPtr, maxLength, encoding)
}
}
@inline(__always)
@_effects(readonly)
internal func _cString(encoding: UInt) -> UnsafePointer<UInt8>? {
switch (encoding, isASCII) {
case (_cocoaASCIIEncoding, true):
fallthrough
case (_cocoaUTF8Encoding, _):
return start
default:
return _cocoaCStringUsingEncodingTrampoline(self, encoding)
}
}
@_effects(readonly)
internal func _nativeIsEqual<T:_AbstractStringStorage>(
_ nativeOther: T
) -> Int8 {
if count != nativeOther.count {
return 0
}
return (start == nativeOther.start ||
(memcmp(start, nativeOther.start, count) == 0)) ? 1 : 0
}
@inline(__always)
@_effects(readonly)
internal func _isEqual(_ other: AnyObject?) -> Int8 {
guard let other = other else {
return 0
}
if self === other {
return 1
}
// Handle the case where both strings were bridged from Swift.
// We can't use String.== because it doesn't match NSString semantics.
let knownOther = _KnownCocoaString(other)
switch knownOther {
case .storage:
return _nativeIsEqual(
_unsafeUncheckedDowncast(other, to: _StringStorage.self))
case .shared:
return _nativeIsEqual(
_unsafeUncheckedDowncast(other, to: _SharedStringStorage.self))
#if !(arch(i386) || arch(arm))
case .tagged:
fallthrough
#endif
case .cocoa:
// We're allowed to crash, but for compatibility reasons NSCFString allows
// non-strings here.
if _isNSString(other) != 1 {
return 0
}
// At this point we've proven that it is an NSString of some sort, but not
// one of ours.
if length != _stdlib_binary_CFStringGetLength(other) {
return 0
}
defer { _fixLifetime(other) }
// CFString will only give us ASCII bytes here, but that's fine.
// We already handled non-ASCII UTF8 strings earlier since they're Swift.
if let otherStart = _cocoaUTF8Pointer(other) {
return (start == otherStart ||
(memcmp(start, otherStart, count) == 0)) ? 1 : 0
}
/*
The abstract implementation of -isEqualToString: falls back to -compare:
immediately, so when we run out of fast options to try, do the same.
We can likely be more clever here if need be
*/
return _cocoaStringCompare(self, other) == 0 ? 1 : 0
}
}
#endif //_runtime(_ObjC)
}
private typealias CountAndFlags = _StringObject.CountAndFlags
//
// TODO(String docs): Documentation about the runtime layout of these instances,
// which is a little complex. The second trailing allocation holds an
// Optional<_StringBreadcrumbs>.
//
final internal class _StringStorage
: __SwiftNativeNSString, _AbstractStringStorage {
#if arch(i386) || arch(arm)
// The total allocated storage capacity. Note that this includes the required
// nul-terminator.
internal var _realCapacity: Int
internal var _count: Int
internal var _flags: UInt16
internal var _reserved: UInt16
@inline(__always)
internal var count: Int { return _count }
@inline(__always)
internal var _countAndFlags: _StringObject.CountAndFlags {
return CountAndFlags(count: _count, flags: _flags)
}
#else
// The capacity of our allocation. Note that this includes the nul-terminator,
// which is not available for overriding.
internal var _realCapacityAndFlags: UInt64
internal var _countAndFlags: _StringObject.CountAndFlags
@inline(__always)
internal var count: Int { return _countAndFlags.count }
// The total allocated storage capacity. Note that this includes the required
// nul-terminator.
@inline(__always)
internal var _realCapacity: Int {
return Int(truncatingIfNeeded:
_realCapacityAndFlags & CountAndFlags.countMask)
}
#endif
@inline(__always)
final internal var isASCII: Bool { return _countAndFlags.isASCII }
final internal var asString: String {
@_effects(readonly) @inline(__always) get {
return String(_StringGuts(self))
}
}
#if _runtime(_ObjC)
@objc(length)
final internal var length: Int {
@_effects(readonly) @inline(__always) get {
return asString.utf16.count // UTF16View special-cases ASCII for us.
}
}
@objc
final internal var hash: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaHashASCIIBytes(start, length: count)
}
return _cocoaHashString(self)
}
}
@objc(characterAtIndex:)
@_effects(readonly)
final internal func character(at offset: Int) -> UInt16 {
let str = asString
return str.utf16[str._toUTF16Index(offset)]
}
@objc(getCharacters:range:)
@_effects(releasenone)
final internal func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange
) {
_getCharacters(buffer, aRange)
}
@objc(_fastCStringContents:)
@_effects(readonly)
final internal func _fastCStringContents(
_ requiresNulTermination: Int8
) -> UnsafePointer<CChar>? {
if isASCII {
return start._asCChar
}
return nil
}
@objc(UTF8String)
@_effects(readonly)
final internal func _utf8String() -> UnsafePointer<UInt8>? {
return start
}
@objc(cStringUsingEncoding:)
@_effects(readonly)
final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? {
return _cString(encoding: encoding)
}
@objc(getCString:maxLength:encoding:)
@_effects(releasenone)
final internal func getCString(
_ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt
) -> Int8 {
return _getCString(outputPtr, maxLength, encoding)
}
@objc
final internal var fastestEncoding: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaASCIIEncoding
}
return _cocoaUTF8Encoding
}
}
@objc(isEqualToString:)
@_effects(readonly)
final internal func isEqual(to other: AnyObject?) -> Int8 {
return _isEqual(other)
}
@objc(copyWithZone:)
final internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
// While _StringStorage instances aren't immutable in general,
// mutations may only occur when instances are uniquely referenced.
// Therefore, it is safe to return self here; any outstanding Objective-C
// reference will make the instance non-unique.
return self
}
#endif // _runtime(_ObjC)
private init(_doNotCallMe: ()) {
_internalInvariantFailure("Use the create method")
}
deinit {
_breadcrumbsAddress.deinitialize(count: 1)
}
}
// Determine the actual number of code unit capacity to request from malloc. We
// round up the nearest multiple of 8 that isn't a mulitple of 16, to fully
// utilize malloc's small buckets while accounting for the trailing
// _StringBreadCrumbs.
//
// NOTE: We may still under-utilize the spare bytes from the actual allocation
// for Strings ~1KB or larger, though at this point we're well into our growth
// curve.
private func determineCodeUnitCapacity(_ desiredCapacity: Int) -> Int {
#if arch(i386) || arch(arm)
// FIXME: Adapt to actual 32-bit allocator. For now, let's arrange things so
// that the instance size will be a multiple of 4.
let bias = Int(bitPattern: _StringObject.nativeBias)
let minimum = bias + desiredCapacity + 1
let size = (minimum + 3) & ~3
_internalInvariant(size % 4 == 0)
let capacity = size - bias
_internalInvariant(capacity > desiredCapacity)
return capacity
#else
// Bigger than _SmallString, and we need 1 extra for nul-terminator.
let minCap = 1 + Swift.max(desiredCapacity, _SmallString.capacity)
_internalInvariant(minCap < 0x1_0000_0000_0000, "max 48-bit length")
// Round up to the nearest multiple of 8 that isn't also a multiple of 16.
let capacity = ((minCap + 7) & -16) + 8
_internalInvariant(
capacity > desiredCapacity && capacity % 8 == 0 && capacity % 16 != 0)
return capacity
#endif
}
// Creation
extension _StringStorage {
@_effects(releasenone)
private static func create(
realCodeUnitCapacity: Int, countAndFlags: CountAndFlags
) -> _StringStorage {
let storage = Builtin.allocWithTailElems_2(
_StringStorage.self,
realCodeUnitCapacity._builtinWordValue, UInt8.self,
1._builtinWordValue, Optional<_StringBreadcrumbs>.self)
#if arch(i386) || arch(arm)
storage._realCapacity = realCodeUnitCapacity
storage._count = countAndFlags.count
storage._flags = countAndFlags.flags
#else
storage._realCapacityAndFlags =
UInt64(truncatingIfNeeded: realCodeUnitCapacity)
storage._countAndFlags = countAndFlags
#endif
storage._breadcrumbsAddress.initialize(to: nil)
storage.terminator.pointee = 0 // nul-terminated
// NOTE: We can't _invariantCheck() now, because code units have not been
// initialized. But, _StringGuts's initializer will.
return storage
}
@_effects(releasenone)
private static func create(
capacity: Int, countAndFlags: CountAndFlags
) -> _StringStorage {
_internalInvariant(capacity >= countAndFlags.count)
let realCapacity = determineCodeUnitCapacity(capacity)
_internalInvariant(realCapacity > capacity)
return _StringStorage.create(
realCodeUnitCapacity: realCapacity, countAndFlags: countAndFlags)
}
@_effects(releasenone)
internal static func create(
initializingFrom bufPtr: UnsafeBufferPointer<UInt8>,
capacity: Int,
isASCII: Bool
) -> _StringStorage {
let countAndFlags = CountAndFlags(
mortalCount: bufPtr.count, isASCII: isASCII)
_internalInvariant(capacity >= bufPtr.count)
let storage = _StringStorage.create(
capacity: capacity, countAndFlags: countAndFlags)
let addr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked
storage.mutableStart.initialize(from: addr, count: bufPtr.count)
storage._invariantCheck()
return storage
}
@_effects(releasenone)
internal static func create(
initializingFrom bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool
) -> _StringStorage {
return _StringStorage.create(
initializingFrom: bufPtr, capacity: bufPtr.count, isASCII: isASCII)
}
}
// Usage
extension _StringStorage {
@inline(__always)
private var mutableStart: UnsafeMutablePointer<UInt8> {
return UnsafeMutablePointer(Builtin.projectTailElems(self, UInt8.self))
}
private var mutableEnd: UnsafeMutablePointer<UInt8> {
@inline(__always) get { return mutableStart + count }
}
@inline(__always)
internal var start: UnsafePointer<UInt8> {
return UnsafePointer(mutableStart)
}
private final var end: UnsafePointer<UInt8> {
@inline(__always) get { return UnsafePointer(mutableEnd) }
}
// Point to the nul-terminator.
private final var terminator: UnsafeMutablePointer<UInt8> {
@inline(__always) get { return mutableEnd }
}
private var codeUnits: UnsafeBufferPointer<UInt8> {
@inline(__always) get {
return UnsafeBufferPointer(start: start, count: count)
}
}
// @opaque
internal var _breadcrumbsAddress: UnsafeMutablePointer<_StringBreadcrumbs?> {
let raw = Builtin.getTailAddr_Word(
start._rawValue,
_realCapacity._builtinWordValue,
UInt8.self,
Optional<_StringBreadcrumbs>.self)
return UnsafeMutablePointer(raw)
}
// The total capacity available for code units. Note that this excludes the
// required nul-terminator.
internal var capacity: Int {
return _realCapacity &- 1
}
// The unused capacity available for appending. Note that this excludes the
// required nul-terminator.
//
// NOTE: Callers who wish to mutate this storage should enfore nul-termination
private var unusedStorage: UnsafeMutableBufferPointer<UInt8> {
@inline(__always) get {
return UnsafeMutableBufferPointer(
start: mutableEnd, count: unusedCapacity)
}
}
// The capacity available for appending. Note that this excludes the required
// nul-terminator.
internal var unusedCapacity: Int {
get { return _realCapacity &- count &- 1 }
}
#if !INTERNAL_CHECKS_ENABLED
@inline(__always) internal func _invariantCheck() {}
#else
internal func _invariantCheck() {
let rawSelf = UnsafeRawPointer(Builtin.bridgeToRawPointer(self))
let rawStart = UnsafeRawPointer(start)
_internalInvariant(unusedCapacity >= 0)
_internalInvariant(count <= capacity)
_internalInvariant(rawSelf + Int(_StringObject.nativeBias) == rawStart)
_internalInvariant(self._realCapacity > self.count, "no room for nul-terminator")
_internalInvariant(self.terminator.pointee == 0, "not nul terminated")
_countAndFlags._invariantCheck()
if isASCII {
_internalInvariant(_allASCII(self.codeUnits))
}
if let crumbs = _breadcrumbsAddress.pointee {
crumbs._invariantCheck(for: self.asString)
}
_internalInvariant(_countAndFlags.isNativelyStored)
_internalInvariant(_countAndFlags.isTailAllocated)
}
#endif // INTERNAL_CHECKS_ENABLED
}
// Appending
extension _StringStorage {
// Perform common post-RRC adjustments and invariant enforcement.
@_effects(releasenone)
private func _postRRCAdjust(newCount: Int, newIsASCII: Bool) {
let countAndFlags = CountAndFlags(
mortalCount: newCount, isASCII: newIsASCII)
#if arch(i386) || arch(arm)
self._count = countAndFlags.count
self._flags = countAndFlags.flags
#else
self._countAndFlags = countAndFlags
#endif
self.terminator.pointee = 0
// TODO(String performance): Consider updating breadcrumbs when feasible.
self._breadcrumbsAddress.pointee = nil
_invariantCheck()
}
// Perform common post-append adjustments and invariant enforcement.
@_effects(releasenone)
private func _postAppendAdjust(
appendedCount: Int, appendedIsASCII isASCII: Bool
) {
let oldTerminator = self.terminator
_postRRCAdjust(
newCount: self.count + appendedCount, newIsASCII: self.isASCII && isASCII)
_internalInvariant(oldTerminator + appendedCount == self.terminator)
}
@_effects(releasenone)
internal func appendInPlace(
_ other: UnsafeBufferPointer<UInt8>, isASCII: Bool
) {
_internalInvariant(self.capacity >= other.count)
let srcAddr = other.baseAddress._unsafelyUnwrappedUnchecked
let srcCount = other.count
self.mutableEnd.initialize(from: srcAddr, count: srcCount)
_postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII)
}
@_effects(releasenone)
internal func appendInPlace<Iter: IteratorProtocol>(
_ other: inout Iter, isASCII: Bool
) where Iter.Element == UInt8 {
var srcCount = 0
while let cu = other.next() {
_internalInvariant(self.unusedCapacity >= 1)
unusedStorage[srcCount] = cu
srcCount += 1
}
_postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII)
}
internal func clear() {
_postRRCAdjust(newCount: 0, newIsASCII: true)
}
}
// Removing
extension _StringStorage {
@_effects(releasenone)
internal func remove(from lower: Int, to upper: Int) {
_internalInvariant(lower <= upper)
let lowerPtr = mutableStart + lower
let upperPtr = mutableStart + upper
let tailCount = mutableEnd - upperPtr
lowerPtr.moveInitialize(from: upperPtr, count: tailCount)
_postRRCAdjust(
newCount: self.count &- (upper &- lower), newIsASCII: self.isASCII)
}
// Reposition a tail of this storage from src to dst. Returns the length of
// the tail.
@_effects(releasenone)
internal func _slideTail(
src: UnsafeMutablePointer<UInt8>,
dst: UnsafeMutablePointer<UInt8>
) -> Int {
_internalInvariant(dst >= mutableStart && src <= mutableEnd)
let tailCount = mutableEnd - src
dst.moveInitialize(from: src, count: tailCount)
return tailCount
}
@_effects(releasenone)
internal func replace(
from lower: Int, to upper: Int, with replacement: UnsafeBufferPointer<UInt8>
) {
_internalInvariant(lower <= upper)
let replCount = replacement.count
_internalInvariant(replCount - (upper - lower) <= unusedCapacity)
// Position the tail.
let lowerPtr = mutableStart + lower
let tailCount = _slideTail(
src: mutableStart + upper, dst: lowerPtr + replCount)
// Copy in the contents.
lowerPtr.moveInitialize(
from: UnsafeMutablePointer(
mutating: replacement.baseAddress._unsafelyUnwrappedUnchecked),
count: replCount)
let isASCII = self.isASCII && _allASCII(replacement)
_postRRCAdjust(newCount: lower + replCount + tailCount, newIsASCII: isASCII)
}
@_effects(releasenone)
internal func replace<C: Collection>(
from lower: Int,
to upper: Int,
with replacement: C,
replacementCount replCount: Int
) where C.Element == UInt8 {
_internalInvariant(lower <= upper)
_internalInvariant(replCount - (upper - lower) <= unusedCapacity)
// Position the tail.
let lowerPtr = mutableStart + lower
let tailCount = _slideTail(
src: mutableStart + upper, dst: lowerPtr + replCount)
// Copy in the contents.
var isASCII = self.isASCII
var srcCount = 0
for cu in replacement {
if cu >= 0x80 { isASCII = false }
lowerPtr[srcCount] = cu
srcCount += 1
}
_internalInvariant(srcCount == replCount)
_postRRCAdjust(
newCount: lower + replCount + tailCount, newIsASCII: isASCII)
}
}
// For shared storage and bridging literals
final internal class _SharedStringStorage
: __SwiftNativeNSString, _AbstractStringStorage {
internal var _owner: AnyObject?
internal var start: UnsafePointer<UInt8>
#if arch(i386) || arch(arm)
internal var _count: Int
internal var _flags: UInt16
@inline(__always)
internal var _countAndFlags: _StringObject.CountAndFlags {
return CountAndFlags(count: _count, flags: _flags)
}
#else
internal var _countAndFlags: _StringObject.CountAndFlags
#endif
internal var _breadcrumbs: _StringBreadcrumbs? = nil
internal var count: Int { return _countAndFlags.count }
internal init(
immortal ptr: UnsafePointer<UInt8>,
countAndFlags: _StringObject.CountAndFlags
) {
self._owner = nil
self.start = ptr
#if arch(i386) || arch(arm)
self._count = countAndFlags.count
self._flags = countAndFlags.flags
#else
self._countAndFlags = countAndFlags
#endif
super.init()
self._invariantCheck()
}
@inline(__always)
final internal var isASCII: Bool { return _countAndFlags.isASCII }
final internal var asString: String {
@_effects(readonly) @inline(__always) get {
return String(_StringGuts(self))
}
}
#if _runtime(_ObjC)
@objc(length)
final internal var length: Int {
@_effects(readonly) get {
return asString.utf16.count // UTF16View special-cases ASCII for us.
}
}
@objc
final internal var hash: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaHashASCIIBytes(start, length: count)
}
return _cocoaHashString(self)
}
}
@objc(characterAtIndex:)
@_effects(readonly)
final internal func character(at offset: Int) -> UInt16 {
let str = asString
return str.utf16[str._toUTF16Index(offset)]
}
@objc(getCharacters:range:)
@_effects(releasenone)
final internal func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange
) {
_getCharacters(buffer, aRange)
}
@objc
final internal var fastestEncoding: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaASCIIEncoding
}
return _cocoaUTF8Encoding
}
}
@objc(_fastCStringContents:)
@_effects(readonly)
final internal func _fastCStringContents(
_ requiresNulTermination: Int8
) -> UnsafePointer<CChar>? {
if isASCII {
return start._asCChar
}
return nil
}
@objc(UTF8String)
@_effects(readonly)
final internal func _utf8String() -> UnsafePointer<UInt8>? {
return start
}
@objc(cStringUsingEncoding:)
@_effects(readonly)
final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? {
return _cString(encoding: encoding)
}
@objc(getCString:maxLength:encoding:)
@_effects(releasenone)
final internal func getCString(
_ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt
) -> Int8 {
return _getCString(outputPtr, maxLength, encoding)
}
@objc(isEqualToString:)
@_effects(readonly)
final internal func isEqual(to other:AnyObject?) -> Int8 {
return _isEqual(other)
}
@objc(copyWithZone:)
final internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
// While _StringStorage instances aren't immutable in general,
// mutations may only occur when instances are uniquely referenced.
// Therefore, it is safe to return self here; any outstanding Objective-C
// reference will make the instance non-unique.
return self
}
#endif // _runtime(_ObjC)
}
extension _SharedStringStorage {
#if !INTERNAL_CHECKS_ENABLED
@inline(__always)
internal func _invariantCheck() {}
#else
internal func _invariantCheck() {
if let crumbs = _breadcrumbs {
crumbs._invariantCheck(for: self.asString)
}
_countAndFlags._invariantCheck()
_internalInvariant(!_countAndFlags.isNativelyStored)
_internalInvariant(!_countAndFlags.isTailAllocated)
}
#endif // INTERNAL_CHECKS_ENABLED
}
| e92ded292c279e62f9f9336128777085 | 28.710199 | 85 | 0.68891 | false | false | false | false |
ReSwift/ReSwift-Todo-Example | refs/heads/master | ReSwift-Todo/DateConverter.swift | mit | 1 | //
// DateConverter.swift
// ReSwift-Todo
//
// Created by Christian Tietze on 13/09/16.
// Copyright © 2016 ReSwift. All rights reserved.
//
import Foundation
extension Calendar {
func dateFromISOComponents(year: Int, month: Int, day: Int) -> Date? {
// Without custom checks, "12-945-23" does work.
guard (1...12).contains(month)
&& (1...31).contains(day)
else { return nil }
var components = DateComponents()
components.year = year
components.month = month
components.day = day
return self.date(from: components)
}
}
class DateConverter {
init() { }
/// Expects `isoDateString` to start with `2016-09-13`
/// (YYYY-MM-DD) and extracts these values.
func date(isoDateString string: String, calendar: Calendar = Calendar.autoupdatingCurrent) -> Date? {
let parts = string.split(separator: "-")
.map(String.init)
.compactMap { Int($0) }
guard parts.count >= 3 else { return nil }
return calendar.dateFromISOComponents(year: parts[0], month: parts[1], day: parts[2])
}
static var isoFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
func string(date: Date) -> String {
return DateConverter.isoFormatter.string(from: date)
}
}
| 870c1d46c132815336f5ccfdbdb9b308 | 24.482759 | 105 | 0.610284 | false | false | false | false |
mleiv/MEGameTracker | refs/heads/master | MEGameTracker/Models/CoreData/Data Rows/DataEventsable.swift | mit | 1 | //
// DataEventsable.swift
// MEGameTracker
//
// Created by Emily Ivie on 4/15/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import Foundation
import CoreData
public protocol DataEventsable {
/// The serialized event data stored (can be edited, like during base import, but this is not recommended)
var rawEventDictionary: [CodableDictionary] { get }
/// A reference to the current core data manager.
/// (Default provided for CodableCoreDataStorable objects.)
var defaultManager: CodableCoreDataManageable { get }
}
extension DataEventsable {
typealias DataEventsableType = DataEvent
// public func getDataEvents(with manager: CodableCoreDataManageable?) -> [DataEvent] {
// let manager = manager ?? CoreDataManager.current
// return (try? manager.decoder.decode([DataEvent].self, from: rawEventDictionary)) ?? []
// }
public func getRelatedDataEvents(
context: NSManagedObjectContext?
) -> NSSet {
let ids = getIdsFromRawEventDictionary()
guard !ids.isEmpty else { return NSSet() }
let manager = type(of: defaultManager).init(context: context)
let directEvents = DataEvent.getAll(ids: ids, with: manager)
let relatedEventIds = ids + directEvents.flatMap({ $0.dependentOn?.events ?? [] }) // yes Flat Map
let allEvents: [DataEvents] = manager.getAll { fetchRequest in
fetchRequest.predicate = NSPredicate(format: "(%K in %@)", "id", relatedEventIds)
}
return NSSet(array: allEvents)
}
private func getIdsFromRawEventDictionary() -> [String] {
return rawEventDictionary.map { $0["id"] as? String }.filter({ $0 != nil }).map({ $0! })
}
}
private struct DataEventsableDecodedEventId: Codable {
let id: String
}
| 14dc7c59954e747514d977eaebd0d0a0 | 34.235294 | 110 | 0.676683 | false | false | false | false |
cwwise/CWWeChat | refs/heads/master | CWWeChat/ChatModule/CWChatKit/Message/View/CWChatUIConstant.swift | mit | 2 | //
// CWChatUIConstant.swift
// CWWeChat
//
// Created by chenwei on 16/6/22.
// Copyright © 2016年 chenwei. All rights reserved.
//
import UIKit
// 上下留白
let kMessageCellTopMargin: CGFloat = 2.0
let kMessageCellBottomMargin: CGFloat = 12.0
let kChatTextMaxWidth = kScreenWidth * 0.58
//图片
let kChatImageMaxWidth = kScreenWidth * 0.45
let kChatImageMinWidth = kScreenWidth * 0.25
let kChatVoiceMaxWidth = kScreenWidth * 0.3
let defaultHeadeImage = CWAsset.Default_head.image
public struct ChatCellUI {
static let bubbleTopMargin: CGFloat = 2
static let bubbleBottomMargin: CGFloat = 11
static let left_cap_insets = UIEdgeInsets(top: 32, left: 40, bottom: 20, right: 40)
/// 左边气泡背景区域 间距
static let left_edge_insets = UIEdgeInsets(top: 2+10, left: 17, bottom: 11+9.5, right: 17)
static let right_cap_insets = UIEdgeInsets(top: 32, left: 40, bottom: 20, right: 40)
/// 右边气泡背景区域 间距
static let right_edge_insets = UIEdgeInsets(top: 2+10, left: 17, bottom: 11+9.5, right: 17)
}
//MARK: UI相关
public struct ChatSessionCellUI {
static let headerImageViewLeftPadding:CGFloat = 10.0
static let headerImageViewTopPadding:CGFloat = 10.0
}
/*
let kTimeMessageCellHeight: CGFloat = 30.0
// cell布局中的间距
let kMessageCellMargin: CGFloat = 10.0
/// 头像
let kAvaterImageViewWidth: CGFloat = 40.0
let kAvaterImageViewMargin: CGFloat = 10.0
/// 名称
let kNameLabelHeight: CGFloat = 14.0
let kNameLabelSpaceX: CGFloat = 12.0
let kNamelabelSpaceY: CGFloat = 1.0
let kAvatarToMessageContent: CGFloat = 5.0
let kMessageCellEdgeOffset: CGFloat = 6.0
public let kChatTextAttribute = [NSAttributedStringKey.foregroundColor:UIColor.black,
NSAttributedStringKey.font: UIFont.fontTextMessageText()]
*/
| 43bec6779ba82a2d001abb5d16567ae2 | 24.871429 | 95 | 0.705135 | false | false | false | false |
noppoMan/aws-sdk-swift | refs/heads/main | Sources/Soto/Services/SageMaker/SageMaker_Error.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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 SageMaker
public struct SageMakerErrorType: AWSErrorType {
enum Code: String {
case conflictException = "ConflictException"
case resourceInUse = "ResourceInUse"
case resourceLimitExceeded = "ResourceLimitExceeded"
case resourceNotFound = "ResourceNotFound"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize SageMaker
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 }
/// There was a conflict when you attempted to modify an experiment, trial, or trial component.
public static var conflictException: Self { .init(.conflictException) }
/// Resource being accessed is in use.
public static var resourceInUse: Self { .init(.resourceInUse) }
/// You have exceeded an Amazon SageMaker resource limit. For example, you might have too many training jobs created.
public static var resourceLimitExceeded: Self { .init(.resourceLimitExceeded) }
/// Resource being access is not found.
public static var resourceNotFound: Self { .init(.resourceNotFound) }
}
extension SageMakerErrorType: Equatable {
public static func == (lhs: SageMakerErrorType, rhs: SageMakerErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension SageMakerErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 339bc1c0e0189fe635718f5536d3f56b | 34.893939 | 122 | 0.652174 | false | false | false | false |
huangxinping/XPKit-swift | refs/heads/master | Source/Extensions/UIKit/UIDevice+XPKit.swift | mit | 1 | //
// UIDevice+XPKit.swift
// XPKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2016 Fabrizio Brancati. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
// MARK: - Private variables -
/// Used to store the XPUniqueIdentifier in defaults
private let XPUniqueIdentifierDefaultsKey = "XPUniqueIdentifier"
private let XPUserUniqueIdentifierDefaultsKey = "XPUserUniqueIdentifier"
// MARK: - Global functions -
/**
Get the iOS version string
- returns: Get the iOS version string
*/
public func IOS_VERSION() -> String {
return UIDevice.currentDevice().systemVersion
}
/**
Compare system versions
- parameter v: Version, like "9.0"
- returns: Returns a Bool
*/
public func SYSTEM_VERSION_EQUAL_TO(v: String) -> Bool {
return UIDevice.currentDevice().systemVersion.compare(v, options: .NumericSearch) == .OrderedSame
}
/**
Compare system versions
- parameter v: Version, like "9.0"
- returns: Returns a Bool
*/
public func SYSTEM_VERSION_GREATER_THAN(v: String) -> Bool {
return UIDevice.currentDevice().systemVersion.compare(v, options: .NumericSearch) == .OrderedDescending
}
/**
Compare system versions
- parameter v: Version, like "9.0"
- returns: Returns a Bool
*/
public func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v: String) -> Bool {
return UIDevice.currentDevice().systemVersion.compare(v, options: .NumericSearch) != .OrderedAscending
}
/**
Compare system versions
- parameter v: Version, like "9.0"
- returns: Returns a Bool
*/
public func SYSTEM_VERSION_LESS_THAN(v: String) -> Bool {
return UIDevice.currentDevice().systemVersion.compare(v, options: .NumericSearch) == .OrderedAscending
}
/**
Compare system versions
- parameter v: Version, like "9.0"
- returns: Returns a Bool
*/
public func SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v: String) -> Bool {
return UIDevice.currentDevice().systemVersion.compare(v, options: .NumericSearch) != .OrderedDescending
}
/**
Returns if the iOS version is greater or equal to choosed one
- returns: Returns if the iOS version is greater or equal to choosed one
*/
public func IS_IOS_5_OR_LATER() -> Bool {
return UIDevice.currentDevice().systemVersion.floatValue >= 5.0
}
/**
Returns if the iOS version is greater or equal to choosed one
- returns: Returns if the iOS version is greater or equal to choosed one
*/
public func IS_IOS_6_OR_LATER() -> Bool {
return UIDevice.currentDevice().systemVersion.floatValue >= 6.0
}
/**
Returns if the iOS version is greater or equal to choosed one
- returns: Returns if the iOS version is greater or equal to choosed one
*/
public func IS_IOS_7_OR_LATER() -> Bool {
return UIDevice.currentDevice().systemVersion.floatValue >= 7.0
}
/**
Returns if the iOS version is greater or equal to choosed one
- returns: Returns if the iOS version is greater or equal to choosed one
*/
public func IS_IOS_8_OR_LATER() -> Bool {
return UIDevice.currentDevice().systemVersion.floatValue >= 8.0
}
/**
Returns if the iOS version is greater or equal to choosed one
- returns: Returns if the iOS version is greater or equal to choosed one
*/
public func IS_IOS_9_OR_LATER() -> Bool {
return UIDevice.currentDevice().systemVersion.floatValue >= 9.0
}
/// This extesion adds some useful functions to UIDevice
public extension UIDevice {
// MARK: - Class functions -
/**
Returns the device platform string
Example: "iPhone7,2"
- returns: Returns the device platform string
*/
public static func devicePlatform() -> String {
var name: [Int32] = [CTL_HW, HW_MACHINE]
var size: Int = 2
sysctl(&name, 2, nil, &size, &name, 0)
var hw_machine = [CChar](count: Int(size), repeatedValue: 0)
sysctl(&name, 2, &hw_machine, &size, &name, 0)
let hardware: String = String.fromCString(hw_machine)!
return hardware
}
/**
Returns the user-friendly device platform string
Example: "iPad Air (Cellular)"
- returns: Returns the user-friendly device platform string
*/
public static func devicePlatformString() -> String {
let platform: String = self.devicePlatform()
switch platform {
// iPhone
case "iPhone1,1": return "iPhone 2G"
case "iPhone1,2": return "iPhone 3G"
case "iPhone2,1": return "iPhone 3GS"
case "iPhone3,1": return "iPhone 4 (GSM)"
case "iPhone3,2": return "iPhone 4 (Rev. A)"
case "iPhone3,3": return "iPhone 4 (CDMA)"
case "iPhone4,1": return "iPhone 4S"
case "iPhone5,1": return "iPhone 5 (GSM)"
case "iPhone5,2": return "iPhone 5 (CDMA)"
case "iPhone5,3": return "iPhone 5c (GSM)"
case "iPhone5,4": return "iPhone 5c (Global)"
case "iPhone6,1": return "iPhone 5s (GSM)"
case "iPhone6,2": return "iPhone 5s (Global)"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone7,2": return "iPhone 6"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE"
// iPod
case "iPod1,1": return "iPod Touch 1G"
case "iPod2,1": return "iPod Touch 2G"
case "iPod3,1": return "iPod Touch 3G"
case "iPod4,1": return "iPod Touch 4G"
case "iPod5,1": return "iPod Touch 5G"
case "iPod7,1": return "iPod Touch 6G"
// iPad
case "iPad1,1": return "iPad 1"
case "iPad2,1": return "iPad 2 (WiFi)"
case "iPad2,2": return "iPad 2 (GSM)"
case "iPad2,3": return "iPad 2 (CDMA)"
case "iPad2,4": return "iPad 2 (32nm)"
case "iPad3,1": return "iPad 3 (WiFi)"
case "iPad3,2": return "iPad 3 (CDMA)"
case "iPad3,3": return "iPad 3 (GSM)"
case "iPad3,4": return "iPad 4 (WiFi)"
case "iPad3,5": return "iPad 4 (GSM)"
case "iPad3,6": return "iPad 4 (CDMA)"
case "iPad4,1": return "iPad Air (WiFi)"
case "iPad4,2": return "iPad Air (Cellular)"
case "iPad4,3": return "iPad Air (China)"
case "iPad5,3": return "iPad Air 2 (WiFi)"
case "iPad5,4": return "iPad Air 2 (Cellular)"
// iPad mini
case "iPad2,5": return "iPad mini (WiFi)"
case "iPad2,6": return "iPad mini (GSM)"
case "iPad2,7": return "iPad mini (CDMA)"
case "iPad4,4": return "iPad mini 2 (WiFi)"
case "iPad4,5": return "iPad mini 2 (Cellular)"
case "iPad4,6": return "iPad mini 2 (China)"
case "iPad4,7": return "iPad mini 3 (WiFi)"
case "iPad4,8": return "iPad mini 3 (Cellular)"
case "iPad4,9": return "iPad mini 3 (China)"
// iPad Pro 9.7
case "iPad6,3": return "iPad Pro 9.7 (WiFi)"
case "iPad6,4": return "iPad Pro 9.7 (Cellular)"
// iPad Pro 12.9
case "iPad6,7": return "iPad Pro 12.9 (WiFi)"
case "iPad6,8": return "iPad Pro 12.9 (Cellular)"
// Apple TV
case "AppleTV2,1": return "Apple TV 2G"
case "AppleTV3,1": return "Apple TV 3G"
case "AppleTV3,2": return "Apple TV 3G"
case "AppleTV5,3": return "Apple TV 4G"
// Apple Watch
case "Watch1,1": return "Apple Watch 38mm"
case "Watch1,2": return "Apple Watch 42mm"
// Simulator
case "i386", "x86_64": return "Simulator"
default:
return platform
}
}
/**
Check if the current device is an iPad
- returns: Returns true if it's an iPad, fasle if not
*/
public static func isiPad() -> Bool {
if self.devicePlatform().substringToIndex(4) == "iPad" {
return true
} else {
return false
}
}
/**
Check if the current device is an iPhone
- returns: Returns true if it's an iPhone, false if not
*/
public static func isiPhone() -> Bool {
if self.devicePlatform().substringToIndex(6) == "iPhone" {
return true
} else {
return false
}
}
/**
Check if the current device is an iPod
- returns: Returns true if it's an iPod, false if not
*/
public static func isiPod() -> Bool {
if self.devicePlatform().substringToIndex(4) == "iPod" {
return true
} else {
return false
}
}
/**
Check if the current device is an Apple TV
- returns: Returns true if it's an Apple TV, false if not
*/
public static func isAppleTV() -> Bool {
if self.devicePlatform().substringToIndex(7) == "AppleTV" {
return true
} else {
return false
}
}
/**
Check if the current device is an Apple Watch
- returns: Returns true if it's an Apple Watch, false if not
*/
public static func isAppleWatch() -> Bool {
if self.devicePlatform().substringToIndex(5) == "Watch" {
return true
} else {
return false
}
}
/**
Check if the current device is a Simulator
- returns: Returns true if it's a Simulator, false if not
*/
public static func isSimulator() -> Bool {
if self.devicePlatform() == "i386" || self.devicePlatform() == "x86_64" {
return true
} else {
return false
}
}
/**
Check if the current device has a Retina display
- returns: Returns true if it has a Retina display, false if not
*/
@available( *, deprecated = 1.4.0, message = "Use isRetina() in UIScreen class")
public static func isRetina() -> Bool {
return UIScreen.isRetina()
}
/**
Check if the current device has a Retina HD display
- returns: Returns true if it has a Retina HD display, false if not
*/
@available( *, deprecated = 1.4.0, message = "Use isRetinaHD() in UIScreen class")
public static func isRetinaHD() -> Bool {
return UIScreen.isRetinaHD()
}
/**
Returns the iOS version without the subversion
Example: 7
- returns: Returns the iOS version
*/
public static func iOSVersion() -> Int {
return Int(UIDevice.currentDevice().systemVersion.substringToCharacter(".")!)!
}
/**
Private, used to get the system info
- parameter typeSpecifier: Type of the system info
- returns: Return the sysyem info
*/
private static func getSysInfo(typeSpecifier: Int32) -> Int {
var name: [Int32] = [CTL_HW, typeSpecifier]
var size: Int = 2
sysctl(&name, 2, nil, &size, &name, 0)
var results: Int = 0
sysctl(&name, 2, &results, &size, &name, 0)
return results
}
/**
Returns the current device CPU frequency
- returns: Returns the current device CPU frequency
*/
public static func cpuFrequency() -> Int {
return self.getSysInfo(HW_CPU_FREQ)
}
/**
Returns the current device BUS frequency
- returns: Returns the current device BUS frequency
*/
public static func busFrequency() -> Int {
return self.getSysInfo(HW_TB_FREQ)
}
/**
Returns the current device RAM size
- returns: Returns the current device RAM size
*/
public static func ramSize() -> Int {
return self.getSysInfo(HW_MEMSIZE)
}
/**
Returns the current device CPU number
- returns: Returns the current device CPU number
*/
public static func cpuNumber() -> Int {
return self.getSysInfo(HW_NCPU)
}
/**
Returns the current device total memory
- returns: Returns the current device total memory
*/
public static func totalMemory() -> Int {
return self.getSysInfo(HW_PHYSMEM)
}
/**
Returns the current device non-kernel memory
- returns: Returns the current device non-kernel memory
*/
public static func userMemory() -> Int {
return self.getSysInfo(HW_USERMEM)
}
/**
Returns the current device total disk space
- returns: Returns the current device total disk space
*/
public static func totalDiskSpace() throws -> AnyObject {
let attributes: NSDictionary = try NSFileManager.defaultManager().attributesOfFileSystemForPath(NSHomeDirectory())
return attributes.objectForKey(NSFileSystemSize)!
}
/**
Returns the current device free disk space
- returns: Returns the current device free disk space
*/
public static func freeDiskSpace() throws -> AnyObject {
let attributes: NSDictionary = try NSFileManager.defaultManager().attributesOfFileSystemForPath(NSHomeDirectory())
return attributes.objectForKey(NSFileSystemFreeSize)!
}
/**
Generate an unique identifier and store it into standardUserDefaults
- returns: Returns a unique identifier as a String
*/
public static func uniqueIdentifier() -> String {
var UUID: String?
if UIDevice.currentDevice().respondsToSelector(Selector("identifierForVendor")) {
UUID = UIDevice.currentDevice().identifierForVendor!.UUIDString
} else {
let defaults = NSUserDefaults.standardUserDefaults()
UUID = defaults.objectForKey(XPUniqueIdentifierDefaultsKey) as? String
if UUID == nil {
UUID = String.generateUUID()
defaults.setObject(UUID, forKey: XPUniqueIdentifierDefaultsKey)
defaults.synchronize()
}
}
return UUID!
}
/**
Save the unique identifier or update it if there is and it is changed.
Is useful for push notification to know if the unique identifier has changed and needs to be send to server
- parameter uniqueIdentifier: The unique identifier to save or update if needed. (Must be NSData or NSString)
- parameter block: The execution block that know if the unique identifier is valid and has to be updated. You have to handle the case if it is valid and the update is needed or not
*/
public static func updateUniqueIdentifier(uniqueIdentifier: NSObject, block: (isValid: Bool, hasToUpdateUniqueIdentifier: Bool, oldUUID: String?) -> ()) {
var userUUID: String = ""
var savedUUID: String? = nil
var isValid = false, hasToUpdate = false
if uniqueIdentifier.isKindOfClass(NSData) {
let data: NSData = uniqueIdentifier as! NSData
userUUID = data.convertToUTF8String()
} else if uniqueIdentifier.isKindOfClass(NSString) {
let string: NSString = uniqueIdentifier as! NSString
userUUID = string.convertToAPNSUUID() as String
}
isValid = userUUID.isUUIDForAPNS()
if isValid {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
savedUUID = defaults.stringForKey(XPUserUniqueIdentifierDefaultsKey)
if savedUUID == nil || savedUUID != userUUID {
defaults.setObject(userUUID, forKey: XPUserUniqueIdentifierDefaultsKey)
defaults.synchronize()
hasToUpdate = true
}
}
block(isValid: isValid, hasToUpdateUniqueIdentifier: hasToUpdate, oldUUID: userUUID)
}
}
| f0d21e3685bdcfa7ee1e598bee27353d | 28.216963 | 193 | 0.699656 | false | false | false | false |
darkbrow/iina | refs/heads/develop | iina/Regex.swift | gpl-3.0 | 2 | //
// Regex.swift
// iina
//
// Created by lhc on 12/1/2017.
// Copyright © 2017 lhc. All rights reserved.
//
import Foundation
class Regex {
static let aspect = Regex("\\A\\d+(\\.\\d+)?:\\d+(\\.\\d+)?\\Z")
static let httpFileName = Regex("attachment; filename=(.+?)\\Z")
static let url = Regex("^(([^:\\/?#]+):)(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?")
static let filePath = Regex("^(/[^/]+)+$")
static let iso639_2Desc = Regex("^.+?\\(([a-z]{2,3})\\)$")
static let geometry = Regex("^((\\d+%?)?(x(\\d+%?))?)?((\\+|\\-)(\\d+%?)(\\+|\\-)(\\d+%?))?$")
var regex: NSRegularExpression?
init (_ pattern: String) {
if let exp = try? NSRegularExpression(pattern: pattern, options: []) {
self.regex = exp
} else {
fatalError("Cannot create regex \(pattern)")
}
}
func matches(_ str: String) -> Bool {
if let matches = regex?.numberOfMatches(in: str, options: [], range: NSMakeRange(0, str.count)) {
return matches > 0
} else {
return false
}
}
func captures(in str: String) -> [String] {
var result: [String] = []
if let match = regex?.firstMatch(in: str, options: [], range: NSMakeRange(0, str.count)) {
for i in 0..<match.numberOfRanges {
let range = match.range(at: i)
if range.length > 0 {
result.append((str as NSString).substring(with: match.range(at: i)))
} else {
result.append("")
}
}
}
return result
}
}
| bcd9c7e14e57a3ffe4eefc6ef46c9768 | 27.461538 | 101 | 0.522297 | false | false | false | false |
Subberbox/Subber-api | refs/heads/master | Sources/App/Controllers/VendorController.swift | mit | 2 | //
// VendorController.swift
// subber-api
//
// Created by Hakon Hanesand on 11/15/16.
//
//
import Foundation
import Vapor
import HTTP
import Turnstile
import Auth
extension Vendor {
func shouldAllow(request: Request) throws {
guard let vendor = try? request.vendor() else {
throw try Abort.custom(status: .forbidden, message: "Method \(request.method) is not allowed on resource Vendor(\(throwableId())) by this user. Must be logged in as Vendor(\(throwableId())).")
}
guard try vendor.throwableId() == throwableId() else {
throw try Abort.custom(status: .forbidden, message: "This Vendor(\(vendor.throwableId()) does not have access to resource Vendor(\(throwableId()). Must be logged in as Vendor(\(throwableId()).")
}
}
}
final class VendorController: ResourceRepresentable {
func index(_ request: Request) throws -> ResponseRepresentable {
return try request.vendor().makeJSON()
}
func show(_ request: Request, vendor: Vendor) throws -> ResponseRepresentable {
try vendor.shouldAllow(request: request)
return try vendor.makeJSON()
}
func create(_ request: Request) throws -> ResponseRepresentable {
var vendor: Vendor = try request.extractModel()
try vendor.save()
let node = try request.json().node
let username: String = try node.extract("username")
let password: String = try node.extract("password")
let usernamePassword = UsernamePassword(username: username, password: password)
try request.vendorSubject().login(credentials: usernamePassword, persist: true)
return vendor
}
func modify(_ request: Request, vendor: Vendor) throws -> ResponseRepresentable {
try vendor.shouldAllow(request: request)
var vendor: Vendor = try request.patchModel(vendor)
try vendor.save()
return try Response(status: .ok, json: vendor.makeJSON())
}
func makeResource() -> Resource<Vendor> {
return Resource(
index: index,
store: create,
show: show,
modify: modify
)
}
}
| 40af6c649c942adcdd096b661cd65a5f | 30.7 | 206 | 0.633619 | false | false | false | false |
playgroundscon/Playgrounds | refs/heads/master | Playgrounds/Controller/PresentationsThursdayDataSource.swift | gpl-3.0 | 1 | //
// ThursdayScheduleViewController.swift
// Playgrounds
//
// Created by Andyy Hope on 18/11/16.
// Copyright © 2016 Andyy Hope. All rights reserved.
//
import UIKit
final class PresentationsThursdayDataSource: NSObject {
var day: ScheduleDay = ScheduleDay(sessions: [])
}
extension PresentationsThursdayDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return day.sessions.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ScheduleSpeakerCell = tableView.dequeueReusableCell(for: indexPath)
let session = day.sessions[indexPath.section]
let speaker = session.speaker
cell.headingLabel.text = session.presentation.title
cell.subheadingLabel.text = speaker.name
cell.avatarImageView.image = UIImage(named: speaker.resource)
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mma"
let date = Date(timeIntervalSince1970: TimeInterval(day.sessions[section].time.rawValue))
return dateFormatter.string(from: date)
}
}
| dcb8f488ee9687474b9d7f49a33626dd | 31.295455 | 100 | 0.695989 | false | false | false | false |
vczhou/twitter_feed | refs/heads/master | TwitterDemo/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// TwitterDemo
//
// Created by Victoria Zhou on 2/21/17.
// Copyright © 2017 Victoria Zhou. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if User.currentUser != nil {
print("There is a current user")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "TweetsNavigationController")
window?.rootViewController = vc
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: User.userDidLogoutNotification), object: nil, queue: OperationQueue.main, using: {(Notification) -> Void in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateInitialViewController()
self.window?.rootViewController = vc
})
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
print(url.description)
TwitterClient.sharedInstance.handleOpenUrl(url: url)
return true
}
}
| e01e2b2f9770e5a3524155e1894e9442 | 45.985294 | 285 | 0.715493 | false | false | false | false |
narner/AudioKit | refs/heads/master | Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Tanh Distortion.xcplaygroundpage/Contents.swift | mit | 1 | //: ## Tanh Distortion
//: ##
//:
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: playgroundAudioFiles[0])
let player = try AKAudioPlayer(file: file)
player.looping = true
var distortion = AKTanhDistortion(player)
distortion.pregain = 1.0
distortion.postgain = 1.0
distortion.postiveShapeParameter = 1.0
distortion.negativeShapeParameter = 1.0
AudioKit.output = distortion
AudioKit.start()
player.play()
//: User Interface Set up
import AudioKitUI
class LiveView: AKLiveViewController {
override func viewDidLoad() {
addTitle("Tanh Distortion")
addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles))
addView(AKButton(title: "Stop Distortion") { button in
let node = distortion
node.isStarted ? node.stop() : node.play()
button.title = node.isStarted ? "Stop Distortion" : "Start Distortion"
})
addView(AKSlider(property: "Pre-gain", value: distortion.pregain, range: 0 ... 10) { sliderValue in
distortion.pregain = sliderValue
})
addView(AKSlider(property: "Post-gain", value: distortion.postgain, range: 0 ... 10) { sliderValue in
distortion.postgain = sliderValue
})
addView(AKSlider(property: "Postive Shape Parameter",
value: distortion.postiveShapeParameter,
range: -10 ... 10
) { sliderValue in
distortion.postiveShapeParameter = sliderValue
})
addView(AKSlider(property: "Negative Shape Parameter",
value: distortion.negativeShapeParameter,
range: -10 ... 10
) { sliderValue in
distortion.negativeShapeParameter = sliderValue
})
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| ebb735b73623fc7a8c3bf91be5815aeb | 29.984127 | 109 | 0.65625 | false | false | false | false |
jimmy54/iRime | refs/heads/master | iRime/Keyboard/tasty-imitation-keyboard/Model/DefaultKeyboard.swift | gpl-3.0 | 1 | //
// DefaultKeyboard.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/10/14.
// Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved.
//
func defaultKeyboard() -> Keyboard {
let defaultKeyboard = Keyboard()
let df = NSString.userDefaultsInGroup()
/**
* 中文输入法
*/
for key in ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 0)
}
for key in ["A", "S", "D", "F", "G", "H", "J", "K", "L"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 0)
}
var keyModel = Key(.modeChange)
keyModel.setLetter("符")
keyModel.toMode = 3
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
for key in ["Z", "X", "C", "V", "B", "N", "M"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
}
var backspace = Key(.backspace)
defaultKeyboard.addKey(backspace, row: 2, page: 0)
var keyModeChangeNumbers = Key(.modeChange)
keyModeChangeNumbers.uppercaseKeyCap = "123"
keyModeChangeNumbers.toMode = 1
defaultKeyboard.addKey(keyModeChangeNumbers, row: 3, page: 0)
var keyboardChange = Key(.keyboardChange)
defaultKeyboard.addKey(keyboardChange, row: 3, page: 0)
var settings = Key(.settings)
var enInput = Key(.modeChange)
enInput.uppercaseKeyCap = "英"
enInput.uppercaseOutput = "英"
enInput.lowercaseKeyCap = "英"
enInput.toMode = 4
defaultKeyboard.addKey(enInput, row: 3, page: 0)
let chineseInput = Key(.modeChange)
chineseInput.uppercaseKeyCap = "中"
chineseInput.uppercaseOutput = "中"
chineseInput.lowercaseKeyCap = "中"
chineseInput.toMode = 0
var spaceTitle = "中文键盘";
if let schemaId = df?.object(forKey: CURRENT_SCHEMA_NAME) {
spaceTitle = schemaId as! String;
}
spaceTitle = spaceTitle + "(⇌)"
var space = Key(.space)
space.uppercaseKeyCap = spaceTitle
space.lowercaseKeyCap = spaceTitle
space.uppercaseOutput = " "
space.lowercaseOutput = " "
defaultKeyboard.addKey(space, row: 3, page: 0)
var returnKey = Key(.return)
returnKey.uppercaseKeyCap = "return"
returnKey.uppercaseOutput = "\n"
returnKey.lowercaseOutput = "\n"
defaultKeyboard.addKey(returnKey, row: 3, page: 0)
//-------------中文符号------------------------
for key in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 3)
}
let row = cornerBracketEnabled ? ["-", "/", ":", ";", "(", ")", "$", "@", "「", "」"] : ["-", "/", ":", ";", "(", ")", "$", "@", "“", "”"]
for key in row {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
keyModel.toMode = -1
defaultKeyboard.addKey(keyModel, row: 1, page: 3)
}
var keyModeChangeSpecialCharacters = Key(.modeChange)
keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+="
keyModeChangeSpecialCharacters.toMode = 2
for key in ["。", ",", "+", "_", "、", "?", "!", ".", ","] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
keyModel.toMode = -1
defaultKeyboard.addKey(keyModel, row: 2, page: 3)
}
defaultKeyboard.addKey(Key(backspace), row: 2, page: 3)
var back = Key(.modeChange)
back.setLetter("返回")
back.toMode = -1
defaultKeyboard.addKey(back, row: 3, page: 3)
defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 3, page: 3)
space = Key(.space)
space.uppercaseKeyCap = "中文符号"
space.lowercaseKeyCap = "中文符号"
space.uppercaseOutput = " "
space.lowercaseOutput = " "
defaultKeyboard.addKey(Key(space), row: 3, page: 3)
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 3)
//--------------------------------------------
/**
* 英文键盘
*/
for key in ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 4)
}
for key in ["A", "S", "D", "F", "G", "H", "J", "K", "L"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 4)
}
keyModel = Key(.shift)
defaultKeyboard.addKey(keyModel, row: 2, page: 4)
for key in ["Z", "X", "C", "V", "B", "N", "M"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 4)
}
backspace = Key(.backspace)
defaultKeyboard.addKey(backspace, row: 2, page: 4)
back = Key(.modeChange)
back.setLetter("返回")
back.toMode = -1
defaultKeyboard.addKey(back, row: 3, page: 4)
keyModeChangeNumbers = Key(.modeChange)
keyModeChangeNumbers.uppercaseKeyCap = "123"
keyModeChangeNumbers.toMode = 1
defaultKeyboard.addKey(keyModeChangeNumbers, row: 3, page: 4)
keyModeChangeSpecialCharacters = Key(.modeChange)
keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+="
keyModeChangeSpecialCharacters.toMode = 2
defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 3, page: 4)
let dot = Key(.specialCharacter)
dot.uppercaseKeyCap = "."
dot.uppercaseOutput = "."
dot.lowercaseKeyCap = "."
dot.setLetter(".")
// defaultKeyboard.addKey(dot, row: 3, page: 4)
// keyboardChange = Key(.KeyboardChange)
// defaultKeyboard.addKey(keyboardChange, row: 3, page: 4)
// settings = Key(.Settings)
space = Key(.space)
space.uppercaseKeyCap = "英文键盘"
space.lowercaseKeyCap = "英文键盘"
space.uppercaseOutput = " "
space.lowercaseOutput = " "
defaultKeyboard.addKey(space, row: 3, page: 4)
returnKey = Key(.return)
returnKey.uppercaseKeyCap = "return"
returnKey.uppercaseOutput = "\n"
returnKey.lowercaseOutput = "\n"
defaultKeyboard.addKey(returnKey, row: 3, page: 4)
//数字键盘
for key in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 1)
}
for key in ["-", "/", ":", ";", "(", ")", "$", "&", "@", "\""] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
keyModel.toMode = -1
defaultKeyboard.addKey(keyModel, row: 1, page: 1)
}
for key in [".", ",", "。", "'", "…", "?", "!", "'", "."] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
keyModel.toMode = -1
defaultKeyboard.addKey(keyModel, row: 2, page: 1)
}
defaultKeyboard.addKey(Key(backspace), row: 2, page: 1)
// keyModeChangeLetters = Key(.ModeChange)
// keyModeChangeLetters.uppercaseKeyCap = "ABC"
// keyModeChangeLetters.toMode = 0
// defaultKeyboard.addKey(keyModeChangeLetters, row: 3, page: 1)
// defaultKeyboard.addKey(Key(chineseInput), row: 3, page: 1)
back = Key(.modeChange)
back.setLetter("返回")
back.toMode = -1
defaultKeyboard.addKey(back, row: 3, page: 1)
// defaultKeyboard.addKey(Key(enInput), row: 3, page: 1)
keyModeChangeSpecialCharacters = Key(.modeChange)
keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+="
keyModeChangeSpecialCharacters.toMode = 2
defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 3, page: 1)
space = Key(.space)
space.uppercaseKeyCap = "数字键盘"
space.lowercaseKeyCap = "数字键盘"
space.uppercaseOutput = " "
space.lowercaseOutput = " "
defaultKeyboard.addKey(Key(space), row: 3, page: 1)
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 1)
/**
* 特殊符号
*/
for key in ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
keyModel.toMode = -1
defaultKeyboard.addKey(keyModel, row: 0, page: 2)
}
for key in ["_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
keyModel.toMode = -1
defaultKeyboard.addKey(keyModel, row: 1, page: 2)
}
// defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2)
for key in [".", ",", "?", "!", "'", "……", "《", "》", "~"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
keyModel.toMode = -1
defaultKeyboard.addKey(keyModel, row: 2, page: 2)
}
defaultKeyboard.addKey(Key(backspace), row: 2, page: 2)
// defaultKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2)
// defaultKeyboard.addKey(Key(chineseInput), row: 3, page: 2)
// defaultKeyboard.addKey(Key(enInput), row: 3, page: 2)
back = Key(.modeChange)
back.setLetter("返回")
back.toMode = -1
defaultKeyboard.addKey(Key(back), row: 3, page: 2)
space = Key(.space)
space.uppercaseKeyCap = "英文符号"
space.lowercaseKeyCap = "英文符号"
space.uppercaseOutput = " "
space.lowercaseOutput = " "
defaultKeyboard.addKey(Key(space), row: 3, page: 2)
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 2)
return defaultKeyboard
}
| a39c1d08489a02eaff1912435236756b | 28.675676 | 140 | 0.573163 | false | false | false | false |
ismailbozk/DateIntervalPicker | refs/heads/master | DateIntervalPicker/DateIntervalPickerExample/SecondDemoVC.swift | mit | 1 | //
// SecondDemoVC.swift
// DateIntervalPicker
//
// Created by Ismail Bozkurt on 10/04/2016.
// The MIT License (MIT)
//
// Copyright (c) 2016 Ismail Bozkurt
//
// 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 SecondDemoVC: UIViewController, DateIntervalPickerViewDelegate {
@IBOutlet weak var beginDateLabel: UILabel!
@IBOutlet weak var endDateLabel: UILabel!
var dateIntervalPickerView: DateIntervalPickerView!
override func viewDidLoad() {
super.viewDidLoad()
self.dateIntervalPickerView = DateIntervalPickerView()
self.view.addSubview(self.dateIntervalPickerView)
self.dateIntervalPickerView.translatesAutoresizingMaskIntoConstraints = false
self.dateIntervalPickerView.ib_addTopConstraintToSuperViewWithMargin(40.0)
self.dateIntervalPickerView.ib_addLeadConstraintToSuperViewWithMargin(0.0)
self.dateIntervalPickerView.ib_addTrailingConstraintToSuperViewWithMargin(0.0)
self.dateIntervalPickerView.ib_addHeightConstraint(400.0)
self.dateIntervalPickerView.layoutIfNeeded()
self.dateIntervalPickerView.delegate = self
self.dateIntervalPickerView.startDate = NSDate()
self.dateIntervalPickerView.endDate = NSDate(timeInterval: -(60 * 60 * 24 * 2), sinceDate: NSDate())
self.dateIntervalPickerView.rangeBackgroundColor = UIColor.purpleColor()
self.dateIntervalPickerView.reload()
self.beginDateLabel.text = self.dateIntervalPickerView.startDate.description
self.endDateLabel.text = self.dateIntervalPickerView.endDate.description
}
// MARK: DateIntervalPickerViewDelegate
func dateIntervalPickerView(dateIntervalPickerView: DateIntervalPickerView, didUpdateStartDate startDate: NSDate) {
self.beginDateLabel.text = startDate.description
}
func dateIntervalPickerView(dateIntervalPickerView: DateIntervalPickerView, didUpdateEndDate endDate: NSDate) {
self.endDateLabel.text = endDate.description
}
}
| eeaadd4898827fb562d5850d3763920e | 44.735294 | 119 | 0.747588 | false | false | false | false |
RobinFalko/Ubergang | refs/heads/master | Examples/TweenApp/Pods/Ubergang/Ubergang/Ease/Bounce.swift | apache-2.0 | 1 | //
// Bounce.swift
// Ubergang
//
// Created by Robin Frielingsdorf on 07/01/16.
// Copyright © 2016 Robin Falko. All rights reserved.
//
import Foundation
open class Bounce: Ease {
/**
Bounce ease in.
- Parameter t: The value to be mapped going from 0 to `d`
- Parameter b: The mapped start value
- Parameter c: The mapped end value
- Parameter d: The end value
- Returns: The mapped result
*/
open class func easeIn(t: Double, b: Double, c: Double, d: Double) -> Double {
return c - easeOut (t: d-t, b: 0, c: c, d: d) + b
}
/**
Bounce ease out.
- Parameter t: The value to be mapped going from 0 to `d`
- Parameter b: The mapped start value
- Parameter c: The mapped end value
- Parameter d: The end value
- Returns: The mapped result
*/
open class func easeOut(t: Double, b: Double, c: Double, d: Double) -> Double {
var t = t
t/=d
if t < (1/2.75) {
return c*(7.5625*t*t) + b
} else if (t < (2/2.75)) {
t-=(1.5/2.75)
let postFix = t
return c*(7.5625*(postFix)*t + 0.75) + b
} else if (t < (2.5/2.75)) {
t-=(2.25/2.75)
let postFix = t
return c*(7.5625*(postFix)*t + 0.9375) + b
} else {
t-=(2.625/2.75)
let postFix = t
return c*(7.5625*(postFix)*t + 0.984375) + b
}
}
/**
Bounce ease in out.
- Parameter t: The value to be mapped going from 0 to `d`
- Parameter b: The mapped start value
- Parameter c: The mapped end value
- Parameter d: The end value
- Returns: The mapped result
*/
open class func easeInOut(t: Double, b: Double, c: Double, d: Double) -> Double {
if (t < d/2) { return easeIn (t: t*2, b: 0, c: c, d: d) * 0.5 + b }
else { return easeOut (t: t*2-d, b: 0, c: c, d: d) * 0.5 + c*0.5 + b }
}
}
| beaca15ab588e0b05ea2a39b432aa087 | 28.294118 | 85 | 0.51506 | false | false | false | false |
Hunter-Li-EF/HLAlbumPickerController | refs/heads/master | HLAlbumPickerController/Classes/HLAlbumGroupCell.swift | mit | 1 | //
// HLAlbumGroupCell.swift
// Pods
//
// Created by Hunter Li on 1/9/2016.
//
//
import UIKit
import Photos
internal class HLAlbumGroupCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .default
layoutMargins = UIEdgeInsets.zero
setupIcon()
setupNameLabel()
setupCountLabel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate var icon: UIImageView?
fileprivate func setupIcon(){
let icon = UIImageView()
icon.translatesAutoresizingMaskIntoConstraints = false
icon.contentMode = .scaleAspectFit
contentView.addSubview(icon)
self.icon = icon
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-8-[icon(==44)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["icon":icon]))
contentView.addConstraint(NSLayoutConstraint(item: icon, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1.0, constant: 8))
contentView.addConstraint(NSLayoutConstraint(item: icon, attribute: .width, relatedBy: .equal, toItem: icon, attribute: .height, multiplier: 1.0, constant: 0))
}
var nameLable: UILabel?
fileprivate func setupNameLabel(){
let nameLable = UILabel()
nameLable.translatesAutoresizingMaskIntoConstraints = false
nameLable.font = UIFont.systemFont(ofSize: 18)
nameLable.textColor = UIColor.darkText
contentView.addSubview(nameLable)
self.nameLable = nameLable
contentView.addConstraint(NSLayoutConstraint(item: nameLable, attribute: .left, relatedBy: .equal, toItem: icon, attribute: .right, multiplier: 1.0, constant: 8))
contentView.addConstraint(NSLayoutConstraint(item: nameLable, attribute: .top, relatedBy: .equal, toItem: icon, attribute: .top, multiplier: 1.0, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: nameLable, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1.0, constant: 0))
}
var countLable: UILabel?
fileprivate func setupCountLabel(){
let countLable = UILabel()
countLable.translatesAutoresizingMaskIntoConstraints = false
countLable.font = UIFont.systemFont(ofSize: 15)
countLable.textColor = UIColor.darkText
contentView.addSubview(countLable)
self.countLable = countLable
contentView.addConstraint(NSLayoutConstraint(item: countLable, attribute: .left, relatedBy: .equal, toItem: nameLable, attribute: .left, multiplier: 1.0, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: countLable, attribute: .bottom, relatedBy: .equal, toItem: icon, attribute: .bottom, multiplier: 1.0, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: countLable, attribute: .right, relatedBy: .equal, toItem: nameLable, attribute: .right, multiplier: 1.0, constant: 0))
}
func refreshView(_ assetGroup: PHAssetCollection?) {
guard let group = assetGroup else{
return
}
nameLable?.text = assetGroup?.localizedTitle
let results = PHAsset.fetchAssets(in: group, options: nil)
if let asset = results.firstObject {
let options = PHImageRequestOptions()
options.version = .current
options.deliveryMode = .highQualityFormat
options.resizeMode = .exact
options.isSynchronous = true
PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: 44 * UIScreen.main.scale, height: 44 * UIScreen.main.scale), contentMode: .aspectFill, options: options) { (image, mdeia) in
self.icon?.image = image
self.countLable?.text = String(results.count)
}
}
}
}
| e558c07a78788cf8b5f45280c36de5a2 | 45.146067 | 212 | 0.673971 | false | false | false | false |
apple/swift-llbuild | refs/heads/main | products/llbuildSwift/BuildValue.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright 2019 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 Swift project authors
// This file contains Swift bindings for the llbuild C API.
#if canImport(Darwin)
import Darwin.C
#elseif os(Windows)
import ucrt
import WinSDK
#elseif canImport(Glibc)
import Glibc
#else
#error("Missing libc or equivalent")
#endif
import struct Foundation.Date
// We don't need this import if we're building
// this file as part of the llbuild framework.
#if !LLBUILD_FRAMEWORK
import llbuild
#endif
extension BuildValueKind: CustomStringConvertible {
public var description: String {
switch self {
case .invalid: return "invalid"
case .virtualInput: return "virtualInput"
case .existingInput: return "existingInput"
case .missingInput: return "missingInput"
case .directoryContents: return "directoryContents"
case .directoryTreeSignature: return "directoryTreeSignature"
case .directoryTreeStructureSignature: return "directoryTreeStructureSignature"
case .staleFileRemoval: return "staleFileRemoval"
case .missingOutput: return "missingOutput"
case .failedInput: return "failedInput"
case .successfulCommand: return "successfulCommand"
case .failedCommand: return "failedCommand"
case .propagatedFailureCommand: return "propagatedFailureCommand"
case .cancelledCommand: return "cancelledCommand"
case .skippedCommand: return "skippedCommand"
case .target: return "target"
case .filteredDirectoryContents: return "filteredDirectoryContents"
case .successfulCommandWithOutputSignature: return "successfulCommandWithOutputSignature"
@unknown default:
return "unknown"
}
}
}
extension BuildValueFileInfo: Equatable {
public static func == (lhs: BuildValueFileInfo, rhs: BuildValueFileInfo) -> Bool {
return lhs.device == rhs.device && lhs.inode == rhs.inode && lhs.mode == rhs.mode && lhs.size == rhs.size && lhs.modTime == rhs.modTime
}
}
extension BuildValueFileInfo: CustomStringConvertible {
public var description: String {
return "<FileInfo device=\(device) inode=\(inode) mode=\(mode) size=\(size) modTime=\(modTime)>"
}
}
extension BuildValueFileTimestamp: Equatable {
public static func == (lhs: llb_build_value_file_timestamp_t_, rhs: BuildValueFileTimestamp) -> Bool {
return lhs.seconds == rhs.seconds && lhs.nanoseconds == rhs.nanoseconds
}
}
extension BuildValueFileTimestamp: Comparable {
public static func < (lhs: BuildValueFileTimestamp, rhs: BuildValueFileTimestamp) -> Bool {
if lhs.seconds != rhs.seconds { return lhs.seconds < rhs.seconds }
return lhs.nanoseconds < rhs.nanoseconds
}
}
extension BuildValueFileTimestamp: CustomStringConvertible {
public var description: String {
return "<FileTimestamp seconds=\(seconds) nanoseconds=\(nanoseconds)>"
}
}
public extension Date {
init(_ ft: BuildValueFileTimestamp) {
// Using reference date, instead of 1970, which offers a bit more nanosecond precision since it is a lower absolute number.
self.init(timeIntervalSinceReferenceDate: Double(ft.seconds) - Date.timeIntervalBetween1970AndReferenceDate + (1.0e-9 * Double(ft.nanoseconds)))
}
}
/// Abstract class of a build value, use subclasses
public class BuildValue: CustomStringConvertible, Equatable, Hashable {
/// Build values can be of different kind - each has its own subclass
public typealias Kind = BuildValueKind
/// Describes information about a file or directory
public typealias FileInfo = BuildValueFileInfo
/// Is part of the file info by providing a timestamp for the modifiation time
public typealias FileTimestamp = BuildValueFileTimestamp
/// Is a calculated signature of general purpose used by some of the subclasses
public typealias CommandSignature = BuildValueCommandSignature
/// The opaque pointer to the internal C++ class
fileprivate let internalBuildValue: OpaquePointer
fileprivate var owned: Bool = true
fileprivate init(_ internalBuildValue: OpaquePointer) {
self.internalBuildValue = internalBuildValue
}
/// Tries to construct a BuildValue from the given data
///
/// NOTE: If the data is malformed this code might assert.
public static func construct(from value: Value) -> BuildValue? {
var llbData = copiedDataFromBytes(value.data)
defer {
llb_data_destroy(&llbData)
}
return construct(from: llb_build_value_make(&llbData))
}
public static func construct(from buildValue: OpaquePointer) -> BuildValue? {
let kind = llb_build_value_get_kind(buildValue)
switch kind {
case .invalid: return Invalid(buildValue)
case .virtualInput: return VirtualInput(buildValue)
case .existingInput: return ExistingInput(buildValue)
case .missingInput: return MissingInput(buildValue)
case .directoryContents: return DirectoryContents(buildValue)
case .directoryTreeSignature: return DirectoryTreeSignature(buildValue)
case .directoryTreeStructureSignature: return DirectoryTreeStructureSignature(buildValue)
case .staleFileRemoval: return StaleFileRemoval(buildValue)
case .missingOutput: return MissingOutput(buildValue)
case .failedInput: return FailedInput(buildValue)
case .successfulCommand: return SuccessfulCommand(buildValue)
case .failedCommand: return FailedCommand(buildValue)
case .propagatedFailureCommand: return PropagatedFailureCommand(buildValue)
case .cancelledCommand: return CancelledCommand(buildValue)
case .skippedCommand: return SkippedCommand(buildValue)
case .target: return Target(buildValue)
case .filteredDirectoryContents: return FilteredDirectoryContents(buildValue)
case .successfulCommandWithOutputSignature: return SuccessfulCommandWithOutputSignature(buildValue)
@unknown default: return nil
}
}
deinit {
// As implemented below, ownership of the internal build value may be
// moved, thus we should only destroy it if we actually own it.
if owned {
llb_build_value_destroy(internalBuildValue)
}
}
/// Moves ownership of the internal build value object
/// This attempts to provide move semantics for uniquely owned instances to
/// prevent copy overhead. If that cannot be guaranteed, it will clone the
/// build value to ensure that the internal object remains valid for other
/// references.
static func move(_ value: inout BuildValue) -> OpaquePointer {
if isKnownUniquelyReferenced(&value) {
value.owned = false
return value.internalBuildValue
}
return llb_build_value_clone(value.internalBuildValue)
}
/// The kind of the build value.
/// The kind also defines the subclass, so kind == .invalid means the instance should be of type Invalid
public var kind: Kind {
return llb_build_value_get_kind(internalBuildValue)
}
/// The raw value data
public var valueData: ValueType {
var result = ValueType()
withUnsafeMutablePointer(to: &result) { ptr in
llb_build_value_get_value_data(internalBuildValue, ptr) { context, data in
context?.assumingMemoryBound(to: ValueType.self).pointee.append(data)
}
}
return result
}
public var description: String {
return "<BuildValue.\(type(of: self))>"
}
public static func ==(lhs: BuildValue, rhs: BuildValue) -> Bool {
return lhs.equal(to: rhs)
}
public func hash(into hasher: inout Hasher) {
hasher.combine(valueData)
}
/// This needs to be overriden in subclass if properties need to be checked
fileprivate func equal(to other: BuildValue) -> Bool {
return type(of: self) == type(of: other)
}
/// An invalid value, for sentinel purposes.
public final class Invalid: BuildValue {
public convenience init() {
self.init(llb_build_value_make_invalid())
}
}
/// A value produced by a virtual input.
public final class VirtualInput: BuildValue {
public convenience init() {
self.init(llb_build_value_make_virtual_input())
}
}
/// A value produced by an existing input file.
public final class ExistingInput: BuildValue {
public convenience init(fileInfo: BuildValueFileInfo) {
self.init(llb_build_value_make_existing_input(fileInfo))
}
/// Information about the existing input file
public var fileInfo: FileInfo {
return llb_build_value_get_output_info(internalBuildValue)
}
override func equal(to other: BuildValue) -> Bool {
return (other as? ExistingInput)?.fileInfo == fileInfo
}
public override var description: String {
return "<BuildValue.\(type(of: self)) fileInfo=\(fileInfo)>"
}
}
/// A value produced by a missing input file.
public final class MissingInput: BuildValue {
public convenience init() {
self.init(llb_build_value_make_missing_input())
}
}
/// The contents of a directory.
public final class DirectoryContents: BuildValue {
public convenience init(directoryInfo: FileInfo, contents: [String]) {
let ptr = contents.withCArrayOfStrings { ptr in
llb_build_value_make_directory_contents(directoryInfo, ptr, Int32(contents.count))
}
self.init(ptr)
}
/// The information about the directory
public var fileInfo: FileInfo {
return llb_build_value_get_output_info(internalBuildValue)
}
/// The contents of the directory
public var contents: [String] {
var result: [String] = []
withUnsafeMutablePointer(to: &result) { ptr in
llb_build_value_get_directory_contents(internalBuildValue, ptr) { ctx, data in
ctx!.assumingMemoryBound(to: [String].self).pointee.append(stringFromData(data))
}
}
return result
}
override func equal(to other: BuildValue) -> Bool {
guard let other = other as? DirectoryContents else { return false }
return fileInfo == other.fileInfo && contents == other.contents
}
public override var description: String {
return "<BuildValue.\(type(of: self)) fileInfo=\(fileInfo) contents=[\(contents.joined(separator: ", "))]>"
}
}
/// The signature of a directories contents.
public final class DirectoryTreeSignature: BuildValue {
public convenience init(signature: CommandSignature) {
self.init(llb_build_value_make_directory_tree_signature(signature))
}
/// The signature of the directory tree
public var signature: CommandSignature {
return llb_build_value_get_directory_tree_signature(internalBuildValue)
}
override func equal(to other: BuildValue) -> Bool {
guard let other = other as? DirectoryTreeSignature else { return false }
return signature == other.signature
}
public override var description: String {
return "<BuildValue.\(type(of: self)) signature=\(signature)>"
}
}
/// The signature of a directories structure.
public final class DirectoryTreeStructureSignature: BuildValue {
public convenience init(signature: CommandSignature) {
self.init(llb_build_value_make_directory_tree_structure_signature(signature))
}
/// The signature of the directory's tree structure
public var signature: CommandSignature {
return llb_build_value_get_directory_tree_structure_signature(internalBuildValue)
}
override func equal(to other: BuildValue) -> Bool {
guard let other = other as? DirectoryTreeStructureSignature else { return false }
return signature == other.signature
}
public override var description: String {
return "<BuildValue.\(type(of: self)) signature=\(signature)>"
}
}
/// A value produced by a command which succeeded, but whose output was
/// missing.
public final class MissingOutput: BuildValue {
public convenience init() {
self.init(llb_build_value_make_missing_output())
}
}
/// A value for a produced output whose command failed or was cancelled.
public final class FailedInput: BuildValue {
public convenience init() {
self.init(llb_build_value_make_failed_input())
}
}
/// A value produced by a successful command.
public final class SuccessfulCommand: BuildValue {
public convenience init(outputInfos: [FileInfo]) {
self.init(llb_build_value_make_successful_command(outputInfos, Int32(outputInfos.count)))
}
/// Information about the outputs of the command
public var outputInfos: [FileInfo] {
var result: [FileInfo] = []
withUnsafeMutablePointer(to: &result) { ptr in
llb_build_value_get_file_infos(internalBuildValue, ptr) { ctx, fileInfo in
ctx!.assumingMemoryBound(to: [FileInfo].self).pointee.append(fileInfo)
}
}
return result
}
override func equal(to other: BuildValue) -> Bool {
guard let other = other as? SuccessfulCommand else { return false }
return outputInfos == other.outputInfos
}
public override var description: String {
return "<BuildValue.\(type(of: self)) outputInfos=[\(outputInfos.map { $0.description }.joined(separator: ", "))]>"
}
}
/// A value produced by a failing command.
public final class FailedCommand: BuildValue {
public convenience init() {
self.init(llb_build_value_make_failed_command())
}
}
/// A value produced by a command which was skipped because one of its
/// dependencies failed.
public final class PropagatedFailureCommand: BuildValue {
public convenience init() {
self.init(llb_build_value_make_propagated_failure_command())
}
}
/// A value produced by a command which was cancelled.
public final class CancelledCommand: BuildValue {
public convenience init() {
self.init(llb_build_value_make_cancelled_command())
}
}
/// A value produced by a command which was skipped.
public final class SkippedCommand: BuildValue {
public convenience init() {
self.init(llb_build_value_make_skipped_command())
}
}
/// Sentinel value representing the result of "building" a top-level target.
public final class Target: BuildValue {
public convenience init() {
self.init(llb_build_value_make_target())
}
}
/// A value produced by stale file removal.
public final class StaleFileRemoval: BuildValue {
public convenience init(fileList: [String]) {
let ptr = fileList.withCArrayOfStrings { ptr in
llb_build_value_make_stale_file_removal(ptr, Int32(fileList.count))
}
self.init(ptr)
}
/// A list of the files that got removed
public var fileList: [String] {
var result: [String] = []
withUnsafeMutablePointer(to: &result) { ptr in
llb_build_value_get_stale_file_list(internalBuildValue, ptr) { ctx, data in
ctx!.assumingMemoryBound(to: [String].self).pointee.append(stringFromData(data))
}
}
return result
}
override func equal(to other: BuildValue) -> Bool {
guard let other = other as? StaleFileRemoval else { return false }
return fileList == other.fileList
}
public override var description: String {
return "<BuildValue.\(type(of: self)) fileList=[\(fileList.joined(separator: ", "))]>"
}
}
/// The filtered contents of a directory.
public final class FilteredDirectoryContents: BuildValue {
public convenience init(contents: [String]) {
let ptr = contents.withCArrayOfStrings { ptr in
llb_build_value_make_filtered_directory_contents(ptr, Int32(contents.count))
}
self.init(ptr)
}
/// The contents of the directory with the filter applied
public var contents: [String] {
var result: [String] = []
withUnsafeMutablePointer(to: &result) { ptr in
llb_build_value_get_directory_contents(internalBuildValue, ptr) { ctx, data in
ctx!.assumingMemoryBound(to: [String].self).pointee.append(stringFromData(data))
}
}
return result
}
override func equal(to other: BuildValue) -> Bool {
guard let other = other as? FilteredDirectoryContents else { return false }
return contents == other.contents
}
public override var description: String {
return "<BuildValue.\(type(of: self)) contents=[\(contents.joined(separator: ", "))]>"
}
}
/// A value produced by a successful command with an output signature.
public final class SuccessfulCommandWithOutputSignature: BuildValue {
public convenience init(outputInfos: [FileInfo], signature: CommandSignature) {
self.init(llb_build_value_make_successful_command_with_output_signature(outputInfos, Int32(outputInfos.count), signature))
}
/// Information about the outputs of the command
public var outputInfos: [FileInfo] {
var result: [FileInfo] = []
withUnsafeMutablePointer(to: &result) { ptr in
llb_build_value_get_file_infos(internalBuildValue, ptr) { ctx, fileInfo in
ctx!.assumingMemoryBound(to: [FileInfo].self).pointee.append(fileInfo)
}
}
return result
}
/// The output signature of the command
public var signature: CommandSignature {
return llb_build_value_get_output_signature(internalBuildValue)
}
override func equal(to other: BuildValue) -> Bool {
guard let other = other as? SuccessfulCommandWithOutputSignature else { return false }
return outputInfos == other.outputInfos && signature == other.signature
}
public override var description: String {
return "<BuildValue.\(type(of: self)) outputInfos=[\(outputInfos.map { $0.description }.joined(separator: ", "))] signature=\(signature)>"
}
}
}
| 7189a0d2e8337d0fbe2c3a1975f5b752 | 38.577778 | 152 | 0.642387 | false | false | false | false |
wangkai678/WKDouYuZB | refs/heads/master | WKDouYuZB/WKDouYuZB/Classes/Main/View/CollectionBaseCell.swift | mit | 1 | //
// CollectionBaseCell.swift
// WKDouYuZB
//
// Created by 王凯 on 17/5/22.
// Copyright © 2017年 wk. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionBaseCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var nickNameLabel: UILabel!
@IBOutlet weak var onlineBtn: UIButton!
//MARK: - 定义模型属性
var anchor : AnchorModel?{
didSet{
//校验模型是否有值
guard let anchor = anchor else {return}
//显示在线人数
var onlineStr : String = "";
if anchor.online >= 10000 {
onlineStr = "\(Int(anchor.online / 10000))万在线";
}else{
onlineStr = "\(anchor.online)在线";
}
onlineBtn.setTitle(onlineStr, for: .normal);
//昵称
nickNameLabel.text = anchor.nickname;
//设置封面图片
guard let iconURL = URL(string: anchor.vertical_src) else {return}
iconImageView.kf.setImage(with: ImageResource(downloadURL: iconURL));
iconImageView.kf.setImage(with: ImageResource(downloadURL: iconURL), placeholder: UIImage(named:"live_cell_default_phone"), options: nil, progressBlock: nil, completionHandler: nil)
}
}
}
| 931c83d9fa1a3a8dfbcb4b31ada7f041 | 29.093023 | 193 | 0.59119 | false | false | false | false |
objecthub/swift-lispkit | refs/heads/master | Sources/LispKit/Primitives/HashTableLibrary.swift | apache-2.0 | 1 | //
// HashTableLibrary.swift
// LispKit
//
// Created by Matthias Zenger on 18/07/2016.
// Copyright © 2016 ObjectHub. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import NumberKit
///
/// Hashtable library: based on R6RS spec.
///
public final class HashTableLibrary: NativeLibrary {
private static let equalHashProc = Procedure("equal-hash", HashTableLibrary.equalHashVal)
private static let eqvHashProc = Procedure("eqv-hash", HashTableLibrary.eqvHashVal)
private static let eqHashProc = Procedure("eq-hash", HashTableLibrary.eqHashVal)
private static let defaultCapacity = 127
private var bucketsProc: Procedure! = nil
private var bucketAddProc: Procedure! = nil
private var bucketDelProc: Procedure! = nil
private var equalProc: Procedure! = nil
private var eqvProc: Procedure! = nil
private var eqProc: Procedure! = nil
private var hashtableUnionLoc = 0
private var hashtableIntersectionLoc = 0
private var hashtableDifferenceLoc = 0
/// Name of the library.
public override class var name: [String] {
return ["lispkit", "hashtable"]
}
/// Dependencies of the library.
public override func dependencies() {
self.`import`(from: ["lispkit", "core"], "define", "lambda", "equal?", "eqv?", "eq?", "not",
"call-with-values")
self.`import`(from: ["lispkit", "control"], "let", "let*", "letrec", "if", "do")
self.`import`(from: ["lispkit", "list"], "cons", "car", "cdr", "pair?", "for-each", "value",
"null?")
self.`import`(from: ["lispkit", "math"], ">", "+", "*")
self.`import`(from: ["lispkit", "vector"], "vector-for-each")
}
/// Access to imported native procedures.
public override func initializations() {
self.equalProc = self.procedure(self.imported("equal?"))
self.eqvProc = self.procedure(self.imported("eqv?"))
self.eqProc = self.procedure(self.imported("eq?"))
}
/// Declarations of the library.
public override func declarations() {
self.bucketsProc = Procedure("_buckets", self.hBuckets)
self.bucketAddProc = Procedure("_bucket-add!", self.hBucketAdd)
self.bucketDelProc = Procedure("_bucket-repl!", self.hBucketRepl)
self.define(HashTableLibrary.equalHashProc)
self.define(HashTableLibrary.eqvHashProc)
self.define(HashTableLibrary.eqHashProc)
self.define(Procedure("_make-hashtable", makeHashTable))
self.define(Procedure("make-eq-hashtable", makeEqHashTable))
self.define(Procedure("make-eqv-hashtable", makeEqvHashTable))
self.define(Procedure("make-equal-hashtable", makeEqualHashTable))
self.define("make-hashtable", via:
"(define (make-hashtable hash eql . size)",
" (letrec ((k (if (pair? size) (car size) \(HashTableLibrary.defaultCapacity)))",
" (find (lambda (key bs)",
" (if (pair? bs)",
" (if (eql (car (car bs)) key) (car bs) (find key (cdr bs)))",
" #f)))",
" (drop (lambda (key bs)", // TODO: Use a built-in filter function for this
" (if (pair? bs)",
" (if (eql (car (car bs)) key)",
" bs",
" (let ((res (drop key (cdr bs))))",
" (cons (car res) (cons (car bs) (cdr res)))))",
" (cons #f bs)))))",
" (_make-hashtable k eql hash",
" (lambda (ht buckets key)",
" (find key (buckets ht (hash key))))",
" (lambda (ht buckets add key value)",
" (add ht (hash key) key value)",
" (if (> (hashtable-load ht) 0.75)",
" (let ((ms (buckets ht)))",
" (hashtable-clear! ht (+ (* (hashtable-size ht) 3) 1))",
" (for-each (lambda (m) (add ht (hash (car m)) (car m) (cdr m))) ms))))",
" (lambda (ht buckets replace key)",
" (let* ((h (hash key))",
" (res (drop key (buckets ht h))))",
" (replace ht h (cdr res)) (car res))))))")
self.define(Procedure("hashtable?", isHashTable))
self.define(Procedure("eq-hashtable?", isEqHashTable))
self.define(Procedure("eqv-hashtable?", isEqvHashTable))
self.define(Procedure("equal-hashtable?", isEqualHashTable))
self.define(Procedure("hashtable-mutable?", isHashTableMutable))
self.define(Procedure("hashtable-size", hashTableSize))
self.define(Procedure("hashtable-load", hashTableLoad))
self.define(Procedure("hashtable-get", hashTableGet))
self.define(Procedure("hashtable-add!", hashTableAdd))
self.define(Procedure("hashtable-remove!", hashTableRemove))
self.define("hashtable-contains?", via:
"(define (hashtable-contains? map key) (pair? (hashtable-get map key)))")
self.define("hashtable-ref", via:
"(define (hashtable-ref map key default) (value (hashtable-get map key) default))")
self.define("hashtable-set!", via:
"(define (hashtable-set! map key value)",
" (hashtable-remove! map key)(hashtable-add! map key value))")
self.define("hashtable-update!", via:
"(define (hashtable-update! map key proc default)" +
" (hashtable-add! map key (proc (value (hashtable-remove! map key) default))))")
self.define("hashtable-delete!", via:
"(define (hashtable-delete! map key)",
" (if (hashtable-remove! map key) (hashtable-delete! map key)))")
self.define(Procedure("hashtable-clear!", hashTableClear))
self.hashtableUnionLoc =
self.define("_hashtable-union!", via:
"(define (_hashtable-union! ht1 ht2)",
" (do ((ks (hashtable->alist ht2) (cdr ks)))",
" ((null? ks))",
" (if (not (hashtable-contains? ht1 (car (car ks))))",
" (hashtable-add! ht1 (car (car ks)) (cdr (car ks))))))")
self.hashtableIntersectionLoc =
self.define("_hashtable-intersection!", via:
"(define (_hashtable-intersection! ht1 ht2)",
" (do ((ks (hashtable->alist ht1) (cdr ks)))",
" ((null? ks))",
" (if (not (hashtable-contains? ht2 (car (car ks))))",
" (hashtable-delete! ht1 (car (car ks))))))")
self.hashtableDifferenceLoc =
self.define("_hashtable-difference!", via:
"(define (_hashtable-difference! ht1 ht2)",
" (do ((ks (hashtable->alist ht1) (cdr ks)))",
" ((null? ks))",
" (if (hashtable-contains? ht2 (car (car ks)))",
" (hashtable-delete! ht1 (car (car ks))))))")
self.define(Procedure("hashtable-union!", hashTableUnion))
self.define(Procedure("hashtable-intersection!", hashTableIntersection))
self.define(Procedure("hashtable-difference!", hashTableDifference))
self.define(Procedure("hashtable-copy", hashTableCopy))
self.define(Procedure("hashtable-keys", hashTableKeys))
self.define(Procedure("hashtable-values", hashTableValues))
self.define(Procedure("hashtable-entries", hashTableEntries))
self.define(Procedure("hashtable-key-list", hashTableKeyList))
self.define(Procedure("hashtable-value-list", hashTableValueList))
self.define("hashtable-for-each", via:
"(define (hashtable-for-each proc ht)",
" (call-with-values",
" (lambda () (hashtable-entries ht))",
" (lambda (keys vals) (vector-for-each proc keys vals))))")
self.define("hashtable-map!", via:
"(define (hashtable-map! proc ht)",
" (call-with-values",
" (lambda () (let ((res (hashtable-entries ht))) (hashtable-clear! ht) res))",
" (lambda (keys vals)",
" (vector-for-each (lambda (key value) (hashtable-add! ht key (proc key value)))",
" keys vals))))")
self.define(Procedure("hashtable->alist", hashTableToAlist))
self.define("alist->hashtable!", via:
"(define (alist->hashtable! hm alist)",
" (for-each (lambda (m) (hashtable-add! hm (car m) (cdr m))) alist))")
self.define(Procedure("alist->eq-hashtable", alistToEqHashTable))
self.define(Procedure("alist->eqv-hashtable", alistToEqvHashTable))
self.define(Procedure("alist->equal-hashtable", alistToEqualHashTable))
self.define(Procedure("hashtable-equivalence-function", hashTableEquivalenceFunction))
self.define(Procedure("hashtable-hash-function", hashTableHashFunction))
self.define(Procedure("boolean-hash", booleanHashVal))
self.define(Procedure("char-hash", charHashVal))
self.define(Procedure("char-ci-hash", charCiHashVal))
self.define(Procedure("string-hash", stringHashVal))
self.define(Procedure("string-ci-hash", stringCiHashVal))
self.define(Procedure("symbol-hash", symbolHashVal))
self.define(Procedure("number-hash", numberHashVal))
self.define(Procedure("combine-hash", combineHash))
self.define("hashtable-empty-copy", via:
"(define (hashtable-empty-copy ht)",
" (make-hashtable (hashtable-hash-function ht #t) (hashtable-equivalence-function ht)))")
}
func makeHashTable(_ capacity: Expr, _ eql: Expr, _ hsh: Expr, _ args: Arguments) throws -> Expr {
guard args.count == 3 else {
throw RuntimeError.argumentCount(
of: "make-hashtable",
min: 6,
max: 6,
args: .pair(capacity, .pair(eql, .pair(hsh, .makeList(args)))))
}
let numBuckets = try capacity.asInt()
let eqlProc = try eql.asProcedure()
let hshProc = try hsh.asProcedure()
if eqlProc == self.equalProc && hshProc == HashTableLibrary.equalHashProc {
return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .equal))
} else if eqlProc == self.eqvProc && hshProc == HashTableLibrary.eqvHashProc {
return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .eqv))
} else if eqlProc == self.eqProc && hshProc == HashTableLibrary.eqHashProc {
return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .eq))
} else {
let procs = HashTable.CustomProcedures(eql: eqlProc,
hsh: hshProc,
get: try args[args.startIndex].asProcedure(),
add: try args[args.startIndex + 1].asProcedure(),
del: try args[args.startIndex + 2].asProcedure())
return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .custom(procs)))
}
}
func makeEqHashTable(_ capacity: Expr?) throws -> Expr {
let numBuckets = try capacity?.asInt() ?? HashTableLibrary.defaultCapacity
return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .eq))
}
func makeEqvHashTable(_ capacity: Expr?) throws -> Expr {
let numBuckets = try capacity?.asInt() ?? HashTableLibrary.defaultCapacity
return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .eqv))
}
func makeEqualHashTable(_ capacity: Expr?) throws -> Expr {
let numBuckets = try capacity?.asInt() ?? HashTableLibrary.defaultCapacity
return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .equal))
}
func isHashTable(_ expr: Expr) -> Expr {
guard case .table(_) = expr else {
return .false
}
return .true
}
func isEqHashTable(_ expr: Expr) -> Expr {
guard case .table(let table) = expr,
case .eq = table.equiv else {
return .false
}
return .true
}
func isEqvHashTable(_ expr: Expr) -> Expr {
guard case .table(let table) = expr,
case .eqv = table.equiv else {
return .false
}
return .true
}
func isEqualHashTable(_ expr: Expr) -> Expr {
guard case .table(let table) = expr,
case .equal = table.equiv else {
return .false
}
return .true
}
func isHashTableMutable(_ expr: Expr) -> Expr {
guard case .table(let table) = expr else {
return .false
}
return .makeBoolean(table.mutable)
}
func hashTableSize(_ expr: Expr) throws -> Expr {
return .fixnum(Int64(try expr.asHashTable().count))
}
func hashTableLoad(_ expr: Expr) throws -> Expr {
let map = try expr.asHashTable()
return .makeNumber(Double(map.count) / Double(map.bucketCount))
}
func hashTableGet(_ args: Arguments) throws -> (Procedure, Exprs) {
try EvalError.assert(args, count: 2)
let map = try args[args.startIndex].asHashTable()
let key = args[args.startIndex + 1]
guard case .custom(let procs) = map.equiv else {
return (CoreLibrary.idProc, [map.get(key) ?? .false])
}
return (procs.get, [.table(map), .procedure(self.bucketsProc), key])
}
func hashTableAdd(_ args: Arguments) throws -> (Procedure, Exprs) {
try EvalError.assert(args, count: 3)
let map = try args.first!.asHashTable()
let key = args[args.startIndex + 1]
let value = args[args.startIndex + 2]
guard map.mutable else {
throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map))
}
guard case .custom(let procs) = map.equiv else {
guard map.add(key: key, mapsTo: value) else {
preconditionFailure("trying to set mapping in immutable hash map")
}
return (CoreLibrary.idProc, [.void])
}
return (procs.add, [.table(map),
.procedure(self.bucketsProc),
.procedure(self.bucketAddProc),
key,
value])
}
func hashTableRemove(_ args: Arguments) throws -> (Procedure, Exprs) {
try EvalError.assert(args, count: 2)
let map = try args.first!.asHashTable()
let key = args[args.startIndex + 1]
guard map.mutable else {
throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map))
}
guard case .custom(let procs) = map.equiv else {
guard let res = map.remove(key: key) else {
preconditionFailure("trying to delete mapping in immutable hash map")
}
return (CoreLibrary.idProc, [res])
}
return (procs.del, [.table(map),
.procedure(self.bucketsProc),
.procedure(self.bucketDelProc),
key])
}
func hashTableCopy(_ expr: Expr, mutable: Expr?) throws -> Expr {
let map = try expr.asHashTable()
return .table(HashTable(copy: map, mutable: mutable == .true))
}
func hashTableClear(_ expr: Expr, k: Expr?) throws -> Expr {
let map = try expr.asHashTable()
guard map.mutable else {
throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map))
}
guard try map.clear(k?.asInt()) else {
preconditionFailure("trying to clear immutable hash map")
}
return .void
}
func hashTableUnion(_ args: Arguments) throws -> (Procedure, Exprs) {
try EvalError.assert(args, count: 2)
let map1 = try args.first!.asHashTable()
let map2 = try args[args.startIndex + 1].asHashTable()
guard map1.mutable else {
throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map1))
}
guard case .custom(_) = map1.equiv else {
guard map1.union(map2) else {
preconditionFailure("trying to union mapping with immutable hash map")
}
return (CoreLibrary.voidProc, [])
}
return (self.procedure(self.hashtableUnionLoc), [.table(map1), .table(map2)])
}
func hashTableIntersection(_ args: Arguments) throws -> (Procedure, Exprs) {
try EvalError.assert(args, count: 2)
let map1 = try args.first!.asHashTable()
let map2 = try args[args.startIndex + 1].asHashTable()
guard map1.mutable else {
throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map1))
}
guard case .custom(_) = map1.equiv else {
guard map1.difference(map2, intersect: true) else {
preconditionFailure("trying to intersect mapping with immutable hash map")
}
return (CoreLibrary.voidProc, [])
}
return (self.procedure(self.hashtableIntersectionLoc), [.table(map1), .table(map2)])
}
func hashTableDifference(_ args: Arguments) throws -> (Procedure, Exprs) {
try EvalError.assert(args, count: 2)
let map1 = try args.first!.asHashTable()
let map2 = try args[args.startIndex + 1].asHashTable()
guard map1.mutable else {
throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map1))
}
guard case .custom(_) = map1.equiv else {
guard map1.difference(map2, intersect: false) else {
preconditionFailure("trying to compute difference with immutable hash map")
}
return (CoreLibrary.voidProc, [])
}
return (self.procedure(self.hashtableDifferenceLoc), [.table(map1), .table(map2)])
}
func hashTableKeys(_ expr: Expr) throws -> Expr {
return .vector(Collection(kind: .immutableVector, exprs: try expr.asHashTable().keys))
}
func hashTableValues(_ expr: Expr) throws -> Expr {
return .vector(Collection(kind: .immutableVector, exprs: try expr.asHashTable().values))
}
func hashTableEntries(_ expr: Expr) throws -> Expr {
return .values(
.pair(.vector(Collection(kind: .immutableVector, exprs: try expr.asHashTable().keys)),
.pair(.vector(Collection(kind: .immutableVector, exprs: try expr.asHashTable().values)),
.null)))
}
func hashTableKeyList(_ expr: Expr) throws -> Expr {
return try expr.asHashTable().keyList()
}
func hashTableValueList(_ expr: Expr) throws -> Expr {
return try expr.asHashTable().valueList()
}
func hashTableToAlist(_ expr: Expr) throws -> Expr {
return try expr.asHashTable().entryList()
}
private func newHashTable(_ equiv: HashTable.Equivalence, capacity: Int?) -> HashTable {
let numBuckets = capacity ?? HashTableLibrary.defaultCapacity
return HashTable(capacity: numBuckets, mutable: true, equiv: equiv)
}
private func enterAlist(_ expr: Expr, into map: HashTable) throws {
var list = expr
while case .pair(.pair(let key, let value), let cdr) = list {
map.add(key: key, mapsTo: value)
list = cdr
}
guard list.isNull else {
throw RuntimeError.type(expr, expected: [.assocListType])
}
}
func alistToEqHashTable(_ expr: Expr, capacity: Expr?) throws -> Expr {
let table = self.newHashTable(.eq, capacity: try capacity?.asInt())
try self.enterAlist(expr, into: table)
return .table(table)
}
func alistToEqvHashTable(_ expr: Expr, capacity: Expr?) throws -> Expr {
let table = self.newHashTable(.eqv, capacity: try capacity?.asInt())
try self.enterAlist(expr, into: table)
return .table(table)
}
func alistToEqualHashTable(_ expr: Expr, capacity: Expr?) throws -> Expr {
let table = self.newHashTable(.equal, capacity: try capacity?.asInt())
try self.enterAlist(expr, into: table)
return .table(table)
}
func hashTableEquivalenceFunction(_ expr: Expr) throws -> Expr {
switch try expr.asHashTable().equiv {
case .eq:
return .procedure(self.eqProc)
case .eqv:
return .procedure(self.eqvProc)
case .equal:
return .procedure(self.equalProc)
case .custom(let procs):
return .procedure(procs.eql)
}
}
func hashTableHashFunction(_ expr: Expr, _ force: Expr?) throws -> Expr {
switch try expr.asHashTable().equiv {
case .eq:
return (force?.isTrue ?? false) ? .procedure(HashTableLibrary.eqHashProc) : .false
case .eqv:
return (force?.isTrue ?? false) ? .procedure(HashTableLibrary.eqvHashProc) : .false
case .equal:
return .procedure(HashTableLibrary.equalHashProc)
case .custom(let procs):
return .procedure(procs.hsh)
}
}
private static func eqHashVal(_ expr: Expr) -> Expr {
return .fixnum(Int64(eqHash(expr)))
}
private static func eqvHashVal(_ expr: Expr) -> Expr {
return .fixnum(Int64(eqvHash(expr)))
}
private static func equalHashVal(_ expr: Expr) -> Expr {
return .fixnum(Int64(equalHash(expr)))
}
private func booleanHashVal(_ expr: Expr) -> Expr {
return .fixnum(Int64(expr.isTrue.hashValue))
}
private func numberHashVal(_ expr: Expr) throws -> Expr {
switch expr {
case .fixnum(let num):
return .fixnum(Int64(num.hashValue))
case .bignum(let num):
return .fixnum(Int64(num.hashValue))
case .rational(let n, let d):
var hasher = Hasher()
hasher.combine(n)
hasher.combine(d)
return .fixnum(Int64(hasher.finalize()))
case .flonum(let num):
return .fixnum(Int64(num.hashValue))
case .complex(let num):
return .fixnum(Int64(num.hashValue))
default:
throw RuntimeError.type(expr, expected: [.numberType])
}
}
private func charHashVal(_ expr: Expr) throws -> Expr {
guard case .char(_) = expr else {
throw RuntimeError.type(expr, expected: [.charType])
}
return .fixnum(Int64(expr.hashValue))
}
private func charCiHashVal(_ expr: Expr) throws -> Expr {
return .fixnum(Int64(try expr.charAsString().lowercased().hashValue))
}
private func stringHashVal(_ expr: Expr) throws -> Expr {
guard case .string(_) = expr else {
throw RuntimeError.type(expr, expected: [.strType])
}
return .fixnum(Int64(expr.hashValue))
}
private func stringCiHashVal(_ expr: Expr) throws -> Expr {
guard case .string(let str) = expr else {
throw RuntimeError.type(expr, expected: [.strType])
}
return .fixnum(Int64(str.lowercased.hashValue))
}
private func symbolHashVal(_ expr: Expr) throws -> Expr {
guard case .symbol(_) = expr else {
throw RuntimeError.type(expr, expected: [.symbolType])
}
return .fixnum(Int64(expr.hashValue))
}
private func combineHash(_ args: Arguments) throws -> Expr {
var hasher = Hasher()
for arg in args {
hasher.combine(try arg.asInt64())
}
return .fixnum(Int64(hasher.finalize()))
}
private func bucket(_ hval: Expr, _ numBuckets: Int) throws -> Int {
switch hval {
case .fixnum(let num):
return Int(num %% Int64(numBuckets))
case .bignum(let num):
let n = BigInt(numBuckets)
let rem = num % n
return Int(rem.isNegative ? (rem + n).intValue! : rem.intValue!)
default:
throw RuntimeError.type(hval, expected: [.exactIntegerType])
}
}
private func hBuckets(_ expr: Expr, hval: Expr?) throws -> Expr {
let map = try expr.asHashTable()
if let hashValue = hval {
return map.bucketList(try self.bucket(hashValue, map.bucketCount))
} else {
return map.bucketList()
}
}
private func hBucketAdd(_ expr: Expr, hval: Expr, key: Expr, value: Expr) throws -> Expr {
guard case .table(let map) = expr else {
throw RuntimeError.type(expr, expected: [.tableType])
}
if !key.isAtom || !value.isAtom {
self.context.objects.manage(map)
}
map.add(try self.bucket(hval, map.bucketCount), key, value)
return .void
}
private func hBucketRepl(_ expr: Expr, hval: Expr, bucket: Expr) throws -> Expr {
guard case .table(let map) = expr else {
throw RuntimeError.type(expr, expected: [.tableType])
}
map.replace(try self.bucket(hval, map.bucketCount), bucket)
return .void
}
public override func release() {
super.release()
self.bucketsProc = nil
self.bucketAddProc = nil
self.bucketDelProc = nil
self.equalProc = nil
self.eqvProc = nil
self.eqProc = nil
}
}
| 7332c3dd0291237e116f63450e2b7067 | 38.542484 | 100 | 0.626736 | false | false | false | false |
mdab121/swift-fcm | refs/heads/master | Sources/FCM/Firebase.swift | mit | 1 | // (c) 2017 Kajetan Michal Dabrowski
// This code is licensed under MIT license (see LICENSE for details)
import Foundation
/// This is the main class that you should be using to send notifications
public class Firebase {
/// Set this to true if you want your requests to be performed in the background.
/// Defaults to false, since I don't think it's been tested enough
/// Please do not change this after pushing notifications
internal var backgroundMode: Bool = false
/// The server key
internal let serverKey: ServerKey
private let serializer: MessageSerializer = MessageSerializer()
private let pushUrl: URL = URL(string: "https://fcm.googleapis.com/fcm/send")!
private let requestAdapter: RequestAdapting = RequestAdapterCurl()
private lazy var backgroundQueue = OperationQueue()
private var requestQueue: OperationQueue {
return backgroundMode ? backgroundQueue : (OperationQueue.current ?? OperationQueue.main)
}
/// Convenience initializer taking a path to a file where the key is stored.
///
/// - Parameter keyPath: Path to the Firebase Server Key
/// - Throws: Throws an error if file doesn't exist
public convenience init(keyPath: String) throws {
let fileManager = FileManager()
guard let keyData = fileManager.contents(atPath: keyPath),
let keyString = String(data: keyData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) else {
throw FirebaseError.invalidServerKey
}
self.init(serverKey: ServerKey(rawValue: keyString))
}
/// Initializes FCM with the key as the parameter. Please note that you should NOT store your server key in the source code and in your repository.
/// Instead, fetch your key from some configuration files, that are not stored in your repository.
///
/// - Parameter serverKey: server key
public init(serverKey: ServerKey) {
self.serverKey = serverKey
}
/// Sends a single message to a single device. After sending it calls the completion closure on the queue that it was called from.
///
/// - Parameters:
/// - message: The message that you want to send
/// - deviceToken: Firebase Device Token that you want to send your message to
/// - completion: completion closure
/// - Throws: Serialization error when the message could not be serialized
public func send(message: Message, to deviceToken: DeviceToken, completion: @escaping (FirebaseResponse) -> Void) throws {
let requestBytes: [UInt8] = try serializer.serialize(message: message, device: deviceToken)
let requestData = Data(requestBytes)
let requestHeaders = generateHeaders()
let url = pushUrl
let completionQueue = OperationQueue.current ?? OperationQueue.main
let requestAdapter = self.requestAdapter
requestQueue.addOperation {
do {
try requestAdapter.send(data: requestData, headers: requestHeaders, url: url) { (data, statusCode, error) in
let response = FirebaseResponse(data: data, statusCode: statusCode, error: error)
completionQueue.addOperation { completion(response) }
}
} catch {
let response = FirebaseResponse(data: nil, statusCode: nil, error: error)
completionQueue.addOperation { completion(response) }
}
}
}
// MARK: Private methods
private func generateHeaders() -> [String: String] {
return [
"Content-Type": "application/json",
"Authorization": "key=\(serverKey.rawValue)"
]
}
}
| 0961ccebadc9e961c7bc4abd71b71430 | 38.482353 | 148 | 0.739869 | false | false | false | false |
calebd/swift | refs/heads/master | test/attr/accessibility_print.swift | apache-2.0 | 8 | // RUN: %empty-directory(%t)
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -print-accessibility -source-filename=%s | %FileCheck %s -check-prefix=CHECK -check-prefix=CHECK-SRC
// RUN: %target-swift-frontend -emit-module-path %t/accessibility_print.swiftmodule %s
// RUN: %target-swift-ide-test -skip-deinit=false -print-module -print-accessibility -module-to-print=accessibility_print -I %t -source-filename=%s | %FileCheck %s
// This file uses alphabetic prefixes on its declarations because swift-ide-test
// sorts decls in a module before printing them.
// CHECK-LABEL: internal var AA_defaultGlobal
var AA_defaultGlobal = 0
// CHECK: {{^}}private{{(\*/)?}} var AB_privateGlobal
// CHECK: {{^}}internal{{(\*/)?}} var AC_internalGlobal
// CHECK: {{^}}public{{(\*/)?}} var AD_publicGlobal
// CHECK: {{^}}fileprivate{{(\*/)?}} var AE_fileprivateGlobal
private var AB_privateGlobal = 0
internal var AC_internalGlobal = 0
public var AD_publicGlobal = 0
fileprivate var AE_fileprivateGlobal = 0
// CHECK-LABEL: internal struct BA_DefaultStruct {
struct BA_DefaultStruct {
// CHECK: internal let x
let x = 0
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} struct BB_PrivateStruct {
private struct BB_PrivateStruct {
// CHECK: internal var x
var x = 0
// CHECK: internal init(x: Int)
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: internal{{(\*/)?}} struct BC_InternalStruct {
internal struct BC_InternalStruct {
// CHECK: internal let x
let x = 0
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} struct BD_PublicStruct {
public struct BD_PublicStruct {
// CHECK: internal var x
var x = 0
// CHECK: internal init(x: Int)
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} struct BE_PublicStructPrivateMembers {
public struct BE_PublicStructPrivateMembers {
// CHECK: private{{(\*/)?}} var x
private var x = 0
// CHECK: private init(x: Int)
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: {{^}}fileprivate{{(\*/)?}} struct BF_FilePrivateStruct {
fileprivate struct BF_FilePrivateStruct {
// CHECK: {{^}} internal var x
var x = 0
// CHECK: {{^}} internal init(x: Int)
// CHECK: {{^}} internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} class CA_PrivateClass
private class CA_PrivateClass {
// CHECK: {{^}} deinit
deinit {}
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: internal{{(\*/)?}} class CB_InternalClass
internal class CB_InternalClass {
// CHECK: {{^}} deinit
deinit {}
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} class CC_PublicClass
public class CC_PublicClass {
// CHECK: {{^}} deinit
deinit {}
// CHECK: internal init()
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} enum DA_PrivateEnum {
private enum DA_PrivateEnum {
// CHECK: {{^}} case Foo
// CHECK: Bar
case Foo, Bar
// CHECK: internal init()
init() { self = .Foo }
// CHECK: internal var hashValue
} // CHECK: {{^[}]}}
// CHECK-LABEL: internal{{(\*/)?}} enum DB_InternalEnum {
internal enum DB_InternalEnum {
// CHECK: {{^}} case Foo
// CHECK: Bar
case Foo, Bar
// CHECK: internal init()
init() { self = .Foo }
// CHECK: internal var hashValue
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} enum DC_PublicEnum {
public enum DC_PublicEnum {
// CHECK: {{^}} case Foo
// CHECK: Bar
case Foo, Bar
// CHECK: internal init()
init() { self = .Foo }
// CHECK: public var hashValue
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} protocol EA_PrivateProtocol {
private protocol EA_PrivateProtocol {
// CHECK: {{^}} associatedtype Foo
associatedtype Foo
// CHECK: fileprivate var Bar
var Bar: Int { get }
// CHECK: fileprivate func baz()
func baz()
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} protocol EB_PublicProtocol {
public protocol EB_PublicProtocol {
// CHECK: {{^}} associatedtype Foo
associatedtype Foo
// CHECK: public var Bar
var Bar: Int { get }
// CHECK: public func baz()
func baz()
} // CHECK: {{^[}]}}
private class FA_PrivateClass {}
internal class FB_InternalClass {}
public class FC_PublicClass {}
// CHECK-SRC: {{^}}ex
// CHECK-LABEL: tension FA_PrivateClass {
extension FA_PrivateClass {
// CHECK: internal func a()
func a() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension FB_InternalClass {
extension FB_InternalClass {
// CHECK: internal func a()
func a() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension FC_PublicClass {
extension FC_PublicClass {
// CHECK: internal func a()
func a() {}
} // CHECK: {{^[}]}}
private class FD_PrivateClass {}
// CHECK-SRC: private
// CHECK-LABEL: extension FD_PrivateClass {
private extension FD_PrivateClass {
// CHECK: private func explicitPrivateExt()
func explicitPrivateExt() {}
} // CHECK: {{^[}]}}
public class FE_PublicClass {}
// CHECK-SRC: private
// CHECK-LABEL: extension FE_PublicClass {
private extension FE_PublicClass {
// CHECK: private func explicitPrivateExt()
func explicitPrivateExt() {}
// CHECK: private struct PrivateNested {
struct PrivateNested {
// CHECK: internal var x
var x: Int
} // CHECK: }
} // CHECK: {{^[}]}}
// CHECK-SRC: internal
// CHECK-LABEL: extension FE_PublicClass {
internal extension FE_PublicClass {
// CHECK: internal func explicitInternalExt()
func explicitInternalExt() {}
// CHECK: internal struct InternalNested {
struct InternalNested {
// CHECK: internal var x
var x: Int
} // CHECK: }
} // CHECK: {{^[}]}}
// CHECK-SRC: public
// CHECK-LABEL: extension FE_PublicClass {
public extension FE_PublicClass {
// CHECK: public func explicitPublicExt()
func explicitPublicExt() {}
// CHECK: public struct PublicNested {
struct PublicNested {
// CHECK: internal var x
var x: Int
} // CHECK: }
} // CHECK: {{^[}]}}
// CHECK-LABEL: internal func GA_localTypes()
func GA_localTypes() {
// CHECK-SRC: private struct Local {
struct Local {
// CHECK-SRC: internal let x
let x = 0
}
_ = Local()
// CHECK-SRC: private enum LocalEnum {
enum LocalEnum {
// CHECK-SRC: {{^}} case A
case A, B
}
let enumVal = LocalEnum.A
_ = (enumVal == .B)
} // CHECK-SRC: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} struct GB_NestedOuter {
public struct GB_NestedOuter {
// CHECK: internal struct Inner {
struct Inner {
// CHECK: private{{(\*/)?}} let x
private let x = 0
// CHECK: internal let y
let y = 0
}
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} struct GC_NestedOuterPrivate {
private struct GC_NestedOuterPrivate {
// CHECK: internal struct Inner {
struct Inner {
// CHECK: private{{(\*/)?}} let x
private let x = 0
// CHECK: internal let y
let y = 0
}
} // CHECK: {{^[}]}}
public protocol HA_PublicProtocol {
associatedtype Assoc
}
internal protocol HB_InternalProtocol {
associatedtype Assoc
}
private protocol HC_PrivateProtocol {
associatedtype Assoc
}
public struct HA_PublicStruct {}
internal struct HB_InternalStruct {}
private struct HC_PrivateStruct {}
// CHECK-LABEL: extension HA_PublicProtocol {
extension HA_PublicProtocol {
// CHECK: internal func unconstrained()
func unconstrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HA_PublicProtocol where Self.Assoc == HA_PublicStruct {
extension HA_PublicProtocol where Assoc == HA_PublicStruct {
// CHECK: internal func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HA_PublicProtocol where Self.Assoc == HB_InternalStruct {
extension HA_PublicProtocol where Assoc == HB_InternalStruct {
// CHECK: internal func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HA_PublicProtocol where Self.Assoc == HC_PrivateStruct {
extension HA_PublicProtocol where Assoc == HC_PrivateStruct {
// CHECK: private func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HB_InternalProtocol {
extension HB_InternalProtocol {
// CHECK: internal func unconstrained()
func unconstrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HB_InternalProtocol where Self.Assoc == HA_PublicStruct {
extension HB_InternalProtocol where Assoc == HA_PublicStruct {
// CHECK: internal func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HB_InternalProtocol where Self.Assoc == HB_InternalStruct {
extension HB_InternalProtocol where Assoc == HB_InternalStruct {
// CHECK: internal func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HB_InternalProtocol where Self.Assoc == HC_PrivateStruct {
extension HB_InternalProtocol where Assoc == HC_PrivateStruct {
// CHECK: private func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HC_PrivateProtocol {
extension HC_PrivateProtocol {
// CHECK: internal func unconstrained()
func unconstrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HC_PrivateProtocol where Self.Assoc == HA_PublicStruct {
extension HC_PrivateProtocol where Assoc == HA_PublicStruct {
// CHECK: private func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HC_PrivateProtocol where Self.Assoc == HB_InternalStruct {
extension HC_PrivateProtocol where Assoc == HB_InternalStruct {
// CHECK: private func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: extension HC_PrivateProtocol where Self.Assoc == HC_PrivateStruct {
extension HC_PrivateProtocol where Assoc == HC_PrivateStruct {
// CHECK: private func constrained()
func constrained() {}
} // CHECK: {{^[}]}}
public protocol IA_PublicAssocTypeProto {
associatedtype PublicValue
var publicValue: PublicValue { get }
}
fileprivate protocol IB_FilePrivateAssocTypeProto {
associatedtype FilePrivateValue
var filePrivateValue: FilePrivateValue { get }
}
// CHECK-LABEL: public{{(\*/)?}} class IC_PublicAssocTypeImpl : IA_PublicAssocTypeProto, IB_FilePrivateAssocTypeProto {
public class IC_PublicAssocTypeImpl: IA_PublicAssocTypeProto, IB_FilePrivateAssocTypeProto {
public var publicValue: Int = 0
public var filePrivateValue: Int = 0
// CHECK-DAG: {{^}} public typealias PublicValue
// CHECK-DAG: {{^}} public typealias FilePrivateValue
} // CHECK: {{^[}]}}
// CHECK-LABEL: private{{(\*/)?}} class ID_PrivateAssocTypeImpl : IA_PublicAssocTypeProto, IB_FilePrivateAssocTypeProto {
private class ID_PrivateAssocTypeImpl: IA_PublicAssocTypeProto, IB_FilePrivateAssocTypeProto {
public var publicValue: Int = 0
public var filePrivateValue: Int = 0
// CHECK-DAG: {{^}} internal typealias PublicValue
// CHECK-DAG: {{^}} internal typealias FilePrivateValue
} // CHECK: {{^[}]}}
// CHECK-LABEL: class MultipleAttributes {
class MultipleAttributes {
// CHECK: {{^}} final {{(/\*)?private(\*/)?}} func foo()
final private func foo() {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} class PublicInitBase {
public class PublicInitBase {
// CHECK: {{^}} {{(/\*)?public(\*/)?}} init()
public init() {}
// CHECK: {{^}} {{(/\*)?fileprivate(\*/)?}} init(other: PublicInitBase)
fileprivate init(other: PublicInitBase) {}
} // CHECK: {{^[}]}}
// CHECK-LABEL: public{{(\*/)?}} class PublicInitInheritor : PublicInitBase {
public class PublicInitInheritor : PublicInitBase {
// CHECK: {{^}} public init()
// CHECK: {{^}} fileprivate init(other: PublicInitBase)
} // CHECK: {{^[}]}}
// CHECK-LABEL: {{(/\*)?private(\*/)?}} class PublicInitPrivateInheritor : PublicInitBase {
private class PublicInitPrivateInheritor : PublicInitBase {
// CHECK: {{^}} internal init()
// CHECK: {{^}} fileprivate init(other: PublicInitBase)
} // CHECK: {{^[}]}}
| 451d3d67e347962f9dcbfb2596f0361d | 30.396277 | 173 | 0.657687 | false | false | false | false |
Allow2CEO/browser-ios | refs/heads/development | Utils/AboutUtils.swift | mpl-2.0 | 2 | /* 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
struct AboutUtils {
fileprivate static let AboutPath = "/about/"
static func isAboutHomeURL(_ url: URL?) -> Bool {
return getAboutComponent(url) == "home"
}
static func isAboutURL(_ url: URL?) -> Bool {
if let scheme = url?.scheme, scheme == "about" {
return true
}
return getAboutComponent(url) != nil
}
/// If the URI is an about: URI, return the path after "about/" in the URI.
/// For example, return "home" for "http://localhost:1234/about/home/#panel=0".
static func getAboutComponent(_ url: URL?) -> String? {
if let scheme = url?.scheme, let host = url?.host, let path = url?.path {
if scheme == "http" && host == "localhost" && path.startsWith(AboutPath) {
return path.substring(from: AboutPath.endIndex)
}
}
return nil
}
}
| 0ffbf8b522126f5ae8ddd87ddbdc7170 | 33.5625 | 86 | 0.601266 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro | refs/heads/master | Parse Dashboard for iOS/ViewControllers/Core/Object/ObjectBuilderViewController.swift | mit | 1 | //
// ObjectBuilderViewController.swift
// Parse Dashboard for iOS
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 12/17/17.
//
import UIKit
import AlertHUDKit
import Former
import SwiftyJSON
class ObjectBuilderViewController: FormViewController {
// MARK: - Properties
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
private var body = JSON()
private let schema: PFSchema
private lazy var formerInputAccessoryView = FormerInputAccessoryView(former: self.former)
lazy var moreSection: SectionFormer = {
let addFieldRow = LabelRowFormer<FormLabelCell>() {
$0.titleLabel.font = .boldSystemFont(ofSize: 15)
$0.titleLabel.textColor = .logoTint
}.configure {
$0.text = "Add Field"
}.onSelected { [weak self] _ in
self?.former.deselect(animated: true)
self?.addField()
}
return SectionFormer(rowFormer: addFieldRow)
}()
// MARK: - Initialization
init(for schema: PFSchema) {
self.schema = schema
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
setupNavigationBar()
buildForm()
}
// MARK: - View Setup
private func setupTableView() {
tableView.contentInset.top = 10
tableView.contentInset.bottom = 80
}
private func setupNavigationBar() {
title = "New \(schema.name) Object"
navigationController?.navigationBar.barTintColor = .darkPurpleBackground
navigationController?.navigationBar.tintColor = .white
navigationController?.navigationBar.titleTextAttributes = [
NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 15),
NSAttributedStringKey.foregroundColor : UIColor.white
]
navigationItem.backBarButtonItem = UIBarButtonItem(title: Localizable.cancel.localized, style: .plain, target: nil, action: nil)
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel,
target: self,
action: #selector(cancelCreation))
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "Save"),
style: .plain,
target: self,
action: #selector(saveNewObject))
}
private func buildForm() {
let currentFields = schema.editableFields().map { return createRow(for: $0) }
let bodySection = SectionFormer(rowFormers: currentFields)
former
.append(sectionFormer: bodySection, moreSection)
.onCellSelected { [weak self] _ in
self?.formerInputAccessoryView.update()
}
}
private func addField() {
let types: [String] = ["Select One", .string, .boolean, .number, .date, .pointer, .array, .file]
let fieldNameRow = TextFieldRowFormer<FormerFieldCell>(instantiateType: .Nib(nibName: "FormerFieldCell")) { [weak self] in
$0.titleLabel.text = "Field Name"
$0.textField.textAlignment = .right
$0.textField.inputAccessoryView = self?.formerInputAccessoryView
}.configure {
$0.placeholder = "ex. Foo"
}
let pointerClassRow = TextFieldRowFormer<FormerFieldCell>(instantiateType: .Nib(nibName: "FormerFieldCell")) { [weak self] in
$0.titleLabel.text = "Target Class"
$0.textField.textAlignment = .right
$0.textField.inputAccessoryView = self?.formerInputAccessoryView
}.configure {
$0.placeholder = "ex. _User"
}
let dataTypePickerRow = InlinePickerRowFormer<FormInlinePickerCell, Any>() {
$0.titleLabel.text = "Data Type"
$0.titleLabel.font = .boldSystemFont(ofSize: 15)
$0.displayLabel.textColor = .darkGray
}.configure {
$0.pickerItems = types.map { return InlinePickerItem(title: $0) }
}.onValueChanged { [weak self] item in
if item.title == .pointer {
self?.former.insertUpdate(rowFormer: pointerClassRow, below: fieldNameRow, rowAnimation: .fade)
} else {
self?.former.removeUpdate(rowFormer: pointerClassRow, rowAnimation: .fade)
}
}
let addRow = LabelRowFormer<FormLabelCell>() {
$0.titleLabel.font = .boldSystemFont(ofSize: 15)
$0.titleLabel.textAlignment = .center
$0.titleLabel.textColor = .logoTint
}.configure {
$0.text = "Add"
}.onSelected { [weak self] _ in
self?.former.deselect(animated: true)
guard let className = self?.schema.name else { return }
guard let fieldName = fieldNameRow.text, !fieldName.isEmpty else {
self?.handleError("Empty Field Name")
return
}
guard dataTypePickerRow.selectedRow > 0 else {
self?.handleError("Please Select a Data Type")
return
}
let dataType = types[dataTypePickerRow.selectedRow]
var newField = JSON()
newField.dictionaryObject?["className"] = className
if dataType == .pointer {
guard let targetClass = pointerClassRow.text else {
self?.handleError("Empty Target Class")
return
}
newField.dictionaryObject?["fields"] = [
fieldName : ["type":dataType, "targetClass":targetClass]
]
} else {
newField.dictionaryObject?["fields"] = [fieldName : ["type":dataType]]
}
do {
let data = try newField.rawData()
ParseLite.shared.put("/schemas/" + className, data: data, completion: { (result, json) in
guard result.success, let json = json else {
self?.handleError(result.error)
return
}
let updatedSchema = PFSchema(json)
let index = (self?.schema.editableFields().count ?? 0) > 0 ? 1 : 0
self?.schema.fields?[fieldName] = updatedSchema.fields?[fieldName]
self?.handleSuccess("Class Updated")
if let newRow = self?.createRow(for: fieldName), let sectionToDelete = self?.former.sectionFormers[index] {
let numberOfRows = self?.former.sectionFormers.first?.numberOfRows ?? 0
let row = index == 1 ? numberOfRows : 0 // Accounts for there being no initial fields
let indexPath = IndexPath(row: row, section: 0)
self?.former
.removeUpdate(sectionFormer: sectionToDelete, rowAnimation: .fade)
.insertUpdate(rowFormer: newRow, toIndexPath: indexPath, rowAnimation: .fade)
.insertUpdate(sectionFormer: self!.moreSection, toSection: 1, rowAnimation: .fade)
} else {
self?.handleError(nil)
}
})
} catch let error {
self?.handleError(error.localizedDescription)
}
}
let section = SectionFormer(rowFormer: fieldNameRow, dataTypePickerRow, addRow)
let index = schema.editableFields().count > 0 ? 1 : 0 // Accounts for there being no initial fields
former
.removeUpdate(sectionFormer: moreSection, rowAnimation: .fade)
.insertUpdate(sectionFormer: section, toSection: index, rowAnimation: .fade)
.onCellSelected { [weak self] _ in
self?.formerInputAccessoryView.update()
}
}
private func createRow(for field: String) -> RowFormer {
let type = schema.typeForField(field) ?? String.string
switch type {
case .string:
return TextFieldRowFormer<FormerFieldCell>(instantiateType: .Nib(nibName: "FormerFieldCell")) { [weak self] in
$0.titleLabel.text = field
$0.textField.textAlignment = .right
$0.textField.inputAccessoryView = self?.formerInputAccessoryView
}.configure {
$0.placeholder = type
}.onTextChanged { [weak self] newValue in
// Update
self?.body.dictionaryObject?[field] = newValue
}
case .file:
return LabelRowFormer<FormLabelCell>() {
$0.titleLabel.font = .boldSystemFont(ofSize: 15)
$0.accessoryType = .disclosureIndicator
}.configure {
$0.text = field
$0.subText = type
}.onSelected { [weak self] _ in
self?.former.deselect(animated: true)
self?.handleError("Sorry, files can only be uploaded after objects creation.")
}
case .boolean:
return SwitchRowFormer<FormSwitchCell>() {
$0.titleLabel.text = field
$0.titleLabel.font = .boldSystemFont(ofSize: 15)
$0.switchButton.onTintColor = .logoTint
}.configure {
$0.switched = false
}.onSwitchChanged { [weak self] newValue in
// Update
self?.body.dictionaryObject?[field] = newValue
}
case .number:
return TextFieldRowFormer<FormerFieldCell>(instantiateType: .Nib(nibName: "FormerFieldCell")) { [weak self] in
$0.titleLabel.text = field
$0.textField.keyboardType = .numbersAndPunctuation
$0.textField.textAlignment = .right
$0.textField.inputAccessoryView = self?.formerInputAccessoryView
}.configure {
$0.placeholder = type
}.onTextChanged { [weak self] newValue in
// Update
let numberValue = Double(newValue)
self?.body.dictionaryObject?[field] = numberValue
}
case .date:
return InlineDatePickerRowFormer<FormInlineDatePickerCell>() {
$0.titleLabel.text = field
$0.titleLabel.font = .boldSystemFont(ofSize: 15)
$0.displayLabel.textColor = .darkGray
$0.displayLabel.font = .systemFont(ofSize: 15)
}.inlineCellSetup {
$0.detailTextLabel?.text = type
$0.datePicker.datePickerMode = .dateAndTime
}.onDateChanged { [weak self] newValue in
// Update
self?.body.dictionaryObject?[field] = [
"__type" : "Date",
"iso" : newValue.stringify()
]
}.displayTextFromDate { date in
return date.string(dateStyle: .medium, timeStyle: .short)
}
case .pointer:
let targetClass = (schema.fields?[field] as? [String:AnyObject])?["targetClass"] as? String
return LabelRowFormer<FormLabelCell>() {
$0.titleLabel.font = .boldSystemFont(ofSize: 15)
$0.accessoryType = .disclosureIndicator
}.configure {
$0.text = field
$0.subText = targetClass
}.onUpdate { [weak self] in
let pointer = self?.body.dictionaryObject?[field] as? [String:AnyObject]
$0.subText = pointer?[.objectId] as? String ?? targetClass
}.onSelected { [weak self] _ in
self?.former.deselect(animated: true)
guard let targetClass = targetClass else { return }
ParseLite.shared.get("/schemas/" + targetClass, completion: { [weak self] (result, json) in
guard result.success, let schemaJSON = json else {
self?.handleError(result.error)
return
}
let schema = PFSchema(schemaJSON)
let selectionController = ObjectSelectorViewController(selecting: field, in: schema)
selectionController.delegate = self
self?.navigationController?.pushViewController(selectionController, animated: true)
})
}
case .object, .array:
return TextViewRowFormer<FormTextViewCell> { [weak self] in
$0.titleLabel.text = field
$0.titleLabel.font = .boldSystemFont(ofSize: 15)
$0.textView.inputAccessoryView = self?.formerInputAccessoryView
}.configure {
$0.placeholder = type
}.onTextChanged { [weak self] newValue in
// Update
let arrayValue = JSON(arrayLiteral: newValue)
self?.body.dictionaryObject?[field] = arrayValue
}
case .relation:
return LabelRowFormer<FormLabelCell>() {
$0.titleLabel.font = .boldSystemFont(ofSize: 15)
$0.accessoryType = .disclosureIndicator
}.configure {
$0.text = field
$0.subText = type
}.onSelected { [weak self] _ in
self?.former.deselect(animated: true)
self?.handleError("Sorry, relations cannot be added via Parse Server's REST API")
}
default:
return TextFieldRowFormer<FormerFieldCell>(instantiateType: .Nib(nibName: "FormerFieldCell")) { [weak self] in
$0.titleLabel.text = field
$0.textField.textAlignment = .right
$0.textField.inputAccessoryView = self?.formerInputAccessoryView
}.configure {
$0.placeholder = type
}.onTextChanged { [weak self] newValue in
// Update
self?.body.dictionaryObject?[field] = newValue
}
}
}
// MARK: - Error Handling
func handleError(_ error: String?) {
let error = error ?? Localizable.unknownError.localized
Ping(text: error, style: .danger).show()
}
func handleSuccess(_ message: String?) {
let message = message?.capitalized ?? Localizable.success.localized
Ping(text: message, style: .success).show()
}
// MARK: - User Actions
@objc
func cancelCreation() {
dismiss(animated: true, completion: nil)
}
@objc
func saveNewObject() {
do {
let data = try body.rawData()
ParseLite.shared.post("/classes/" + schema.name, data: data, completion: { [weak self] (result, json) in
guard result.success, let json = json else {
self?.handleError(result.error)
return
}
let newObject = ParseLiteObject(json)
self?.handleSuccess("Object \(newObject.id) Created")
self?.dismiss(animated: true, completion: nil)
})
} catch let error {
Ping(text: error.localizedDescription, style: .danger).show()
}
}
}
extension ObjectBuilderViewController: ObjectSelectorViewControllerDelegate {
func objectSelector(_ viewController: ObjectSelectorViewController, didSelect object: ParseLiteObject, for key: String) {
guard let type = schema.typeForField(key) else {
handleError("Unknown type for selected field")
return
}
switch type {
case .pointer:
body.dictionaryObject?[key] = [
"__type" : "Pointer",
"objectId" : object.id,
"className" : object.schema?.name
]
guard let index = schema.editableFields().index(of: key) else { return }
former.reload(indexPaths: [IndexPath(row: index, section: 0)])
viewController.navigationController?.popViewController(animated: true)
default:
handleError("Type `Pointer` cannot be assigned to field `\(key)`")
}
}
}
| 51dbf6d06fe5d5aa3507d078624cfc84 | 43.421801 | 136 | 0.537981 | false | false | false | false |
tavon321/FoodApp | refs/heads/master | FoodApp/FoodApp/Menu.swift | mit | 1 | //
// Menu.swift
// TODO
//
// Created by Luis F Ruiz Arroyave on 10/23/16.
// Copyright © 2016 UdeM. All rights reserved.
//
import Foundation
class Menu: NSObject, NSCoding {
//MARK: - Properties
var _id: String
var restaurant: String
var name: String
var price: String
var image: String
//MARK: - Init
//Designated Initializer
init(_id: String, restaurant:String, name:String, price:String,image:String) {
self._id = _id
self.restaurant = restaurant
self.name = name
self.price = price
self.image = price
super.init()
}
required convenience init(coder aDecoder: NSCoder) {
let _id = aDecoder.decodeObjectForKey("_id") as! String
let restaurant = aDecoder.decodeObjectForKey("restaurant") as! String
let name = aDecoder.decodeObjectForKey("name") as! String
let price = aDecoder.decodeObjectForKey("price") as! String
let image = aDecoder.decodeObjectForKey("image") as! String
self.init(_id: _id, restaurant:restaurant, name:name, price:price,image: image)
}
//Convenience Initializer
convenience override init() {
self.init(_id: "", restaurant:"" ,name:"", price:"",image:"")
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(_id, forKey: "_id")
aCoder.encodeObject(name, forKey: "restaurant")
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(price, forKey: "price")
aCoder.encodeObject(price, forKey: "image")
}
// static func save(tasks:[Task]) {
// let data = NSKeyedArchiver.archivedDataWithRootObject(tasks)
// NSUserDefaults.standardUserDefaults().setObject(data, forKey: "Tasks")
// }
class func menus() -> [Menu] {
var menus = [Menu]()
if let data = NSUserDefaults.standardUserDefaults().objectForKey("Menus") as? NSData {
if let objectTasks = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Menu] {
menus = objectTasks
}
}
return menus
}
static func menus(completionHandler: CompletionHandler){
Services.menus { (success, response) in
if success {
var menus = [Menu]()
for(_, value) in response { // response = [String: AnyObject]
let array = value as! NSArray
for itemMenu in array {
let menu = Menu()
let dictMenu = itemMenu as! NSDictionary // itemTask representa una tarea
for(keyMenu, valueMenu) in dictMenu{
if menu.respondsToSelector(NSSelectorFromString(keyMenu as! String)) {
menu.setValue(valueMenu, forKey: keyMenu as! String) //KVC key value Coding Key-value coding is a mechanism for accessing an object’s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables.
}
}
menus.append(menu)
}
}
completionHandler(success:success, response: ["menus":menus])
}else {
completionHandler(success: success, response: response)
}
}
}
}
| 210116f4b21445c836ab80c399e53d50 | 33.346154 | 334 | 0.566349 | false | false | false | false |
zuoya0820/DouYuZB | refs/heads/master | DouYuZB/DouYuZB/Classes/Main/View/CollectionBaseCell.swift | mit | 1 | //
// CollectionBaseCell.swift
// DouYuZB
//
// Created by zuoya on 2017/10/22.
// Copyright © 2017年 zuoya. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionBaseCell: UICollectionViewCell {
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var onlineBtn: UIButton!
var anchor : AnchorModel? {
didSet {
// 0.校验模型是否有值
guard let anchor = anchor else {
return
}
// 1.取出在线人数显示的文字
var onlineStr : String = ""
if anchor.online >= 10000 {
onlineStr = "\(Int(anchor.online / 10000))万在线"
} else {
onlineStr = "\(Int(anchor.online))在线"
}
onlineBtn.setTitle(onlineStr, for: .normal)
// 2.昵称的显示
nicknameLabel.text = anchor.nickname
// 3.设置封面图片
guard let iconURL : URL = URL(string : anchor.vertical_src) else { return }
iconImageView.kf.setImage(with: ImageResource.init(downloadURL: iconURL))
}
}
}
| 50cd338a69c4e784cdce60dea5a2c849 | 26.022727 | 87 | 0.535744 | false | false | false | false |
gouyz/GYZBaking | refs/heads/master | baking/Classes/Tool/comView/GYZLoadingView.swift | mit | 1 | //
// GYZLoadingView.swift
// LazyHuiSellers
// 加载动画loading
// Created by gouyz on 2016/12/22.
// Copyright © 2016年 gouyz. All rights reserved.
//
import UIKit
class GYZLoadingView: UIView {
// MARK: 生命周期方法
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupUI(){
addSubview(desLab)
addSubview(loadView)
loadView.snp.makeConstraints { (make) in
make.center.equalTo(self)
make.size.equalTo(CGSize.init(width: 40, height: 40))
}
desLab.snp.makeConstraints { (make) in
make.left.equalTo(loadView.snp.right)
make.centerY.equalTo(self)
make.height.equalTo(loadView)
make.width.equalTo(100)
}
}
/// 描述
lazy var desLab : UILabel = {
let lab = UILabel()
lab.font = k14Font
lab.textColor = kHeightGaryFontColor
lab.text = "正在加载..."
return lab
}()
/// 菊花动画
lazy var loadView : UIActivityIndicatorView = {
let indView = UIActivityIndicatorView.init(activityIndicatorStyle: .gray)
return indView
}()
/// 开始动画
func startAnimating(){
loadView.startAnimating()
}
}
| 7775900b25d4576cc743fd843c24a524 | 22.932203 | 81 | 0.573654 | false | false | false | false |
0gajun/mal | refs/heads/cpp14 | swift3/Sources/step2_eval/main.swift | mpl-2.0 | 15 | import Foundation
// read
func READ(_ str: String) throws -> MalVal {
return try read_str(str)
}
// eval
func eval_ast(_ ast: MalVal, _ env: Dictionary<String, MalVal>) throws -> MalVal {
switch ast {
case MalVal.MalSymbol(let sym):
if env[sym] == nil {
throw MalError.General(msg: "'\(sym)' not found")
}
return env[sym]!
case MalVal.MalList(let lst, _):
return list(try lst.map { try EVAL($0, env) })
case MalVal.MalVector(let lst, _):
return vector(try lst.map { try EVAL($0, env) })
case MalVal.MalHashMap(let dict, _):
var new_dict = Dictionary<String,MalVal>()
for (k,v) in dict { new_dict[k] = try EVAL(v, env) }
return hash_map(new_dict)
default:
return ast
}
}
func EVAL(_ ast: MalVal, _ env: Dictionary<String, MalVal>) throws -> MalVal {
switch ast {
case MalVal.MalList(let lst, _): if lst.count == 0 { return ast }
default: return try eval_ast(ast, env)
}
switch try eval_ast(ast, env) {
case MalVal.MalList(let elst, _):
switch elst[0] {
case MalVal.MalFunc(let fn,_,_,_,_,_):
let args = Array(elst[1..<elst.count])
return try fn(args)
default:
throw MalError.General(msg: "Cannot apply on '\(elst[0])'")
}
default: throw MalError.General(msg: "Invalid apply")
}
}
// print
func PRINT(_ exp: MalVal) -> String {
return pr_str(exp, true)
}
// repl
func rep(_ str:String) throws -> String {
return PRINT(try EVAL(try READ(str), repl_env))
}
func IntOp(_ op: (Int, Int) -> Int, _ a: MalVal, _ b: MalVal) throws -> MalVal {
switch (a, b) {
case (MalVal.MalInt(let i1), MalVal.MalInt(let i2)):
return MalVal.MalInt(op(i1, i2))
default:
throw MalError.General(msg: "Invalid IntOp call")
}
}
var repl_env: Dictionary<String,MalVal> = [
"+": malfunc({ try IntOp({ $0 + $1}, $0[0], $0[1]) }),
"-": malfunc({ try IntOp({ $0 - $1}, $0[0], $0[1]) }),
"*": malfunc({ try IntOp({ $0 * $1}, $0[0], $0[1]) }),
"/": malfunc({ try IntOp({ $0 / $1}, $0[0], $0[1]) }),
]
while true {
print("user> ", terminator: "")
let line = readLine(strippingNewline: true)
if line == nil { break }
if line == "" { continue }
do {
print(try rep(line!))
} catch (MalError.Reader(let msg)) {
print("Error: \(msg)")
} catch (MalError.General(let msg)) {
print("Error: \(msg)")
}
}
| 0577e8856fbf11b97062ca6c53809c72 | 27.375 | 82 | 0.551462 | false | false | false | false |
atsumo/swift-tutorial | refs/heads/master | StopWatch/StopWatch/ViewController.swift | mit | 1 | //
// ViewController.swift
// StopWatch
//
// Created by atsumo on 9/25/15.
// Copyright © 2015 atsumo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var _count = 0
var _isRunning = false
var _timer = NSTimer()
@IBOutlet weak var label: UILabel!
@IBAction func start(sender: UIButton) {
if _isRunning == true {
return
}
_timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
_isRunning = true
}
@IBAction func stop(sender: UIButton) {
if _isRunning == false {
return
}
_timer.invalidate()
_isRunning = false
}
@IBAction func reset(sender: UIButton) {
_count = 0
label.text = "\(format(0))"
}
func update() {
_count++
label.text = "\(format(_count))"
}
func format(count:Int) -> String {
let ms = count % 100
let s = (count - ms) / 100 % 60
let m = (count - s - ms) / 6000 % 3600
return String(format: "%02d:%02d:%02d", m, s, ms)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| d16d4ea284a2df6fb079ae396602f2ef | 21.61194 | 135 | 0.550495 | false | false | false | false |
qingtianbuyu/Mono | refs/heads/master | Moon/Classes/Main/Other/MNBackNavgationController.swift | mit | 1 | //
// MNBackNavgationController.swift
// Moon
//
// Created by YKing on 16/6/24.
// Copyright © 2016年 YKing. All rights reserved.
//
import UIKit
class MNBackNavgationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
interactivePopGestureRecognizer?.delegate = nil
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
viewController.navigationItem.hidesBackButton = true
if childViewControllers.count > 0 {
viewController.hidesBottomBarWhenPushed = true
let button = UIButton(type:UIButtonType.custom);
button.setBackgroundImage(UIImage(named: "icon-update-arrow-left-black"), for: UIControlState.normal)
button.setBackgroundImage(UIImage(named: "icon-update-arrow-left-black"), for: UIControlState.highlighted)
button.frame = CGRect(x:0, y:0, width:button.currentBackgroundImage!.size.width, height:button.currentBackgroundImage!.size.height)
button.addTarget(self, action: #selector(MNBackNavgationController.back), for: UIControlEvents.touchUpInside)
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
}
super.pushViewController(viewController, animated: animated)
}
func back() {
self.popViewController(animated: true)
}
}
| ee989862371e21d2974cb27f51424606 | 33.461538 | 137 | 0.747024 | false | false | false | false |
jdspoone/Recipinator | refs/heads/master | RecipeBook/IngredientAmountToIngredientAmountPolicy.swift | mit | 1 | /*
Written by Jeff Spooner
Custom migration policy for IngredientAmount instances
*/
import CoreData
class IngredientAmountToIngredientAmountPolicy: NSEntityMigrationPolicy
{
override func createRelationships(forDestination destinationInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws
{
// Get the user info dictionary
let userInfo = mapping.userInfo!
// Get the source version
let sourceVersion = userInfo["sourceVersion"] as? String
// If a source version was specified
if let sourceVersion = sourceVersion {
// Get the source note
let sourceIngredientAmount = manager.sourceInstances(forEntityMappingName: mapping.name, destinationInstances: [destinationInstance]).first!
// Get the source note's relationship keys and values
let sourceRelationshipKeys = Array(sourceIngredientAmount.entity.relationshipsByName.keys)
let sourceRelationshipValues = sourceIngredientAmount.dictionaryWithValues(forKeys: sourceRelationshipKeys)
// Switch on the source version
switch sourceVersion {
// Migrating from v1.2 to v1.3
case "v1.2":
// Get the source instance's incorrectly named recipesUsedIn relationship
let sourceRecipe = sourceRelationshipValues["recipesUsedIn"] as! NSManagedObject
// Get the corresponding destination recipe
let destinationRecipe = manager.destinationInstances(forEntityMappingName: "RecipeToRecipe", sourceInstances: [sourceRecipe]).first!
// Set the destination instance's recipeUsedIn relationship
destinationInstance.setValue(destinationRecipe, forKey: "recipeUsedIn")
default:
break
}
}
}
}
| 45330a9b49619b9465cdd93c0270330e | 32.981818 | 155 | 0.691279 | false | false | false | false |
kiwitechnologies/ServiceClientiOS | refs/heads/master | ServiceClient/ServiceClient/TSGServiceClient/External/ImageCaching/ImageDownloader.swift | mit | 1 | // ImageDownloader.swift
//
// Copyright (c) 2015-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
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
/// The `RequestReceipt` is an object vended by the `ImageDownloader` when starting a download request. It can be used
/// to cancel active requests running on the `ImageDownloader` session. As a general rule, image download requests
/// should be cancelled using the `RequestReceipt` instead of calling `cancel` directly on the `request` itself. The
/// `ImageDownloader` is optimized to handle duplicate request scenarios as well as pending versus active downloads.
public class RequestReceipt {
/// The download request created by the `ImageDownloader`.
public let request: Request
/// The unique identifier for the image filters and completion handlers when duplicate requests are made.
public let receiptID: String
init(request: Request, receiptID: String) {
self.request = request
self.receiptID = receiptID
}
}
/// The `ImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming
/// downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded
/// image is cached in the underlying `NSURLCache` as well as the in-memory image cache that supports image filters.
/// By default, any download request with a cached image equivalent in the image cache will automatically be served the
/// cached image representation. Additional advanced features include supporting multiple image filters and completion
/// handlers for a single request.
public class ImageDownloader {
/// The completion handler closure used when an image download completes.
public typealias CompletionHandler = Response<Image, NSError> -> Void
/// The progress handler closure called periodically during an image download.
public typealias ProgressHandler = (bytesRead: Int64, totalBytesRead: Int64, totalExpectedBytesToRead: Int64) -> Void
/**
Defines the order prioritization of incoming download requests being inserted into the queue.
- FIFO: All incoming downloads are added to the back of the queue.
- LIFO: All incoming downloads are added to the front of the queue.
*/
public enum DownloadPrioritization {
case FIFO, LIFO
}
class ResponseHandler {
let identifier: String
let request: Request
var operations: [(id: String, filter: ImageFilter?, completion: CompletionHandler?)]
init(request: Request, id: String, filter: ImageFilter?, completion: CompletionHandler?) {
self.request = request
self.identifier = ImageDownloader.identifierForURLRequest(request.request!)
self.operations = [(id: id, filter: filter, completion: completion)]
}
}
// MARK: - Properties
/// The image cache used to store all downloaded images in.
public let imageCache: ImageRequestCache?
/// The credential used for authenticating each download request.
public private(set) var credential: NSURLCredential?
/// The underlying Alamofire `Manager` instance used to handle all download requests.
public let sessionManager:Manager
let downloadPrioritization: DownloadPrioritization
let maximumActiveDownloads: Int
var activeRequestCount = 0
var queuedRequests: [Request] = []
var responseHandlers: [String: ResponseHandler] = [:]
private let synchronizationQueue: dispatch_queue_t = {
let name = String(format: "com.alamofire.imagedownloader.synchronizationqueue-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL)
}()
private let responseQueue: dispatch_queue_t = {
let name = String(format: "com.alamofire.imagedownloader.responsequeue-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_CONCURRENT)
}()
// MARK: - Initialization
/// The default instance of `ImageDownloader` initialized with default values.
public static let defaultInstance = ImageDownloader()
/**
Creates a default `NSURLSessionConfiguration` with common usage parameter values.
- returns: The default `NSURLSessionConfiguration` instance.
*/
public class func defaultURLSessionConfiguration() -> NSURLSessionConfiguration {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
configuration.HTTPShouldSetCookies = true
configuration.HTTPShouldUsePipelining = false
configuration.requestCachePolicy = .UseProtocolCachePolicy
configuration.allowsCellularAccess = true
configuration.timeoutIntervalForRequest = 60
configuration.URLCache = ImageDownloader.defaultURLCache()
return configuration
}
/**
Creates a default `NSURLCache` with common usage parameter values.
- returns: The default `NSURLCache` instance.
*/
public class func defaultURLCache() -> NSURLCache {
return NSURLCache(
memoryCapacity: 20 * 1024 * 1024, // 20 MB
diskCapacity: 150 * 1024 * 1024, // 150 MB
diskPath: "com.alamofire.imagedownloader"
)
}
/**
Initializes the `ImageDownloader` instance with the given configuration, download prioritization, maximum active
download count and image cache.
- parameter configuration: The `NSURLSessionConfiguration` to use to create the underlying Alamofire
`Manager` instance.
- parameter downloadPrioritization: The download prioritization of the download queue. `.FIFO` by default.
- parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time.
- parameter imageCache: The image cache used to store all downloaded images in.
- returns: The new `ImageDownloader` instance.
*/
public init(
configuration: NSURLSessionConfiguration = ImageDownloader.defaultURLSessionConfiguration(),
downloadPrioritization: DownloadPrioritization = .FIFO,
maximumActiveDownloads: Int = 4,
imageCache: ImageRequestCache? = AutoPurgingImageCache())
{
self.sessionManager = Manager(configuration: configuration)
self.sessionManager.startRequestsImmediately = false
self.downloadPrioritization = downloadPrioritization
self.maximumActiveDownloads = maximumActiveDownloads
self.imageCache = imageCache
}
/**
Initializes the `ImageDownloader` instance with the given sesion manager, download prioritization, maximum
active download count and image cache.
- parameter sessionManager: The Alamofire `Manager` instance to handle all download requests.
- parameter downloadPrioritization: The download prioritization of the download queue. `.FIFO` by default.
- parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time.
- parameter imageCache: The image cache used to store all downloaded images in.
- returns: The new `ImageDownloader` instance.
*/
public init(
sessionManager: Manager,
downloadPrioritization: DownloadPrioritization = .FIFO,
maximumActiveDownloads: Int = 4,
imageCache: ImageRequestCache? = AutoPurgingImageCache())
{
self.sessionManager = sessionManager
self.sessionManager.startRequestsImmediately = false
self.downloadPrioritization = downloadPrioritization
self.maximumActiveDownloads = maximumActiveDownloads
self.imageCache = imageCache
}
// MARK: - Authentication
/**
Associates an HTTP Basic Auth credential with all future download requests.
- parameter user: The user.
- parameter password: The password.
- parameter persistence: The URL credential persistence. `.ForSession` by default.
*/
public func addAuthentication(
user user: String,
password: String,
persistence: NSURLCredentialPersistence = .ForSession)
{
let credential = NSURLCredential(user: user, password: password, persistence: persistence)
addAuthentication(usingCredential: credential)
}
/**
Associates the specified credential with all future download requests.
- parameter credential: The credential.
*/
public func addAuthentication(usingCredential credential: NSURLCredential) {
dispatch_sync(synchronizationQueue) {
self.credential = credential
}
}
// MARK: - Download
/**
Creates a download request using the internal Alamofire `Manager` instance for the specified URL request.
If the same download request is already in the queue or currently being downloaded, the filter and completion
handler are appended to the already existing request. Once the request completes, all filters and completion
handlers attached to the request are executed in the order they were added. Additionally, any filters attached
to the request with the same identifiers are only executed once. The resulting image is then passed into each
completion handler paired with the filter.
You should not attempt to directly cancel the `request` inside the request receipt since other callers may be
relying on the completion of that request. Instead, you should call `cancelRequestForRequestReceipt` with the
returned request receipt to allow the `ImageDownloader` to optimize the cancellation on behalf of all active
callers.
- parameter URLRequest: The URL request.
- parameter receiptID: The `identifier` for the `RequestReceipt` returned. Defaults to a new, randomly
generated UUID.
- parameter filter: The image filter to apply to the image after the download is complete. Defaults
to `nil`.
- parameter progress: The closure to be executed periodically during the lifecycle of the request.
Defaults to `nil`.
- parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue.
- parameter completion: The closure called when the download request is complete. Defaults to `nil`.
- returns: The request receipt for the download request if available. `nil` if the image is stored in the image
cache and the URL request cache policy allows the cache to be used.
*/
public func downloadImage(
URLRequest URLRequest: URLRequestConvertible,
receiptID: String = NSUUID().UUIDString,
filter: ImageFilter? = nil,
progress: ProgressHandler? = nil,
progressQueue: dispatch_queue_t = dispatch_get_main_queue(),
completion: CompletionHandler?)
-> RequestReceipt?
{
var request: Request!
dispatch_sync(synchronizationQueue) {
// 1) Append the filter and completion handler to a pre-existing request if it already exists
let identifier = ImageDownloader.identifierForURLRequest(URLRequest)
if let responseHandler = self.responseHandlers[identifier] {
responseHandler.operations.append(id: receiptID, filter: filter, completion: completion)
request = responseHandler.request
return
}
// 2) Attempt to load the image from the image cache if the cache policy allows it
switch URLRequest.URLRequest.cachePolicy {
case .UseProtocolCachePolicy, .ReturnCacheDataElseLoad, .ReturnCacheDataDontLoad:
if let image = self.imageCache?.imageForRequest(
URLRequest.URLRequest,
withAdditionalIdentifier: filter?.identifier)
{
dispatch_async(dispatch_get_main_queue()) {
let response = Response<Image, NSError>(
request: URLRequest.URLRequest,
response: nil,
data: nil,
result: .Success(image)
)
completion?(response)
}
return
}
default:
break
}
// 3) Create the request and set up authentication, validation and response serialization
request = self.sessionManager.request(URLRequest)
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
request.validate()
if let progress = progress {
request.progress { bytesRead, totalBytesRead, totalExpectedBytesToRead in
dispatch_async(progressQueue) {
progress(
bytesRead: bytesRead,
totalBytesRead: totalBytesRead,
totalExpectedBytesToRead: totalExpectedBytesToRead
)
}
}
}
request.response(
queue: self.responseQueue,
responseSerializer: Request.imageResponseSerializer(),
completionHandler: { [weak self] response in
guard let strongSelf = self, let request = response.request else { return }
let responseHandler = strongSelf.safelyRemoveResponseHandlerWithIdentifier(identifier)
switch response.result {
case .Success(let image):
var filteredImages: [String: Image] = [:]
for (_, filter, completion) in responseHandler.operations {
var filteredImage: Image
if let filter = filter {
if let alreadyFilteredImage = filteredImages[filter.identifier] {
filteredImage = alreadyFilteredImage
} else {
filteredImage = filter.filter(image)
filteredImages[filter.identifier] = filteredImage
}
} else {
filteredImage = image
}
strongSelf.imageCache?.addImage(
filteredImage,
forRequest: request,
withAdditionalIdentifier: filter?.identifier
)
dispatch_async(dispatch_get_main_queue()) {
let response = Response<Image, NSError>(
request: response.request,
response: response.response,
data: response.data,
result: .Success(filteredImage),
timeline: response.timeline
)
completion?(response)
}
}
case .Failure:
for (_, _, completion) in responseHandler.operations {
dispatch_async(dispatch_get_main_queue()) { completion?(response) }
}
}
strongSelf.safelyDecrementActiveRequestCount()
strongSelf.safelyStartNextRequestIfNecessary()
}
)
// 4) Store the response handler for use when the request completes
let responseHandler = ResponseHandler(
request: request,
id: receiptID,
filter: filter,
completion: completion
)
self.responseHandlers[identifier] = responseHandler
// 5) Either start the request or enqueue it depending on the current active request count
if self.isActiveRequestCountBelowMaximumLimit() {
self.startRequest(request)
} else {
self.enqueueRequest(request)
}
}
if let request = request {
return RequestReceipt(request: request, receiptID: receiptID)
}
return nil
}
/**
Creates a download request using the internal Alamofire `Manager` instance for each specified URL request.
For each request, if the same download request is already in the queue or currently being downloaded, the
filter and completion handler are appended to the already existing request. Once the request completes, all
filters and completion handlers attached to the request are executed in the order they were added.
Additionally, any filters attached to the request with the same identifiers are only executed once. The
resulting image is then passed into each completion handler paired with the filter.
You should not attempt to directly cancel any of the `request`s inside the request receipts array since other
callers may be relying on the completion of that request. Instead, you should call
`cancelRequestForRequestReceipt` with the returned request receipt to allow the `ImageDownloader` to optimize
the cancellation on behalf of all active callers.
- parameter URLRequests: The URL requests.
- parameter filter The image filter to apply to the image after each download is complete.
- parameter progress: The closure to be executed periodically during the lifecycle of the request. Defaults
to `nil`.
- parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue.
- parameter completion: The closure called when each download request is complete.
- returns: The request receipts for the download requests if available. If an image is stored in the image
cache and the URL request cache policy allows the cache to be used, a receipt will not be returned
for that request.
*/
public func downloadImages(
URLRequests URLRequests: [URLRequestConvertible],
filter: ImageFilter? = nil,
progress: ProgressHandler? = nil,
progressQueue: dispatch_queue_t = dispatch_get_main_queue(),
completion: CompletionHandler? = nil)
-> [RequestReceipt]
{
return URLRequests.flatMap {
downloadImage(
URLRequest: $0,
filter: filter,
progress: progress,
progressQueue: progressQueue,
completion: completion
)
}
}
/**
Cancels the request in the receipt by removing the response handler and cancelling the request if necessary.
If the request is pending in the queue, it will be cancelled if no other response handlers are registered with
the request. If the request is currently executing or is already completed, the response handler is removed and
will not be called.
- parameter requestReceipt: The request receipt to cancel.
*/
public func cancelRequestForRequestReceipt(requestReceipt: RequestReceipt) {
dispatch_sync(synchronizationQueue) {
let identifier = ImageDownloader.identifierForURLRequest(requestReceipt.request.request!)
guard let responseHandler = self.responseHandlers[identifier] else { return }
if let index = responseHandler.operations.indexOf({ $0.id == requestReceipt.receiptID }) {
let operation = responseHandler.operations.removeAtIndex(index)
let response: Response<Image, NSError> = {
let URLRequest = requestReceipt.request.request!
let error: NSError = {
let failureReason = "ImageDownloader cancelled URL request: \(URLRequest.URLString)"
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: Error.Domain, code: NSURLErrorCancelled, userInfo: userInfo)
}()
return Response(request: URLRequest, response: nil, data: nil, result: .Failure(error))
}()
dispatch_async(dispatch_get_main_queue()) { operation.completion?(response) }
}
if responseHandler.operations.isEmpty && requestReceipt.request.task.state == .Suspended {
requestReceipt.request.cancel()
}
}
}
// MARK: - Internal - Thread-Safe Request Methods
func safelyRemoveResponseHandlerWithIdentifier(identifier: String) -> ResponseHandler {
var responseHandler: ResponseHandler!
dispatch_sync(synchronizationQueue) {
responseHandler = self.responseHandlers.removeValueForKey(identifier)
}
return responseHandler
}
func safelyStartNextRequestIfNecessary() {
dispatch_sync(synchronizationQueue) {
guard self.isActiveRequestCountBelowMaximumLimit() else { return }
while (!self.queuedRequests.isEmpty) {
if let request = self.dequeueRequest() where request.task.state == .Suspended {
self.startRequest(request)
break
}
}
}
}
func safelyDecrementActiveRequestCount() {
dispatch_sync(self.synchronizationQueue) {
if self.activeRequestCount > 0 {
self.activeRequestCount -= 1
}
}
}
// MARK: - Internal - Non Thread-Safe Request Methods
func startRequest(request: Request) {
request.resume()
activeRequestCount += 1
}
func enqueueRequest(request: Request) {
switch downloadPrioritization {
case .FIFO:
queuedRequests.append(request)
case .LIFO:
queuedRequests.insert(request, atIndex: 0)
}
}
func dequeueRequest() -> Request? {
var request: Request?
if !queuedRequests.isEmpty {
request = queuedRequests.removeFirst()
}
return request
}
func isActiveRequestCountBelowMaximumLimit() -> Bool {
return activeRequestCount < maximumActiveDownloads
}
static func identifierForURLRequest(URLRequest: URLRequestConvertible) -> String {
return URLRequest.URLRequest.URLString
}
}
| b850eb6a7cd43b3f12db2085addad888 | 43.056159 | 122 | 0.636498 | false | false | false | false |
qvacua/vimr | refs/heads/master | VimR/VimR/KeysPref.swift | mit | 1 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Cocoa
import PureLayout
import RxSwift
final class KeysPref: PrefPane, UiComponent, NSTextFieldDelegate {
typealias StateType = AppState
enum Action {
case isLeftOptionMeta(Bool)
case isRightOptionMeta(Bool)
}
override var displayName: String {
"Keys"
}
override var pinToContainer: Bool {
true
}
required init(source: Observable<StateType>, emitter: ActionEmitter, state: StateType) {
self.emit = emitter.typedEmit()
self.isLeftOptionMeta = state.mainWindowTemplate.isLeftOptionMeta
self.isRightOptionMeta = state.mainWindowTemplate.isRightOptionMeta
super.init(frame: .zero)
self.addViews()
self.updateViews()
source
.observe(on: MainScheduler.instance)
.subscribe(onNext: { state in
if self.isLeftOptionMeta != state.mainWindowTemplate.isLeftOptionMeta
|| self.isRightOptionMeta != state.mainWindowTemplate.isRightOptionMeta
{
self.isLeftOptionMeta = state.mainWindowTemplate.isLeftOptionMeta
self.isRightOptionMeta = state.mainWindowTemplate.isRightOptionMeta
self.updateViews()
}
})
.disposed(by: self.disposeBag)
}
private let emit: (Action) -> Void
private let disposeBag = DisposeBag()
private var isLeftOptionMeta: Bool
private var isRightOptionMeta: Bool
private let isLeftOptionMetaCheckbox = NSButton(forAutoLayout: ())
private let isRightOptionMetaCheckbox = NSButton(forAutoLayout: ())
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func updateViews() {
self.isLeftOptionMetaCheckbox.boolState = self.isLeftOptionMeta
self.isRightOptionMetaCheckbox.boolState = self.isRightOptionMeta
}
private func addViews() {
let paneTitle = self.paneTitleTextField(title: "Keys")
let isLeftOptionMeta = self.isLeftOptionMetaCheckbox
self.configureCheckbox(
button: isLeftOptionMeta,
title: "Use Left Option as Meta",
action: #selector(KeysPref.isLeftOptionMetaAction(_:))
)
let isRightOptionMeta = self.isRightOptionMetaCheckbox
self.configureCheckbox(
button: isRightOptionMeta,
title: "Use Right Option as Meta",
action: #selector(KeysPref.isRightOptionMetaAction(_:))
)
let metaInfo = self.infoTextField(markdown: #"""
When an Option key is set to Meta, then every input containing the corresponding Option key will\
be passed through to Neovim. This means that you can use mappings like `<M-1>` in Neovim, but\
cannot use the corresponding Option key for keyboard shortcuts containing `Option` or to enter\
special characters like `µ` which is entered by `Option-M` (on the ABC keyboard layout).
"""#)
self.addSubview(paneTitle)
self.addSubview(isLeftOptionMeta)
self.addSubview(isRightOptionMeta)
self.addSubview(metaInfo)
paneTitle.autoPinEdge(toSuperviewEdge: .top, withInset: 18)
paneTitle.autoPinEdge(toSuperviewEdge: .left, withInset: 18)
paneTitle.autoPinEdge(toSuperviewEdge: .right, withInset: 18, relation: .greaterThanOrEqual)
isLeftOptionMeta.autoPinEdge(.top, to: .bottom, of: paneTitle, withOffset: 18)
isLeftOptionMeta.autoPinEdge(toSuperviewEdge: .left, withInset: 18)
isRightOptionMeta.autoPinEdge(.top, to: .bottom, of: isLeftOptionMeta, withOffset: 5)
isRightOptionMeta.autoPinEdge(toSuperviewEdge: .left, withInset: 18)
metaInfo.autoPinEdge(.top, to: .bottom, of: isRightOptionMeta, withOffset: 5)
metaInfo.autoPinEdge(toSuperviewEdge: .left, withInset: 18)
}
}
// MARK: - Actions
extension KeysPref {
@objc func isLeftOptionMetaAction(_ sender: NSButton) {
self.emit(.isLeftOptionMeta(sender.boolState))
}
@objc func isRightOptionMetaAction(_ sender: NSButton) {
self.emit(.isRightOptionMeta(sender.boolState))
}
}
| 5224435e03105571dbe402f9379fc5d1 | 30.47619 | 101 | 0.725164 | false | false | false | false |
ContinuousLearning/PokemonKit | refs/heads/develop | Carthage/Checkouts/ObjectMapper/ObjectMapper/Core/Mapper.swift | apache-2.0 | 7 | //
// Mapper.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Hearst
//
// 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 enum MappingType {
case FromJSON
case ToJSON
}
/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects
public final class Mapper<N: Mappable> {
public var context: MapContext?
public init(context: MapContext? = nil){
self.context = context
}
// MARK: Mapping functions that map to an existing object toObject
/// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
public func map(JSON: AnyObject?, toObject object: N) -> N {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON, toObject: object)
}
return object
}
/// Map a JSON string onto an existing object
public func map(JSONString: String, toObject object: N) -> N {
if let JSON = Mapper.parseJSONDictionary(JSONString) {
return map(JSON, toObject: object)
}
return object
}
/// Maps a JSON dictionary to an existing object that conforms to Mappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
public func map(JSONDictionary: [String : AnyObject], toObject object: N) -> N {
var mutableObject = object
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary, toObject: true, context: context)
mutableObject.mapping(map)
return mutableObject
}
//MARK: Mapping functions that create an object
/// Map an optional JSON string to an object that conforms to Mappable
public func map(JSONString: String?) -> N? {
if let JSONString = JSONString {
return map(JSONString)
}
return nil
}
/// Map a JSON string to an object that conforms to Mappable
public func map(JSONString: String) -> N? {
if let JSON = Mapper.parseJSONDictionary(JSONString) {
return map(JSON)
}
return nil
}
/// Map a JSON NSString to an object that conforms to Mappable
public func map(JSONString: NSString) -> N? {
return map(JSONString as String)
}
/// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil.
public func map(JSON: AnyObject?) -> N? {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON)
}
return nil
}
/// Maps a JSON dictionary to an object that conforms to Mappable
public func map(JSONDictionary: [String : AnyObject]) -> N? {
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary, context: context)
// check if object is StaticMappable
if let klass = N.self as? StaticMappable.Type {
if var object = klass.objectForMapping(map) as? N {
object.mapping(map)
return object
}
}
// fall back to using init? to create N
if var object = N(map) {
object.mapping(map)
return object
}
return nil
}
// MARK: Mapping functions for Arrays and Dictionaries
/// Maps a JSON array to an object that conforms to Mappable
public func mapArray(JSONString: String) -> [N]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
if let objectArray = mapArray(parsedJSON) {
return objectArray
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(parsedJSON) {
return [object]
}
return nil
}
/// Maps a optional JSON String into an array of objects that conforms to Mappable
public func mapArray(JSONString: String?) -> [N]? {
if let JSONString = JSONString {
return mapArray(JSONString)
}
return nil
}
/// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapArray(JSON: AnyObject?) -> [N]? {
if let JSONArray = JSON as? [[String : AnyObject]] {
return mapArray(JSONArray)
}
return nil
}
/// Maps an array of JSON dictionary to an array of Mappable objects
public func mapArray(JSONArray: [[String : AnyObject]]) -> [N]? {
// map every element in JSON array to type N
let result = JSONArray.flatMap(map)
return result
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONString: String) -> [String : N]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
return mapDictionary(parsedJSON)
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSON: AnyObject?) -> [String : N]? {
if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
return mapDictionary(JSONDictionary)
}
return nil
}
/// Maps a JSON dictionary of dictionaries to a dictionary of Mappble objects
public func mapDictionary(JSONDictionary: [String : [String : AnyObject]]) -> [String : N]? {
// map every value in dictionary to type N
let result = JSONDictionary.filterMap(map)
if result.isEmpty == false {
return result
}
return nil
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSON: AnyObject?, toDictionary dictionary: [String : N]) -> [String : N] {
if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
return mapDictionary(JSONDictionary, toDictionary: dictionary)
}
return dictionary
}
/// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappble objects
public func mapDictionary(JSONDictionary: [String : [String : AnyObject]], toDictionary dictionary: [String : N]) -> [String : N] {
var mutableDictionary = dictionary
for (key, value) in JSONDictionary {
if let object = dictionary[key] {
map(value, toObject: object)
} else {
mutableDictionary[key] = map(value)
}
}
return mutableDictionary
}
/// Maps a JSON object to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSON: AnyObject?) -> [String : [N]]? {
if let JSONDictionary = JSON as? [String : [[String : AnyObject]]] {
return mapDictionaryOfArrays(JSONDictionary)
}
return nil
}
///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSONDictionary: [String : [[String : AnyObject]]]) -> [String : [N]]? {
// map every value in dictionary to type N
let result = JSONDictionary.filterMap {
mapArray($0)
}
if result.isEmpty == false {
return result
}
return nil
}
/// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects
public func mapArrayOfArrays(JSON: AnyObject?) -> [[N]]? {
if let JSONArray = JSON as? [[[String : AnyObject]]] {
var objectArray = [[N]]()
for innerJSONArray in JSONArray {
if let array = mapArray(innerJSONArray){
objectArray.append(array)
}
}
if objectArray.isEmpty == false {
return objectArray
}
}
return nil
}
// MARK: Utility functions for converting strings to JSON objects
/// Convert a JSON String into a Dictionary<String, AnyObject> using NSJSONSerialization
public static func parseJSONDictionary(JSON: String) -> [String : AnyObject]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSON)
return Mapper.parseJSONDictionary(parsedJSON)
}
/// Convert a JSON Object into a Dictionary<String, AnyObject> using NSJSONSerialization
public static func parseJSONDictionary(JSON: AnyObject?) -> [String : AnyObject]? {
if let JSONDict = JSON as? [String : AnyObject] {
return JSONDict
}
return nil
}
/// Convert a JSON String into an Object using NSJSONSerialization
public static func parseJSONString(JSON: String) -> AnyObject? {
let data = JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
if let data = data {
let parsedJSON: AnyObject?
do {
parsedJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
} catch let error {
print(error)
parsedJSON = nil
}
return parsedJSON
}
return nil
}
}
extension Mapper {
// MARK: Functions that create JSON from objects
///Maps an object that conforms to Mappable to a JSON dictionary <String : AnyObject>
public func toJSON(object: N) -> [String : AnyObject] {
var mutableObject = object
let map = Map(mappingType: .ToJSON, JSONDictionary: [:], context: context)
mutableObject.mapping(map)
return map.JSONDictionary
}
///Maps an array of Objects to an array of JSON dictionaries [[String : AnyObject]]
public func toJSONArray(array: [N]) -> [[String : AnyObject]] {
return array.map {
// convert every element in array to JSON dictionary equivalent
self.toJSON($0)
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionary(dictionary: [String : N]) -> [String : [String : AnyObject]] {
return dictionary.map { k, v in
// convert every value in dictionary to its JSON dictionary equivalent
return (k, self.toJSON(v))
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionaryOfArrays(dictionary: [String : [N]]) -> [String : [[String : AnyObject]]] {
return dictionary.map { k, v in
// convert every value (array) in dictionary to its JSON dictionary equivalent
return (k, self.toJSONArray(v))
}
}
/// Maps an Object to a JSON string with option of pretty formatting
public func toJSONString(object: N, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSON(object)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
/// Maps an array of Objects to a JSON string with option of pretty formatting
public func toJSONString(array: [N], prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONArray(array)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
/// Converts an Object to a JSON string with option of pretty formatting
public static func toJSONString(JSONObject: AnyObject, prettyPrint: Bool) -> String? {
let options: NSJSONWritingOptions = prettyPrint ? .PrettyPrinted : []
if let JSON = Mapper.toJSONData(JSONObject, options: options) {
return String(data: JSON, encoding: NSUTF8StringEncoding)
}
return nil
}
/// Converts an Object to JSON data with options
public static func toJSONData(JSONObject: AnyObject, options: NSJSONWritingOptions) -> NSData? {
if NSJSONSerialization.isValidJSONObject(JSONObject) {
let JSONData: NSData?
do {
JSONData = try NSJSONSerialization.dataWithJSONObject(JSONObject, options: options)
} catch let error {
print(error)
JSONData = nil
}
return JSONData
}
return nil
}
}
extension Mapper where N: Hashable {
/// Maps a JSON array to an object that conforms to Mappable
public func mapSet(JSONString: String) -> Set<N>? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
if let objectArray = mapArray(parsedJSON) {
return Set(objectArray)
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(parsedJSON) {
return Set([object])
}
return nil
}
/// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapSet(JSON: AnyObject?) -> Set<N>? {
if let JSONArray = JSON as? [[String : AnyObject]] {
return mapSet(JSONArray)
}
return nil
}
/// Maps an Set of JSON dictionary to an array of Mappable objects
public func mapSet(JSONArray: [[String : AnyObject]]) -> Set<N> {
// map every element in JSON array to type N
return Set(JSONArray.flatMap(map))
}
///Maps a Set of Objects to a Set of JSON dictionaries [[String : AnyObject]]
public func toJSONSet(set: Set<N>) -> [[String : AnyObject]] {
return set.map {
// convert every element in set to JSON dictionary equivalent
self.toJSON($0)
}
}
/// Maps a set of Objects to a JSON string with option of pretty formatting
public func toJSONString(set: Set<N>, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONSet(set)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
}
extension Dictionary {
internal func map<K: Hashable, V>(@noescape f: Element -> (K, V)) -> [K : V] {
var mapped = [K : V]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func map<K: Hashable, V>(@noescape f: Element -> (K, [V])) -> [K : [V]] {
var mapped = [K : [V]]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func filterMap<U>(@noescape f: Value -> U?) -> [Key : U] {
var mapped = [Key : U]()
for (key, value) in self {
if let newValue = f(value) {
mapped[key] = newValue
}
}
return mapped
}
}
| 3820901c9ba0b350a045b5e25a0459b1 | 30.193478 | 135 | 0.69754 | false | false | false | false |
jovito-royeca/Decktracker | refs/heads/master | osx/DataSource/DataSource/Ruling.swift | apache-2.0 | 1 | //
// Ruling.swift
// DataSource
//
// Created by Jovit Royeca on 29/06/2016.
// Copyright © 2016 Jovito Royeca. All rights reserved.
//
import Foundation
import CoreData
class Ruling: NSManagedObject {
struct Keys {
static let Text = "text"
static let Date = "date"
}
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
init(dictionary: [String : AnyObject], context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName("Ruling", inManagedObjectContext: context)!
super.init(entity: entity,insertIntoManagedObjectContext: context)
update(dictionary)
}
func update(dictionary: [String : AnyObject]) {
text = dictionary[Keys.Text] as? String
if let d = dictionary[Keys.Date] as? String {
let formatter = NSDateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
date = formatter.dateFromString(d)
}
}
var yearKeyPath: String? {
if let date = date {
let formatter = NSDateFormatter()
formatter.dateFormat = "YYYY"
return formatter.stringFromDate(date)
}
return nil
}
}
| 4304f841e1a92dede874ee40a1d6a067 | 26.156863 | 113 | 0.620217 | false | false | false | false |
AlexanderMazaletskiy/SAHistoryNavigationViewController | refs/heads/master | SAHistoryNavigationViewController/SAHistoryViewController.swift | mit | 2 | //
// SAHistoryViewController.swift
// SAHistoryNavigationViewControllerSample
//
// Created by 鈴木大貴 on 2015/03/26.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
protocol SAHistoryViewControllerDelegate: class {
func didSelectIndex(index: Int)
}
class SAHistoryViewController: UIViewController {
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
var images: [UIImage]?
var currentIndex: Int = 0
weak var delegate: SAHistoryViewControllerDelegate?
private let kLineSpace: CGFloat = 20.0
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let size = UIScreen.mainScreen().bounds.size
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.itemSize = size
layout.minimumInteritemSpacing = 0.0
layout.minimumLineSpacing = 20.0
layout.sectionInset = UIEdgeInsets(top: 0.0, left: size.width, bottom: 0.0, right: size.width)
layout.scrollDirection = .Horizontal
}
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = .clearColor()
collectionView.showsHorizontalScrollIndicator = false
NSLayoutConstraint.applyAutoLayout(view, target: collectionView, index: nil, top: 0.0, left: 0.0, right: 0.0, bottom: 0.0, height: nil, width: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func reload() {
collectionView.reloadData()
scrollToIndex(currentIndex, animated: false)
}
func scrollToIndex(index: Int, animated: Bool) {
let width = UIScreen.mainScreen().bounds.size.width
collectionView.setContentOffset(CGPoint(x: (width + kLineSpace) * CGFloat(index), y: 0), animated: animated)
}
}
extension SAHistoryViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let count = images?.count {
return count
}
return 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
for view in cell.subviews {
if let view = view as? UIImageView {
view.removeFromSuperview()
}
}
let imageView = UIImageView(frame: cell.bounds)
imageView.image = images?[indexPath.row]
cell.addSubview(imageView)
return cell
}
}
extension SAHistoryViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.deselectItemAtIndexPath(indexPath, animated: false)
delegate?.didSelectIndex(indexPath.row)
}
} | a39ae550263dbc5b97b506bf706f7909 | 34.107843 | 155 | 0.681564 | false | false | false | false |
adrfer/swift | refs/heads/master | test/SILGen/witnesses.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | FileCheck %s
infix operator <~> {}
func archetype_method<T: X>(x x: T, y: T) -> T {
var x = x
var y = y
return x.selfTypes(x: y)
}
// CHECK-LABEL: sil hidden @_TF9witnesses16archetype_method{{.*}} : $@convention(thin) <T where T : X> (@out T, @in T, @in T) -> () {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.selfTypes!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@out τ_0_0, @in τ_0_0, @inout τ_0_0) -> ()
// CHECK: apply [[METHOD]]<T>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@out τ_0_0, @in τ_0_0, @inout τ_0_0) -> ()
// CHECK: }
func archetype_generic_method<T: X>(x x: T, y: Loadable) -> Loadable {
var x = x
return x.generic(x: y)
}
// CHECK-LABEL: sil hidden @_TF9witnesses24archetype_generic_method{{.*}} : $@convention(thin) <T where T : X> (@in T, Loadable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.generic!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@out τ_1_0, @in τ_1_0, @inout τ_0_0) -> ()
// CHECK: apply [[METHOD]]<T, Loadable>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@out τ_1_0, @in τ_1_0, @inout τ_0_0) -> ()
// CHECK: }
// CHECK-LABEL: sil hidden @_TF9witnesses32archetype_associated_type_method{{.*}} : $@convention(thin) <T where T : WithAssocType> (@out T, @in T, @in T.AssocType) -> ()
// CHECK: apply %{{[0-9]+}}<T, T.AssocType>
func archetype_associated_type_method<T: WithAssocType>(x x: T, y: T.AssocType) -> T {
return x.useAssocType(x: y)
}
protocol StaticMethod { static func staticMethod() }
// CHECK-LABEL: sil hidden @_TF9witnesses23archetype_static_method{{.*}} : $@convention(thin) <T where T : StaticMethod> (@in T) -> ()
func archetype_static_method<T: StaticMethod>(x x: T) {
// CHECK: [[METHOD:%.*]] = witness_method $T, #StaticMethod.staticMethod!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : StaticMethod> (@thick τ_0_0.Type) -> ()
// CHECK: apply [[METHOD]]<T>
T.staticMethod()
}
protocol Existentiable {
func foo() -> Loadable
func generic<T>() -> T
}
func protocol_method(x x: Existentiable) -> Loadable {
return x.foo()
}
// CHECK-LABEL: sil hidden @_TF9witnesses15protocol_methodFT1xPS_13Existentiable__VS_8Loadable : $@convention(thin) (@in Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.foo!1
// CHECK: apply [[METHOD]]<[[OPENED]]>({{%.*}})
// CHECK: }
func protocol_generic_method(x x: Existentiable) -> Loadable {
return x.generic()
}
// CHECK-LABEL: sil hidden @_TF9witnesses23protocol_generic_methodFT1xPS_13Existentiable__VS_8Loadable : $@convention(thin) (@in Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.generic!1
// CHECK: apply [[METHOD]]<[[OPENED]], Loadable>({{%.*}}, {{%.*}})
// CHECK: }
@objc protocol ObjCAble {
func foo()
}
// CHECK-LABEL: sil hidden @_TF9witnesses20protocol_objc_methodFT1xPS_8ObjCAble__T_ : $@convention(thin) (@owned ObjCAble) -> ()
// CHECK: witness_method [volatile] $@opened({{.*}}) ObjCAble, #ObjCAble.foo!1.foreign
func protocol_objc_method(x x: ObjCAble) {
x.foo()
}
struct Loadable {}
protocol AddrOnly {}
protocol Classes : class {}
protocol X {
mutating
func selfTypes(x x: Self) -> Self
mutating
func loadable(x x: Loadable) -> Loadable
mutating
func addrOnly(x x: AddrOnly) -> AddrOnly
mutating
func generic<A>(x x: A) -> A
mutating
func classes<A2: Classes>(x x: A2) -> A2
func <~>(x: Self, y: Self) -> Self
}
protocol Y {}
protocol WithAssocType {
typealias AssocType
func useAssocType(x x: AssocType) -> Self
}
protocol ClassBounded : class {
func selfTypes(x x: Self) -> Self
}
struct ConformingStruct : X {
mutating
func selfTypes(x x: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@out ConformingStruct, @in ConformingStruct, @inout ConformingStruct) -> () {
// CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct):
// CHECK-NEXT: %3 = load %1 : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %4 = function_ref @_TFV9witnesses16ConformingStruct9selfTypes{{.*}} : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: %5 = apply %4(%3, %2) : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store %5 to %0 : $*ConformingStruct
// CHECK-NEXT: %7 = tuple ()
// CHECK-NEXT: return %7 : $()
// CHECK-NEXT: }
mutating
func loadable(x x: Loadable) -> Loadable { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_8loadable{{.*}} : $@convention(witness_method) (Loadable, @inout ConformingStruct) -> Loadable {
// CHECK: bb0(%0 : $Loadable, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @_TFV9witnesses16ConformingStruct8loadable{{.*}} : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: %3 = apply %2(%0, %1) : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: return %3 : $Loadable
// CHECK-NEXT: }
mutating
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_8addrOnly{{.*}} : $@convention(witness_method) (@out AddrOnly, @in AddrOnly, @inout ConformingStruct) -> () {
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses16ConformingStruct8addrOnly{{.*}} : $@convention(method) (@out AddrOnly, @in AddrOnly, @inout ConformingStruct) -> ()
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@out AddrOnly, @in AddrOnly, @inout ConformingStruct) -> ()
// CHECK-NEXT: return %4 : $()
// CHECK-NEXT: }
mutating
func generic<C>(x x: C) -> C { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_7generic{{.*}} : $@convention(witness_method) <A> (@out A, @in A, @inout ConformingStruct) -> () {
// CHECK: bb0(%0 : $*A, %1 : $*A, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses16ConformingStruct7generic{{.*}} : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformingStruct) -> ()
// CHECK-NEXT: %4 = apply %3<A>(%0, %1, %2) : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformingStruct) -> ()
// CHECK-NEXT: return %4 : $()
// CHECK-NEXT: }
mutating
func classes<C2: Classes>(x x: C2) -> C2 { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_7classes{{.*}} : $@convention(witness_method) <A2 where A2 : Classes> (@owned A2, @inout ConformingStruct) -> @owned A2 {
// CHECK: bb0(%0 : $A2, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @_TFV9witnesses16ConformingStruct7classes{{.*}} : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: %3 = apply %2<A2>(%0, %1) : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: return %3 : $A2
// CHECK-NEXT: }
}
func <~>(x: ConformingStruct, y: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@out ConformingStruct, @in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> () {
// CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct, %3 : $@thick ConformingStruct.Type):
// CHECK-NEXT: %4 = load %1 : $*ConformingStruct
// CHECK-NEXT: %5 = load %2 : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %6 = function_ref @_TZF9witnessesoi3ltgFTVS_16ConformingStructS0__S0_ : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: %7 = apply %6(%4, %5) : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store %7 to %0 : $*ConformingStruct
// CHECK-NEXT: %9 = tuple ()
// CHECK-NEXT: return %9 : $()
// CHECK-NEXT: }
final class ConformingClass : X {
func selfTypes(x x: ConformingClass) -> ConformingClass { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses15ConformingClassS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@out ConformingClass, @in ConformingClass, @inout ConformingClass) -> () {
// CHECK: bb0(%0 : $*ConformingClass, %1 : $*ConformingClass, %2 : $*ConformingClass):
// -- load and retain 'self' from inout witness 'self' parameter
// CHECK-NEXT: %3 = load %2 : $*ConformingClass
// CHECK-NEXT: strong_retain %3 : $ConformingClass
// CHECK-NEXT: %5 = load %1 : $*ConformingClass
// CHECK: %6 = function_ref @_TFC9witnesses15ConformingClass9selfTypes
// CHECK-NEXT: %7 = apply %6(%5, %3) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK-NEXT: store %7 to %0 : $*ConformingClass
// CHECK-NEXT: %9 = tuple ()
// CHECK-NEXT: strong_release %3
// CHECK-NEXT: return %9 : $()
// CHECK-NEXT: }
func loadable(x x: Loadable) -> Loadable { return x }
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x x: D) -> D { return x }
func classes<D2: Classes>(x x: D2) -> D2 { return x }
}
func <~>(x: ConformingClass, y: ConformingClass) -> ConformingClass { return x }
extension ConformingClass : ClassBounded { }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses15ConformingClassS_12ClassBoundedS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass {
// CHECK: bb0([[C0:%.*]] : $ConformingClass, [[C1:%.*]] : $ConformingClass):
// CHECK-NEXT: strong_retain [[C1]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @_TFC9witnesses15ConformingClass9selfTypes
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[C0]], [[C1]]) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK-NEXT: strong_release [[C1]]
// CHECK-NEXT: return [[RESULT]] : $ConformingClass
// CHECK-NEXT: }
struct ConformingAOStruct : X {
var makeMeAO : AddrOnly
mutating
func selfTypes(x x: ConformingAOStruct) -> ConformingAOStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses18ConformingAOStructS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@out ConformingAOStruct, @in ConformingAOStruct, @inout ConformingAOStruct) -> () {
// CHECK: bb0(%0 : $*ConformingAOStruct, %1 : $*ConformingAOStruct, %2 : $*ConformingAOStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses18ConformingAOStruct9selfTypes{{.*}} : $@convention(method) (@out ConformingAOStruct, @in ConformingAOStruct, @inout ConformingAOStruct) -> ()
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@out ConformingAOStruct, @in ConformingAOStruct, @inout ConformingAOStruct) -> ()
// CHECK-NEXT: return %4 : $()
// CHECK-NEXT: }
func loadable(x x: Loadable) -> Loadable { return x }
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x x: D) -> D { return x }
func classes<D2: Classes>(x x: D2) -> D2 { return x }
}
func <~>(x: ConformingAOStruct, y: ConformingAOStruct) -> ConformingAOStruct { return x }
// TODO: The extra abstraction change in these generic witnesses leads to a
// bunch of redundant temporaries that could be avoided by a more sophisticated
// abstraction difference implementation.
struct ConformsWithMoreGeneric : X, Y {
mutating
func selfTypes<E>(x x: E) -> E { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@out ConformsWithMoreGeneric, @in ConformsWithMoreGeneric, @inout ConformsWithMoreGeneric) -> () {
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: %3 = load %1 : $*ConformsWithMoreGeneric
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %4 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric9selfTypes{{.*}} : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: %5 = alloc_stack $ConformsWithMoreGeneric
// CHECK-NEXT: store %3 to %5 : $*ConformsWithMoreGeneric
// CHECK-NEXT: %7 = alloc_stack $ConformsWithMoreGeneric
// CHECK-NEXT: %8 = apply %4<ConformsWithMoreGeneric>(%7, %5, %2) : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: %9 = load %7 : $*ConformsWithMoreGeneric
// CHECK-NEXT: store %9 to %0 : $*ConformsWithMoreGeneric
// CHECK-NEXT: %11 = tuple ()
// CHECK-NEXT: dealloc_stack %7 : $*ConformsWithMoreGeneric
// CHECK-NEXT: dealloc_stack %5 : $*ConformsWithMoreGeneric
// CHECK-NEXT: return %11 : $()
// CHECK-NEXT: }
func loadable<F>(x x: F) -> F { return x }
mutating
func addrOnly<G>(x x: G) -> G { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_8addrOnly{{.*}} : $@convention(witness_method) (@out AddrOnly, @in AddrOnly, @inout ConformsWithMoreGeneric) -> () {
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric8addrOnly{{.*}} : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: %4 = apply %3<AddrOnly>(%0, %1, %2) : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: return %4 : $()
// CHECK-NEXT: }
mutating
func generic<H>(x x: H) -> H { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_7generic{{.*}} : $@convention(witness_method) <A> (@out A, @in A, @inout ConformsWithMoreGeneric) -> () {
// CHECK: bb0(%0 : $*A, %1 : $*A, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric7generic{{.*}} : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: %4 = apply %3<A>(%0, %1, %2) : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: return %4 : $()
// CHECK-NEXT: }
mutating
func classes<I>(x x: I) -> I { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_7classes{{.*}} : $@convention(witness_method) <A2 where A2 : Classes> (@owned A2, @inout ConformsWithMoreGeneric) -> @owned A2 {
// CHECK: bb0(%0 : $A2, %1 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref witnesses.ConformsWithMoreGeneric.classes
// CHECK-NEXT: %2 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric7classes{{.*}} : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: %3 = alloc_stack $A2
// CHECK-NEXT: store %0 to %3 : $*A2
// CHECK-NEXT: %5 = alloc_stack $A2
// CHECK-NEXT: %6 = apply %2<A2>(%5, %3, %1) : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: %7 = load %5 : $*A2
// CHECK-NEXT: dealloc_stack %5 : $*A2
// CHECK-NEXT: dealloc_stack %3 : $*A2
// CHECK-NEXT: return %7 : $A2
// CHECK-NEXT: }
}
func <~> <J: Y, K: Y>(x: J, y: K) -> K { return y }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@out ConformsWithMoreGeneric, @in ConformsWithMoreGeneric, @in ConformsWithMoreGeneric, @thick ConformsWithMoreGeneric.Type) -> () {
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric, %3 : $@thick ConformsWithMoreGeneric.Type):
// CHECK-NEXT: %4 = load %1 : $*ConformsWithMoreGeneric
// CHECK-NEXT: %5 = load %2 : $*ConformsWithMoreGeneric
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %6 = function_ref @_TZF9witnessesoi3ltg{{.*}} : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@out τ_0_1, @in τ_0_0, @in τ_0_1) -> ()
// CHECK-NEXT: %7 = alloc_stack $ConformsWithMoreGeneric
// CHECK-NEXT: store %4 to %7 : $*ConformsWithMoreGeneric
// CHECK-NEXT: %9 = alloc_stack $ConformsWithMoreGeneric
// CHECK-NEXT: store %5 to %9 : $*ConformsWithMoreGeneric
// CHECK-NEXT: %11 = alloc_stack $ConformsWithMoreGeneric
// CHECK-NEXT: %12 = apply %6<ConformsWithMoreGeneric, ConformsWithMoreGeneric>(%11, %7, %9) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@out τ_0_1, @in τ_0_0, @in τ_0_1) -> ()
// CHECK-NEXT: %13 = load %11 : $*ConformsWithMoreGeneric
// CHECK-NEXT: store %13 to %0 : $*ConformsWithMoreGeneric
// CHECK-NEXT: %15 = tuple ()
// CHECK-NEXT: dealloc_stack %11 : $*ConformsWithMoreGeneric
// CHECK-NEXT: dealloc_stack %9 : $*ConformsWithMoreGeneric
// CHECK-NEXT: dealloc_stack %7 : $*ConformsWithMoreGeneric
// CHECK-NEXT: return %15 : $()
// CHECK-NEXT: }
protocol LabeledRequirement {
func method(x x: Loadable)
}
struct UnlabeledWitness : LabeledRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16UnlabeledWitnessS_18LabeledRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (Loadable, @in_guaranteed UnlabeledWitness) -> ()
func method(x _: Loadable) {}
}
protocol LabeledSelfRequirement {
func method(x x: Self)
}
struct UnlabeledSelfWitness : LabeledSelfRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses20UnlabeledSelfWitnessS_22LabeledSelfRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (@in UnlabeledSelfWitness, @in_guaranteed UnlabeledSelfWitness) -> ()
func method(x _: UnlabeledSelfWitness) {}
}
protocol UnlabeledRequirement {
func method(x _: Loadable)
}
struct LabeledWitness : UnlabeledRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14LabeledWitnessS_20UnlabeledRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (Loadable, @in_guaranteed LabeledWitness) -> ()
func method(x x: Loadable) {}
}
protocol UnlabeledSelfRequirement {
func method(_: Self)
}
struct LabeledSelfWitness : UnlabeledSelfRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses18LabeledSelfWitnessS_24UnlabeledSelfRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (@in LabeledSelfWitness, @in_guaranteed LabeledSelfWitness) -> ()
func method(x: LabeledSelfWitness) {}
}
protocol ReadOnlyRequirement {
var prop: String { get }
static var prop: String { get }
}
struct ImmutableModel: ReadOnlyRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14ImmutableModelS_19ReadOnlyRequirementS_FS1_g4propSS : $@convention(witness_method) (@in_guaranteed ImmutableModel) -> @owned String
let prop: String = "a"
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14ImmutableModelS_19ReadOnlyRequirementS_ZFS1_g4propSS : $@convention(witness_method) (@thick ImmutableModel.Type) -> @owned String
static let prop: String = "b"
}
protocol FailableRequirement {
init?(foo: Int)
}
protocol NonFailableRefinement: FailableRequirement {
init(foo: Int)
}
protocol IUOFailableRequirement {
init!(foo: Int)
}
struct NonFailableModel: FailableRequirement, NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_19FailableRequirementS_FS1_C{{.*}} : $@convention(witness_method) (@out Optional<NonFailableModel>, Int, @thick NonFailableModel.Type) -> ()
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_21NonFailableRefinementS_FS1_C{{.*}} : $@convention(witness_method) (@out NonFailableModel, Int, @thick NonFailableModel.Type) -> ()
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_22IUOFailableRequirementS_FS1_C{{.*}} : $@convention(witness_method) (@out ImplicitlyUnwrappedOptional<NonFailableModel>, Int, @thick NonFailableModel.Type) -> ()
init(foo: Int) {}
}
struct FailableModel: FailableRequirement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses13FailableModelS_19FailableRequirementS_FS1_C{{.*}}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses13FailableModelS_22IUOFailableRequirementS_FS1_C{{.*}}
// CHECK: bb0([[SELF:%[0-9]+]] : $*ImplicitlyUnwrappedOptional<FailableModel>, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick FailableModel.Type):
// CHECK: [[FN:%.*]] = function_ref @_TFV9witnesses13FailableModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FN]](
// CHECK: [[OUTER:%.*]] = unchecked_trivial_bit_cast [[INNER]] : $Optional<FailableModel> to $ImplicitlyUnwrappedOptional<FailableModel>
// CHECK: store [[OUTER]] to %0
// CHECK: return
init?(foo: Int) {}
}
struct IUOFailableModel : NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16IUOFailableModelS_21NonFailableRefinementS_FS1_C{{.*}}
// CHECK: bb0([[SELF:%[0-9]+]] : $*IUOFailableModel, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick IUOFailableModel.Type):
// CHECK: [[META:%[0-9]+]] = metatype $@thin IUOFailableModel.Type
// CHECK: [[INIT:%[0-9]+]] = function_ref @_TFV9witnesses16IUOFailableModelC{{.*}} : $@convention(thin) (Int, @thin IUOFailableModel.Type) -> ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[FOO]], [[META]]) : $@convention(thin) (Int, @thin IUOFailableModel.Type) -> ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[IUO_RESULT_TEMP:%[0-9]+]] = alloc_stack $ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: store [[IUO_RESULT]] to [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[FORCE_FN:%[0-9]+]] = function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue{{.*}} : $@convention(thin) <τ_0_0> (@out τ_0_0, @in ImplicitlyUnwrappedOptional<τ_0_0>) -> ()
// CHECK: [[RESULT_TEMP:%[0-9]+]] = alloc_stack $IUOFailableModel
// CHECK: apply [[FORCE_FN]]<IUOFailableModel>([[RESULT_TEMP]], [[IUO_RESULT_TEMP]]) : $@convention(thin) <τ_0_0> (@out τ_0_0, @in ImplicitlyUnwrappedOptional<τ_0_0>) -> ()
// CHECK: [[RESULT:%[0-9]+]] = load [[RESULT_TEMP]] : $*IUOFailableModel
// CHECK: store [[RESULT]] to [[SELF]] : $*IUOFailableModel
// CHECK: dealloc_stack [[RESULT_TEMP]] : $*IUOFailableModel
// CHECK: dealloc_stack [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: return
init!(foo: Int) { return nil }
}
protocol FailableClassRequirement: class {
init?(foo: Int)
}
protocol NonFailableClassRefinement: FailableClassRequirement {
init(foo: Int)
}
protocol IUOFailableClassRequirement: class {
init!(foo: Int)
}
final class NonFailableClassModel: FailableClassRequirement, NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned Optional<NonFailableClassModel>
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_26NonFailableClassRefinementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned NonFailableClassModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned ImplicitlyUnwrappedOptional<NonFailableClassModel>
init(foo: Int) {}
}
final class FailableClassModel: FailableClassRequirement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses18FailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses18FailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}}
// CHECK: [[FUNC:%.*]] = function_ref @_TFC9witnesses18FailableClassModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: [[OUTER:%.*]] = unchecked_ref_cast [[INNER]] : $Optional<FailableClassModel> to $ImplicitlyUnwrappedOptional<FailableClassModel>
// CHECK: return [[OUTER]] : $ImplicitlyUnwrappedOptional<FailableClassModel>
init?(foo: Int) {}
}
final class IUOFailableClassModel: NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_26NonFailableClassRefinementS_FS1_C{{.*}}
// CHECK: function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue{{.*}}
// CHECK: return [[RESULT:%[0-9]+]] : $IUOFailableClassModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}}
init!(foo: Int) {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}}
// CHECK: [[FUNC:%.*]] = function_ref @_TFC9witnesses21IUOFailableClassModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: [[OUTER:%.*]] = unchecked_ref_cast [[INNER]] : $ImplicitlyUnwrappedOptional<IUOFailableClassModel> to $Optional<IUOFailableClassModel>
// CHECK: return [[OUTER]] : $Optional<IUOFailableClassModel>
}
protocol HasAssoc {
typealias Assoc
}
protocol GenericParameterNameCollisionType {
func foo<T>(x: T)
typealias Assoc2
func bar<T>(x: T -> Assoc2)
}
struct GenericParameterNameCollision<T: HasAssoc> :
GenericParameterNameCollisionType {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTW{{.*}}GenericParameterNameCollision{{.*}}GenericParameterNameCollisionType{{.*}}foo{{.*}} : $@convention(witness_method) <T1 where T1 : HasAssoc><T> (@in T, @in_guaranteed GenericParameterNameCollision<T1>) -> () {
// CHECK: bb0(%0 : $*T, %1 : $*GenericParameterNameCollision<T1>):
// CHECK: apply {{%.*}}<T1, T1.Assoc, T>
func foo<U>(x: U) {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTW{{.*}}GenericParameterNameCollision{{.*}}GenericParameterNameCollisionType{{.*}}bar{{.*}} : $@convention(witness_method) <T1 where T1 : HasAssoc><T> (@owned @callee_owned (@out T1.Assoc, @in T) -> (), @in_guaranteed GenericParameterNameCollision<T1>) -> () {
// CHECK: bb0(%0 : $@callee_owned (@out T1.Assoc, @in T) -> (), %1 : $*GenericParameterNameCollision<T1>):
// CHECK: apply {{%.*}}<T1, T1.Assoc, T>
func bar<V>(x: V -> T.Assoc) {}
}
protocol PropertyRequirement {
var width: Int { get set }
static var height: Int { get set }
var depth: Int { get set }
}
class PropertyRequirementBase {
var width: Int = 12
static var height: Int = 13
}
class PropertyRequirementWitnessFromBase : PropertyRequirementBase, PropertyRequirement {
var depth: Int = 14
// Make sure the contravariant return type in materializeForSet works correctly
// If the witness is in a base class of the conforming class, make sure we have a bit_cast in there:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_FS1_m5widthSi : {{.*}} {
// CHECK: upcast
// CHECK-NEXT: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementBase, #PropertyRequirementBase.width!materializeForSet.1
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0
// CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1
// CHECK-NEXT: [[CAST:%.*]] = unchecked_trivial_bit_cast [[CADR]]
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CAST]] : {{.*}})
// CHECK-NEXT: strong_release
// CHECK-NEXT: return [[TUPLE]]
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_ZFS1_m6heightSi : {{.*}} {
// CHECK: [[OBJ:%.*]] = upcast %2 : $@thick PropertyRequirementWitnessFromBase.Type to $@thick PropertyRequirementBase.Type
// CHECK: [[METH:%.*]] = function_ref @_TZFC9witnesses23PropertyRequirementBasem6heightSi
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0
// CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1
// CHECK-NEXT: [[CAST:%.*]] = unchecked_trivial_bit_cast [[CADR]]
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CAST]] : {{.*}})
// CHECK-NEXT: return [[TUPLE]]
// Otherwise, we shouldn't need the bit_cast:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_FS1_m5depthSi
// CHECK: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementWitnessFromBase, #PropertyRequirementWitnessFromBase.depth!materializeForSet.1
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: strong_release
// CHECK-NEXT: return [[RES]]
}
| 037cb0ee94eb02be47e06cbcc4b1aa61 | 58.298246 | 314 | 0.669034 | false | false | false | false |
mattermost/mattermost-mobile | refs/heads/main | ios/Gekidou/Sources/Gekidou/Networking/ShareExtension.swift | apache-2.0 | 1 | //
// File.swift
//
//
// Created by Elias Nahum on 26-06-22.
//
import Foundation
import os.log
struct UploadSessionData {
var serverUrl: String?
var channelId: String?
var files: [String] = []
var fileIds: [String] = []
var message: String = ""
var totalFiles: Int = 0
func toDictionary() -> NSDictionary {
let data: NSDictionary = [
"serverUrl": serverUrl as Any,
"channelId": channelId as Any,
"files": files,
"fileIds": fileIds,
"message": message,
"totalFiles": totalFiles
]
return data
}
func fromDictionary(dict: NSDictionary) -> UploadSessionData {
let serverUrl = dict["serverUrl"] as! String
let channelId = dict["channelId"] as! String
let files = dict["files"] as! [String]
let fileIds = dict["fileIds"] as! [String]
let message = dict["message"] as! String
let totalFiles = dict["totalFiles"] as! Int
return UploadSessionData(
serverUrl: serverUrl,
channelId: channelId,
files: files,
fileIds: fileIds,
message: message,
totalFiles: totalFiles
)
}
}
public class ShareExtension: NSObject {
public var backgroundSession: URLSession?
private var cacheURL: URL?
private let fileMgr = FileManager.default
private let preferences = Preferences.default
public var completionHandler: (() -> Void)?
public override init() {
super.init()
if let groupId = appGroupId,
let containerUrl = fileMgr.containerURL(forSecurityApplicationGroupIdentifier: groupId),
let url = containerUrl.appendingPathComponent("Library", isDirectory: true) as URL?,
let cache = url.appendingPathComponent("Cache", isDirectory: true) as URL? {
self.cacheURL = cache
self.createCacheDirectoryIfNeeded()
}
}
private func createCacheDirectoryIfNeeded() {
var isDirectory = ObjCBool(false)
if let cachePath = cacheURL?.path {
let exists = FileManager.default.fileExists(atPath: cachePath, isDirectory: &isDirectory)
if !exists && !isDirectory.boolValue {
try? FileManager.default.createDirectory(atPath: cachePath, withIntermediateDirectories: true, attributes: nil)
}
}
}
func saveUploadSessionData(id: String, data: UploadSessionData) {
preferences.set(data.toDictionary(), forKey: id)
os_log(
OSLogType.default,
"Mattermost BackgroundSession: saveUploadSessionData for identifier=%{public}@",
id
)
}
func createUploadSessionData(id: String, serverUrl: String, channelId: String, message: String, files: [String]) {
let data = UploadSessionData(
serverUrl: serverUrl,
channelId: channelId,
files: files,
message: message,
totalFiles: files.count
)
saveUploadSessionData(id: id, data: data)
}
func getUploadSessionData(id: String) -> UploadSessionData? {
if let data = preferences.object(forKey: id) as? NSDictionary {
return UploadSessionData().fromDictionary(dict: data)
}
return nil
}
func removeUploadSessionData(id: String) {
preferences.removeObject(forKey: id)
os_log(
OSLogType.default,
"Mattermost BackgroundSession: removeUploadSessionData for identifier=%{public}@",
id
)
}
func appendCompletedUploadToSession(id: String, fileId: String) {
if let data = getUploadSessionData(id: id) {
var fileIds = data.fileIds
fileIds.append(fileId)
let newData = UploadSessionData(
serverUrl: data.serverUrl,
channelId: data.channelId,
files: data.files,
fileIds: fileIds,
message: data.message,
totalFiles: data.totalFiles
)
saveUploadSessionData(id: id, data: newData)
}
}
func deleteUploadedFiles(files: [String]) {
for file in files {
do {
try fileMgr.removeItem(atPath: file)
} catch {
os_log(
OSLogType.default,
"Mattermost BackgroundSession: deleteUploadedFiles filed to delete=%{public}@",
file
)
}
}
}
}
| 1fbec4cea192696b4e9721152678b143 | 30.378378 | 121 | 0.576012 | false | false | false | false |
cliqz-oss/browser-ios | refs/heads/development | Client/Frontend/Browser/NewTabChoiceViewController.swift | mpl-2.0 | 2 | /* 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
/// Screen presented to the user when selecting the page that is displayed when the user goes to a new tab.
class NewTabChoiceViewController: UITableViewController {
let newTabOptions: [NewTabPage] = [.BlankPage, .TopSites, .Bookmarks, .History, .HomePage]
let prefs: Prefs
var currentChoice: NewTabPage!
var hasHomePage: Bool!
fileprivate let BasicCheckmarkCell = "BasicCheckmarkCell"
fileprivate var authenticationInfo: AuthenticationKeychainInfo?
init(prefs: Prefs) {
self.prefs = prefs
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = Strings.SettingsNewTabTitle
tableView.accessibilityIdentifier = "NewTabPage.Setting.Options"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: BasicCheckmarkCell)
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
let headerFooterFrame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.view.frame.width, height: UIConstants.TableViewHeaderFooterHeight))
let headerView = SettingsTableSectionHeaderFooterView(frame: headerFooterFrame)
headerView.showTopBorder = false
headerView.showBottomBorder = true
let footerView = SettingsTableSectionHeaderFooterView(frame: headerFooterFrame)
footerView.showTopBorder = true
footerView.showBottomBorder = false
tableView.tableHeaderView = headerView
tableView.tableFooterView = footerView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.currentChoice = NewTabAccessors.getNewTabPage(prefs)
self.hasHomePage = HomePageAccessors.getHomePage(prefs) != nil
tableView.reloadData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.prefs.setString(currentChoice.rawValue, forKey: NewTabAccessors.PrefKey)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: BasicCheckmarkCell, for: indexPath)
let option = newTabOptions[indexPath.row]
cell.textLabel?.attributedText = NSAttributedString.tableRowTitle(option.settingTitle)
cell.accessoryType = (currentChoice == option) ? .checkmark : .none
let enabled = (option != .HomePage) || hasHomePage
cell.textLabel?.textColor = enabled ? UIConstants.TableViewRowTextColor : UIConstants.TableViewDisabledRowTextColor
cell.isUserInteractionEnabled = enabled
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newTabOptions.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
currentChoice = newTabOptions[indexPath.row]
tableView.reloadData()
}
}
| e2f1ee2bc7b6da4978a96d5b82d54206 | 37.724138 | 153 | 0.723657 | false | false | false | false |
Why51982/SLDouYu | refs/heads/master | SLDouYu/SLDouYu/Classes/Home/Controller/SLRecommendViewController.swift | mit | 1 | //
// SLRecommendViewController.swift
// SLDouYu
//
// Created by CHEUNGYuk Hang Raymond on 2016/10/26.
// Copyright © 2016年 CHEUNGYuk Hang Raymond. All rights reserved.
//
import UIKit
//MARK: - 定义常量
private let kItemMargin: CGFloat = 10
private let kItemW: CGFloat = (kScreenW - 3 * kItemMargin) / 2
private let kNormalItemH: CGFloat = kItemW * 3 / 4
private let kPrettyItemH: CGFloat = kItemW * 4 / 3
private let kHeaderViewH: CGFloat = 50
private let kCycleViewH: CGFloat = kScreenW * 3 / 8
private let kGameViewH: CGFloat = 90
private let kNormalCellReuseIdentifier = "kNormalCellReuseIdentifier"
private let kPrettyCellReuseIdentifier = "kPrettyCellReuseIdentifier"
private let kHeaderViewReuseIdentifier = "kHeaderViewReuseIdentifier"
class SLRecommendViewController: SLBaseAnchorViewController {
//MARK: - 懒加载
/// 网络请求的VM
fileprivate lazy var recommendVM: SLRecommendViewModel = SLRecommendViewModel()
/// 创建cycleView
fileprivate lazy var cycleView: SLRecommendCycleView = {
let cycleView = SLRecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH)
return cycleView
}()
/// 创建推荐游戏界面
fileprivate lazy var gameView: SLRecommendGameView = {
let gameView = SLRecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
}
//MARK: - 设置UI界面内容
extension SLRecommendViewController {
//设置UI界面
override func setupUI() {
super.setupUI()
//将cycleView添加到collectionView上
//注意要清空cycle的autoresizingMask,防止其随着父控件的拉升而拉升,造成看不见
collectionView.addSubview(cycleView)
//添加gameView
collectionView.addSubview(gameView)
//调整collectionView的内边距,使cycleView显示出来
collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0)
}
}
//MARK: - 请求网络数据
extension SLRecommendViewController {
//请求推荐网络数据
override func loadData() {
//给父类的ViewModel赋值
baseVM = recommendVM
//发送轮播的网络请求
loadCycleData()
recommendVM.requestData {
//刷新表格
self.collectionView.reloadData()
//取出数据
var groups = self.recommendVM.anchorGroups
//去除前两组数据
groups.remove(at: 0)
groups.remove(at: 0)
//拼接更多一组
let moreGroup = SLAnchorGroup()
moreGroup.tag_name = "更多"
groups.append(moreGroup)
//给GameView赋值
self.gameView.groups = groups
//停止动画,并显示collectionView
self.loadDataFinished()
}
}
//请求轮播图的网络数据
fileprivate func loadCycleData() {
recommendVM.requestCycleData {
self.cycleView.cycleModels = self.recommendVM.cycleModels
}
}
}
//MARK: - UICollectionViewDataSource
extension SLRecommendViewController: UICollectionViewDelegateFlowLayout {
//UICollectionViewDelegateFlowLayout - 定义item的大小
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//如果为颜值组(第一组),修改尺寸
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrettyItemH)
}
return CGSize(width: kItemW, height: kNormalItemH)
}
}
| 4a1e22641947584cdf5e135f60bc2e99 | 28.601626 | 160 | 0.642955 | false | false | false | false |
devincoughlin/swift | refs/heads/master | test/SILGen/statements.swift | apache-2.0 | 3 |
// RUN: %target-swift-emit-silgen -module-name statements -Xllvm -sil-full-demangle -parse-as-library -verify %s | %FileCheck %s
class MyClass {
func foo() { }
}
func markUsed<T>(_ t: T) {}
func marker_1() {}
func marker_2() {}
func marker_3() {}
class BaseClass {}
class DerivedClass : BaseClass {}
var global_cond: Bool = false
func bar(_ x: Int) {}
func foo(_ x: Int, _ y: Bool) {}
func abort() -> Never { abort() }
func assignment(_ x: Int, y: Int) {
var x = x
var y = y
x = 42
y = 57
_ = x
_ = y
(x, y) = (1,2)
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}assignment
// CHECK: integer_literal $Builtin.IntLiteral, 42
// CHECK: assign
// CHECK: integer_literal $Builtin.IntLiteral, 57
// CHECK: assign
func if_test(_ x: Int, y: Bool) {
if (y) {
bar(x);
}
bar(x);
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements7if_test{{[_0-9a-zA-Z]*}}F
func if_else(_ x: Int, y: Bool) {
if (y) {
bar(x);
} else {
foo(x, y);
}
bar(x);
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements7if_else{{[_0-9a-zA-Z]*}}F
func nested_if(_ x: Int, y: Bool, z: Bool) {
if (y) {
if (z) {
bar(x);
}
} else {
if (z) {
foo(x, y);
}
}
bar(x);
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements9nested_if{{[_0-9a-zA-Z]*}}F
func nested_if_merge_noret(_ x: Int, y: Bool, z: Bool) {
if (y) {
if (z) {
bar(x);
}
} else {
if (z) {
foo(x, y);
}
}
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements21nested_if_merge_noret{{[_0-9a-zA-Z]*}}F
func nested_if_merge_ret(_ x: Int, y: Bool, z: Bool) -> Int {
if (y) {
if (z) {
bar(x);
}
return 1
} else {
if (z) {
foo(x, y);
}
}
return 2
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements19nested_if_merge_ret{{[_0-9a-zA-Z]*}}F
func else_break(_ x: Int, y: Bool, z: Bool) {
while z {
if y {
} else {
break
}
}
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements10else_break{{[_0-9a-zA-Z]*}}F
func loop_with_break(_ x: Int, _ y: Bool, _ z: Bool) -> Int {
while (x > 2) {
if (y) {
bar(x);
break
}
}
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements15loop_with_break{{[_0-9a-zA-Z]*}}F
func loop_with_continue(_ x: Int, y: Bool, z: Bool) -> Int {
while (x > 2) {
if (y) {
bar(x);
continue
}
_ = loop_with_break(x, y, z);
}
bar(x);
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements18loop_with_continue{{[_0-9a-zA-Z]*}}F
func do_loop_with_continue(_ x: Int, y: Bool, z: Bool) -> Int {
repeat {
if (x < 42) {
bar(x);
continue
}
_ = loop_with_break(x, y, z);
}
while (x > 2);
bar(x);
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements21do_loop_with_continue{{[_0-9a-zA-Z]*}}F
// CHECK-LABEL: sil hidden [ossa] @{{.*}}for_loops1
func for_loops1(_ x: Int, c: Bool) {
for i in 1..<100 {
markUsed(i)
}
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}for_loops2
func for_loops2() {
// rdar://problem/19316670
// CHECK: alloc_stack $Optional<MyClass>
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown]
// CHECK: [[NEXT:%[0-9]+]] = function_ref @$ss16IndexingIteratorV4next{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: apply [[NEXT]]<Array<MyClass>>
// CHECK: class_method [[OBJ:%[0-9]+]] : $MyClass, #MyClass.foo!1
let objects = [MyClass(), MyClass() ]
for obj in objects {
obj.foo()
}
return
}
func void_return() {
let b:Bool
if b {
return
}
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements11void_return{{[_0-9a-zA-Z]*}}F
// CHECK: cond_br {{%[0-9]+}}, [[BB1:bb[0-9]+]], [[BB2:bb[0-9]+]]
// CHECK: [[BB1]]:
// CHECK: br [[EPILOG:bb[0-9]+]]
// CHECK: [[BB2]]:
// CHECK: br [[EPILOG]]
// CHECK: [[EPILOG]]:
// CHECK: [[R:%[0-9]+]] = tuple ()
// CHECK: return [[R]]
func foo() {}
// <rdar://problem/13549626>
// CHECK-LABEL: sil hidden [ossa] @$s10statements14return_from_if{{[_0-9a-zA-Z]*}}F
func return_from_if(_ a: Bool) -> Int {
// CHECK: bb0(%0 : $Bool):
// CHECK: cond_br {{.*}}, [[THEN:bb[0-9]+]], [[ELSE:bb[0-9]+]]
if a {
// CHECK: [[THEN]]:
// CHECK: br [[EPILOG:bb[0-9]+]]({{%.*}})
return 1
} else {
// CHECK: [[ELSE]]:
// CHECK: br [[EPILOG]]({{%.*}})
return 0
}
// CHECK-NOT: function_ref @foo
// CHECK: [[EPILOG]]([[RET:%.*]] : $Int):
// CHECK: return [[RET]]
foo() // expected-warning {{will never be executed}}
}
class C {}
func use(_ c: C) {}
func for_each_loop(_ x: [C]) {
for i in x {
use(i)
}
_ = 0
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}test_break
func test_break(_ i : Int) {
switch i {
case (let x) where x != 17:
if x == 42 { break }
markUsed(x)
default:
break
}
}
// <rdar://problem/19150249> Allow labeled "break" from an "if" statement
// CHECK-LABEL: sil hidden [ossa] @$s10statements13test_if_breakyyAA1CCSgF : $@convention(thin) (@guaranteed Optional<C>) -> () {
func test_if_break(_ c : C?) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<C>):
label1:
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $Optional<C>, case #Optional.some!enumelt.1: [[TRUE:bb[0-9]+]], case #Optional.none!enumelt: [[FALSE:bb[0-9]+]]
if let x = c {
// CHECK: [[TRUE]]({{.*}} : @owned $C):
// CHECK: apply
foo()
// CHECK: destroy_value
// CHECK: br [[FALSE:bb[0-9]+]]
break label1
use(x) // expected-warning {{will never be executed}}
}
// CHECK: [[FALSE]]:
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements18test_if_else_breakyyAA1CCSgF : $@convention(thin) (@guaranteed Optional<C>) -> () {
func test_if_else_break(_ c : C?) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<C>):
label2:
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $Optional<C>, case #Optional.some!enumelt.1: [[TRUE:bb[0-9]+]], case #Optional.none!enumelt: [[FALSE:bb[0-9]+]]
if let x = c {
// CHECK: [[TRUE]]({{.*}} : @owned $C):
use(x)
// CHECK: apply
// CHECK: br [[EPILOG:bb[0-9]+]]
} else {
// CHECK: [[FALSE]]:
// CHECK: apply
// CHECK: br [[EPILOG:bb[0-9]+]]
foo()
break label2
foo() // expected-warning {{will never be executed}}
}
// CHECK: [[EPILOG]]:
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements23test_if_else_then_breakyySb_AA1CCSgtF
func test_if_else_then_break(_ a : Bool, _ c : C?) {
label3:
// CHECK: bb0({{.*}}, [[ARG2:%.*]] : @guaranteed $Optional<C>):
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]]
// CHECK: switch_enum [[ARG2_COPY]] : $Optional<C>, case #Optional.some!enumelt.1: [[TRUE:bb[0-9]+]], case #Optional.none!enumelt: [[FALSE:bb[0-9]+]]
if let x = c {
// CHECK: [[TRUE]]({{.*}} : @owned $C):
use(x)
// CHECK: br [[EPILOG_BB:bb[0-9]+]]
} else if a {
// CHECK: [[FALSE]]:
// CHECK: cond_br {{.*}}, [[TRUE2:bb[0-9]+]], [[FALSE2:bb[0-9]+]]
//
// CHECK: [[TRUE2]]:
// CHECK: apply
// CHECK: br [[EPILOG_BB]]
foo()
break label3
foo() // expected-warning {{will never be executed}}
}
// CHECK: [[FALSE2]]:
// CHECK: br [[EPILOG_BB]]
// CHECK: [[EPILOG_BB]]:
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements13test_if_breakyySbF
func test_if_break(_ a : Bool) {
// CHECK: br [[LOOP:bb[0-9]+]]
// CHECK: [[LOOP]]:
// CHECK-NEXT: struct_extract {{.*}}
// CHECK-NEXT: cond_br {{.*}}, [[LOOPTRUE:bb[0-9]+]], [[EXIT:bb[0-9]+]]
while a {
if a {
foo()
break // breaks out of while, not if.
}
foo()
}
// CHECK: [[LOOPTRUE]]:
// CHECK-NEXT: struct_extract {{.*}}
// CHECK-NEXT: cond_br {{.*}}, [[IFTRUE:bb[0-9]+]], [[IFFALSE:bb[0-9]+]]
// [[IFTRUE]]:
// CHECK: function_ref statements.foo
// CHECK: br [[OUT:bb[0-9]+]]
// CHECK: [[IFFALSE]]:
// CHECK: function_ref statements.foo
// CHECK: br [[LOOP]]
// CHECK: [[EXIT]]:
// CHECK: br [[OUT]]
// CHECK: [[OUT]]:
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements7test_doyyF
func test_do() {
// CHECK: integer_literal $Builtin.IntLiteral, 0
// CHECK: [[BAR:%.*]] = function_ref @$s10statements3baryySiF
// CHECK: apply [[BAR]](
bar(0)
// CHECK-NOT: br bb
do {
// CHECK: [[CTOR:%.*]] = function_ref @$s10statements7MyClassC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[OBJ:%.*]] = apply [[CTOR]](
let obj = MyClass()
_ = obj
// CHECK: integer_literal $Builtin.IntLiteral, 1
// CHECK: [[BAR:%.*]] = function_ref @$s10statements3baryySiF
// CHECK: apply [[BAR]](
bar(1)
// CHECK-NOT: br bb
// CHECK: destroy_value [[OBJ]]
// CHECK-NOT: br bb
}
// CHECK: integer_literal $Builtin.IntLiteral, 2
// CHECK: [[BAR:%.*]] = function_ref @$s10statements3baryySiF
// CHECK: apply [[BAR]](
bar(2)
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements15test_do_labeledyyF
func test_do_labeled() {
// CHECK: integer_literal $Builtin.IntLiteral, 0
// CHECK: [[BAR:%.*]] = function_ref @$s10statements3baryySiF
// CHECK: apply [[BAR]](
bar(0)
// CHECK: br bb1
// CHECK: bb1:
lbl: do {
// CHECK: [[CTOR:%.*]] = function_ref @$s10statements7MyClassC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[OBJ:%.*]] = apply [[CTOR]](
let obj = MyClass()
_ = obj
// CHECK: integer_literal $Builtin.IntLiteral, 1
// CHECK: [[BAR:%.*]] = function_ref @$s10statements3baryySiF
// CHECK: apply [[BAR]](
bar(1)
// CHECK: [[GLOBAL:%.*]] = function_ref @$s10statements11global_condSbvau
// CHECK: cond_br {{%.*}}, bb2, bb3
if (global_cond) {
// CHECK: bb2:
// CHECK: destroy_value [[OBJ]]
// CHECK: br bb1
continue lbl
}
// CHECK: bb3:
// CHECK: integer_literal $Builtin.IntLiteral, 2
// CHECK: [[BAR:%.*]] = function_ref @$s10statements3baryySiF
// CHECK: apply [[BAR]](
bar(2)
// CHECK: [[GLOBAL:%.*]] = function_ref @$s10statements11global_condSbvau
// CHECK: cond_br {{%.*}}, bb4, bb5
if (global_cond) {
// CHECK: bb4:
// CHECK: destroy_value [[OBJ]]
// CHECK: br bb6
break lbl
}
// CHECK: bb5:
// CHECK: integer_literal $Builtin.IntLiteral, 3
// CHECK: [[BAR:%.*]] = function_ref @$s10statements3baryySiF
// CHECK: apply [[BAR]](
bar(3)
// CHECK: destroy_value [[OBJ]]
// CHECK: br bb6
}
// CHECK: integer_literal $Builtin.IntLiteral, 4
// CHECK: [[BAR:%.*]] = function_ref @$s10statements3baryySiF
// CHECK: apply [[BAR]](
bar(4)
}
func callee1() {}
func callee2() {}
func callee3() {}
// CHECK-LABEL: sil hidden [ossa] @$s10statements11defer_test1yyF
func defer_test1() {
defer { callee1() }
defer { callee2() }
callee3()
// CHECK: [[C3:%.*]] = function_ref @$s10statements7callee3yyF
// CHECK: apply [[C3]]
// CHECK: [[C2:%.*]] = function_ref @$s10statements11defer_test1yyF6
// CHECK: apply [[C2]]
// CHECK: [[C1:%.*]] = function_ref @$s10statements11defer_test1yyF6
// CHECK: apply [[C1]]
}
// CHECK: sil private [ossa] @$s10statements11defer_test1yyF6
// CHECK: function_ref @{{.*}}callee1yyF
// CHECK: sil private [ossa] @$s10statements11defer_test1yyF6
// CHECK: function_ref @{{.*}}callee2yyF
// CHECK-LABEL: sil hidden [ossa] @$s10statements11defer_test2yySbF
func defer_test2(_ cond : Bool) {
// CHECK: [[C3:%.*]] = function_ref @{{.*}}callee3yyF
// CHECK: apply [[C3]]
callee3()
// test the condition.
// CHECK: [[CONDTRUE:%.*]] = struct_extract {{.*}}
// CHECK: cond_br [[CONDTRUE]], [[BODY:bb[0-9]+]], [[EXIT:bb[0-9]+]]
while cond {
// CHECK: [[BODY]]:
// CHECK: [[C2:%.*]] = function_ref @{{.*}}callee2yyF
// CHECK: apply [[C2]]
// CHECK: [[C1:%.*]] = function_ref @$s10statements11defer_test2yySbF6
// CHECK: apply [[C1]]
// CHECK: br [[RETURN:bb[0-9]+]]
defer { callee1() }
callee2()
break
}
// CHECK: [[EXIT]]:
// CHECK: br [[RETURN]]
// CHECK: [[RETURN]]:
// CHECK: [[C3:%.*]] = function_ref @{{.*}}callee3yyF
// CHECK: apply [[C3]]
callee3()
}
func generic_callee_1<T>(_: T) {}
func generic_callee_2<T>(_: T) {}
func generic_callee_3<T>(_: T) {}
// CHECK-LABEL: sil hidden [ossa] @$s10statements16defer_in_generic{{[_0-9a-zA-Z]*}}F
func defer_in_generic<T>(_ x: T) {
// CHECK: [[C3:%.*]] = function_ref @$s10statements16generic_callee_3{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[C3]]<T>
// CHECK: [[C2:%.*]] = function_ref @$s10statements16defer_in_genericyyxlF6
// CHECK: apply [[C2]]<T>
// CHECK: [[C1:%.*]] = function_ref @$s10statements16defer_in_genericyyxlF6
// CHECK: apply [[C1]]<T>
defer { generic_callee_1(x) }
defer { generic_callee_2(x) }
generic_callee_3(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements017defer_in_closure_C8_genericyyxlF : $@convention(thin) <T> (@in_guaranteed T) -> ()
func defer_in_closure_in_generic<T>(_ x: T) {
// CHECK-LABEL: sil private [ossa] @$s10statements017defer_in_closure_C8_genericyyxlFyycfU_ : $@convention(thin) <T> () -> ()
_ = {
// CHECK-LABEL: sil private [ossa] @$s10statements017defer_in_closure_C8_genericyyxlFyycfU_6$deferL_yylF : $@convention(thin) <T> () -> ()
defer { generic_callee_1(T.self) } // expected-warning {{'defer' statement at end of scope always executes immediately}}{{5-10=do}}
}
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements13defer_mutableyySiF
func defer_mutable(_ x: Int) {
var x = x
// CHECK: [[BOX:%.*]] = alloc_box ${ var Int }
// CHECK-NEXT: project_box [[BOX]]
// CHECK-NOT: [[BOX]]
// CHECK: function_ref @$s10statements13defer_mutableyySiF6$deferL_yyF : $@convention(thin) (@inout_aliasable Int) -> ()
// CHECK-NOT: [[BOX]]
// CHECK: destroy_value [[BOX]]
defer { _ = x } // expected-warning {{'defer' statement at end of scope always executes immediately}}{{3-8=do}}
}
protocol StaticFooProtocol { static func foo() }
func testDeferOpenExistential(_ b: Bool, type: StaticFooProtocol.Type) {
defer { type.foo() }
if b { return }
return
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements22testRequireExprPatternyySiF
func testRequireExprPattern(_ a : Int) {
marker_1()
// CHECK: [[M1:%[0-9]+]] = function_ref @$s10statements8marker_1yyF : $@convention(thin) () -> ()
// CHECK-NEXT: apply [[M1]]() : $@convention(thin) () -> ()
// CHECK: function_ref Swift.~= infix<A where A: Swift.Equatable>(A, A) -> Swift.Bool
// CHECK: cond_br {{.*}}, bb1, bb2
guard case 4 = a else { marker_2(); return }
// Fall through case comes first.
// CHECK: bb1:
// CHECK: [[M3:%[0-9]+]] = function_ref @$s10statements8marker_3yyF : $@convention(thin) () -> ()
// CHECK-NEXT: apply [[M3]]() : $@convention(thin) () -> ()
// CHECK-NEXT: br bb3
marker_3()
// CHECK: bb2:
// CHECK: [[M2:%[0-9]+]] = function_ref @$s10statements8marker_2yyF : $@convention(thin) () -> ()
// CHECK-NEXT: apply [[M2]]() : $@convention(thin) () -> ()
// CHECK-NEXT: br bb3
// CHECK: bb3:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements20testRequireOptional1yS2iSgF
// CHECK: bb0([[ARG:%.*]] : $Optional<Int>):
// CHECK-NEXT: debug_value [[ARG]] : $Optional<Int>, let, name "a"
// CHECK-NEXT: switch_enum [[ARG]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME:bb[0-9]+]], case #Optional.none!enumelt: [[NONE:bb[0-9]+]]
func testRequireOptional1(_ a : Int?) -> Int {
// CHECK: [[SOME]]([[PAYLOAD:%.*]] : $Int):
// CHECK-NEXT: debug_value [[PAYLOAD]] : $Int, let, name "t"
// CHECK-NEXT: return [[PAYLOAD]] : $Int
guard let t = a else { abort() }
// CHECK: [[NONE]]:
// CHECK-NEXT: // function_ref statements.abort() -> Swift.Never
// CHECK-NEXT: [[FUNC_REF:%.*]] = function_ref @$s10statements5aborts5NeverOyF
// CHECK-NEXT: apply [[FUNC_REF]]() : $@convention(thin) () -> Never
// CHECK-NEXT: unreachable
return t
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements20testRequireOptional2yS2SSgF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<String>):
// CHECK-NEXT: debug_value [[ARG]] : $Optional<String>, let, name "a"
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] : $Optional<String>
// CHECK-NEXT: switch_enum [[ARG_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
func testRequireOptional2(_ a : String?) -> String {
guard let t = a else { abort() }
// CHECK: [[SOME_BB]]([[STR:%.*]] : @owned $String):
// CHECK-NEXT: debug_value [[STR]] : $String, let, name "t"
// CHECK-NEXT: [[BORROWED_STR:%.*]] = begin_borrow [[STR]]
// CHECK-NEXT: [[RETURN:%.*]] = copy_value [[BORROWED_STR]]
// CHECK-NEXT: end_borrow [[BORROWED_STR]]
// CHECK-NEXT: destroy_value [[STR]] : $String
// CHECK-NEXT: return [[RETURN]] : $String
// CHECK: [[NONE_BB]]:
// CHECK-NEXT: // function_ref statements.abort() -> Swift.Never
// CHECK-NEXT: [[ABORT_FUNC:%.*]] = function_ref @$s10statements5aborts5NeverOyF
// CHECK-NEXT: [[NEVER:%.*]] = apply [[ABORT_FUNC]]()
// CHECK-NEXT: unreachable
return t
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements19testCleanupEmission{{[_0-9a-zA-Z]*}}F
// <rdar://problem/20563234> let-else problem: cleanups for bound patterns shouldn't be run in the else block
protocol MyProtocol {}
func testCleanupEmission<T>(_ x: T) {
// SILGen shouldn't crash/verify abort on this example.
guard let x2 = x as? MyProtocol else { return }
_ = x2
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements15test_is_patternyyAA9BaseClassCF
func test_is_pattern(_ y : BaseClass) {
// checked_cast_br %0 : $BaseClass to $DerivedClass
guard case is DerivedClass = y else { marker_1(); return }
marker_2()
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements15test_as_patternyAA12DerivedClassCAA04BaseF0CF
func test_as_pattern(_ y : BaseClass) -> DerivedClass {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $BaseClass):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: checked_cast_br [[ARG_COPY]] : $BaseClass to $DerivedClass
guard case let result as DerivedClass = y else { }
// CHECK: bb{{.*}}({{.*}} : @owned $DerivedClass):
// CHECK: bb{{.*}}([[PTR:%[0-9]+]] : @owned $DerivedClass):
// CHECK-NEXT: debug_value [[PTR]] : $DerivedClass, let, name "result"
// CHECK-NEXT: [[BORROWED_PTR:%.*]] = begin_borrow [[PTR]]
// CHECK-NEXT: [[RESULT:%.*]] = copy_value [[BORROWED_PTR]]
// CHECK-NEXT: end_borrow [[BORROWED_PTR]]
// CHECK-NEXT: destroy_value [[PTR]] : $DerivedClass
// CHECK-NEXT: return [[RESULT]] : $DerivedClass
return result
}
// CHECK-LABEL: sil hidden [ossa] @$s10statements22let_else_tuple_bindingyS2i_SitSgF
func let_else_tuple_binding(_ a : (Int, Int)?) -> Int {
// CHECK: bb0([[ARG:%.*]] : $Optional<(Int, Int)>):
// CHECK-NEXT: debug_value [[ARG]] : $Optional<(Int, Int)>, let, name "a"
// CHECK-NEXT: switch_enum [[ARG]] : $Optional<(Int, Int)>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
guard let (x, y) = a else { }
_ = y
return x
// CHECK: [[SOME_BB]]([[PAYLOAD:%.*]] : $(Int, Int)):
// CHECK-NEXT: ([[PAYLOAD_1:%.*]], [[PAYLOAD_2:%.*]]) = destructure_tuple [[PAYLOAD]]
// CHECK-NEXT: debug_value [[PAYLOAD_1]] : $Int, let, name "x"
// CHECK-NEXT: debug_value [[PAYLOAD_2]] : $Int, let, name "y"
// CHECK-NEXT: return [[PAYLOAD_1]] : $Int
}
| 38735d4454d5098bc8f89bc47e549757 | 27.739259 | 166 | 0.576009 | false | true | false | false |
Pacific3/PFoundation | refs/heads/master | PFoundation/Error.swift | mit | 1 | public let ErrorDomain = "net.Pacific3.ErrorDomainSpecification"
public protocol ErrorConvertible {
associatedtype Code
associatedtype Description
associatedtype Domain
var code: Code { get }
var errorDescription: Description { get }
var domain: Domain { get }
}
public enum Error: ErrorConvertible {
case Error(Int, String)
case None
public var code: Int {
return getCode()
}
public var errorDescription: String {
return getErrorDescription()
}
public var domain: String {
return ErrorDomain
}
func getCode() -> Int {
switch self {
case let .Error(c, _):
return c
case .None:
return -1001
}
}
func getErrorDescription() -> String {
switch self {
case let .Error(_, d):
return d
case .None:
return "Malformed error."
}
}
}
public struct ErrorSpecification<CodeType, DescriptionType, DomainType>: ErrorConvertible {
var _code: CodeType
var _desc: DescriptionType
var _domain: DomainType
public var code: CodeType {
return _code
}
public var errorDescription: DescriptionType {
return _desc
}
public var domain: DomainType {
return _domain
}
public init<E: ErrorConvertible where E.Code == CodeType, E.Description == DescriptionType, E.Domain == DomainType>(ec: E) {
_code = ec.code
_desc = ec.errorDescription
_domain = ec.domain
}
}
| e887fc9495c9581f167adfcd0595792d | 21.388889 | 128 | 0.578784 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/WordPressTest/Classes/Stores/ActivityStoreTests.swift | gpl-2.0 | 1 | import WordPressFlux
import XCTest
@testable import WordPress
@testable import WordPressKit
class ActivityStoreTests: XCTestCase {
private var dispatcher: ActionDispatcher!
private var store: ActivityStore!
private var activityServiceMock: ActivityServiceRemoteMock!
private var backupServiceMock: JetpackBackupServiceMock!
override func setUp() {
super.setUp()
dispatcher = ActionDispatcher()
activityServiceMock = ActivityServiceRemoteMock()
backupServiceMock = JetpackBackupServiceMock()
store = ActivityStore(dispatcher: dispatcher, activityServiceRemote: activityServiceMock, backupService: backupServiceMock)
}
override func tearDown() {
dispatcher = nil
store = nil
super.tearDown()
}
// Check if refreshActivities call the service with the correct after and before date
//
func testRefreshActivities() {
let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo")
let afterDate = Date()
let beforeDate = Date(timeIntervalSinceNow: 86400)
let group = ["post"]
dispatch(.refreshActivities(site: jetpackSiteRef, quantity: 10, afterDate: afterDate, beforeDate: beforeDate, group: group))
XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithAfterDate, afterDate)
XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithBeforeDate, beforeDate)
XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithGroup, group)
}
// Check if loadMoreActivities call the service with the correct params
//
func testLoadMoreActivities() {
let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo")
let afterDate = Date()
let beforeDate = Date(timeIntervalSinceNow: 86400)
let group = ["post", "user"]
dispatch(.loadMoreActivities(site: jetpackSiteRef, quantity: 10, offset: 20, afterDate: afterDate, beforeDate: beforeDate, group: group))
XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithSiteID, 9)
XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithCount, 10)
XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithOffset, 20)
XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithAfterDate, afterDate)
XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithBeforeDate, beforeDate)
XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithGroup, group)
}
// Check if loadMoreActivities keep the activies and add the new retrieved ones
//
func testLoadMoreActivitiesKeepTheExistent() {
let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo")
store.state.activities[jetpackSiteRef] = [Activity.mock()]
activityServiceMock.activitiesToReturn = [Activity.mock(), Activity.mock()]
activityServiceMock.hasMore = true
dispatch(.loadMoreActivities(site: jetpackSiteRef, quantity: 10, offset: 20, afterDate: nil, beforeDate: nil, group: []))
XCTAssertEqual(store.state.activities[jetpackSiteRef]?.count, 3)
XCTAssertTrue(store.state.hasMore)
}
// resetActivities remove all activities
//
func testResetActivities() {
let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo")
store.state.activities[jetpackSiteRef] = [Activity.mock()]
activityServiceMock.activitiesToReturn = [Activity.mock(), Activity.mock()]
activityServiceMock.hasMore = true
dispatch(.resetActivities(site: jetpackSiteRef))
XCTAssertTrue(store.state.activities[jetpackSiteRef]!.isEmpty)
XCTAssertFalse(store.state.fetchingActivities[jetpackSiteRef]!)
XCTAssertFalse(store.state.hasMore)
}
// Check if loadMoreActivities keep the activies and add the new retrieved ones
//
func testReturnOnlyRewindableActivities() {
let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo")
store.state.activities[jetpackSiteRef] = [Activity.mock()]
activityServiceMock.activitiesToReturn = [Activity.mock(isRewindable: true), Activity.mock()]
activityServiceMock.hasMore = true
store.onlyRestorableItems = true
dispatch(.loadMoreActivities(site: jetpackSiteRef, quantity: 10, offset: 20, afterDate: nil, beforeDate: nil, group: []))
XCTAssertEqual(store.state.activities[jetpackSiteRef]?.filter { $0.isRewindable }.count, 1)
}
// refreshGroups call the service with the correct params
//
func testRefreshGroups() {
let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo")
let afterDate = Date()
let beforeDate = Date(timeIntervalSinceNow: 86400)
dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: afterDate, beforeDate: beforeDate))
XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledWithSiteID, 9)
XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledWithAfterDate, afterDate)
XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledWithBeforeDate, beforeDate)
}
// refreshGroups stores the returned groups
//
func testRefreshGroupsStoreGroups() {
let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo")
activityServiceMock.groupsToReturn = [try! ActivityGroup("post", dictionary: ["name": "Posts and Pages", "count": 5] as [String: AnyObject])]
dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil))
XCTAssertEqual(store.state.groups[jetpackSiteRef]?.count, 1)
XCTAssertTrue(store.state.groups[jetpackSiteRef]!.contains(where: { $0.key == "post" && $0.name == "Posts and Pages" && $0.count == 5}))
}
// refreshGroups does not produce multiple requests
//
func testRefreshGroupsDoesNotProduceMultipleRequests() {
let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo")
dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil))
dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil))
XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledTimes, 1)
}
// When a previous request for Activity types has suceeded, return the cached groups
//
func testRefreshGroupsUseCache() {
let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo")
activityServiceMock.groupsToReturn = [try! ActivityGroup("post", dictionary: ["name": "Posts and Pages", "count": 5] as [String: AnyObject])]
dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil))
dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil))
XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledTimes, 1)
XCTAssertTrue(store.state.groups[jetpackSiteRef]!.contains(where: { $0.key == "post" && $0.name == "Posts and Pages" && $0.count == 5}))
}
// Request groups endpoint again if the cache expired
//
func testRefreshGroupsRequestsAgainIfTheFirstSucceeds() {
let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo")
activityServiceMock.groupsToReturn = [try! ActivityGroup("post", dictionary: ["name": "Posts and Pages", "count": 5] as [String: AnyObject])]
dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil))
dispatch(.resetGroups(site: jetpackSiteRef))
dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: Date(), beforeDate: nil))
XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledTimes, 2)
}
// MARK: - Backup Status
// Query for backup status call the service
//
func testBackupStatusQueryCallsService() {
let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo")
_ = store.query(.backupStatus(site: jetpackSiteRef))
store.processQueries()
XCTAssertEqual(backupServiceMock.didCallGetAllBackupStatusWithSite, jetpackSiteRef)
}
// MARK: - Helpers
private func dispatch(_ action: ActivityAction) {
dispatcher.dispatch(action)
}
}
class ActivityServiceRemoteMock: ActivityServiceRemote {
var getActivityForSiteCalledWithSiteID: Int?
var getActivityForSiteCalledWithOffset: Int?
var getActivityForSiteCalledWithCount: Int?
var getActivityForSiteCalledWithAfterDate: Date?
var getActivityForSiteCalledWithBeforeDate: Date?
var getActivityForSiteCalledWithGroup: [String]?
var getActivityGroupsForSiteCalledWithSiteID: Int?
var getActivityGroupsForSiteCalledWithAfterDate: Date?
var getActivityGroupsForSiteCalledWithBeforeDate: Date?
var getActivityGroupsForSiteCalledTimes = 0
var activitiesToReturn: [Activity]?
var hasMore = false
var groupsToReturn: [ActivityGroup]?
override func getActivityForSite(_ siteID: Int,
offset: Int = 0,
count: Int,
after: Date? = nil,
before: Date? = nil,
group: [String] = [],
success: @escaping (_ activities: [Activity], _ hasMore: Bool) -> Void,
failure: @escaping (Error) -> Void) {
getActivityForSiteCalledWithSiteID = siteID
getActivityForSiteCalledWithCount = count
getActivityForSiteCalledWithOffset = offset
getActivityForSiteCalledWithAfterDate = after
getActivityForSiteCalledWithBeforeDate = before
getActivityForSiteCalledWithGroup = group
if let activitiesToReturn = activitiesToReturn {
success(activitiesToReturn, hasMore)
}
}
override func getActivityGroupsForSite(_ siteID: Int, after: Date? = nil, before: Date? = nil, success: @escaping ([ActivityGroup]) -> Void, failure: @escaping (Error) -> Void) {
getActivityGroupsForSiteCalledWithSiteID = siteID
getActivityGroupsForSiteCalledWithAfterDate = after
getActivityGroupsForSiteCalledWithBeforeDate = before
getActivityGroupsForSiteCalledTimes += 1
if let groupsToReturn = groupsToReturn {
success(groupsToReturn)
}
}
override func getRewindStatus(_ siteID: Int, success: @escaping (RewindStatus) -> Void, failure: @escaping (Error) -> Void) {
}
}
extension ActivityGroup {
class func mock() -> ActivityGroup {
try! ActivityGroup("post", dictionary: ["name": "Posts and Pages", "count": 5] as [String: AnyObject])
}
}
class JetpackBackupServiceMock: JetpackBackupService {
var didCallGetAllBackupStatusWithSite: JetpackSiteRef?
init() {
super.init(managedObjectContext: TestContextManager.sharedInstance().mainContext)
}
override func getAllBackupStatus(for site: JetpackSiteRef, success: @escaping ([JetpackBackup]) -> Void, failure: @escaping (Error) -> Void) {
didCallGetAllBackupStatusWithSite = site
let jetpackBackup = JetpackBackup(backupPoint: Date(), downloadID: 100, rewindID: "", startedAt: Date(), progress: 10, downloadCount: 0, url: "", validUntil: nil)
success([jetpackBackup])
}
}
| 50bbe66991527ddd8533e00996162851 | 42.636015 | 182 | 0.703222 | false | true | false | false |
chwo/TwitterTimeline | refs/heads/master | TwitterTimeline/TwitterTimeline/HashtagTimelineVC.swift | mit | 1 | //
// HashtagTimelineVC.swift
// TwitterTimeline
//
// Created by Christian Wollny on 03.04.15.
// Copyright (c) 2015 Christian Wollny. All rights reserved.
//
import UIKit
import Accounts
import Social
class HashtagTimelineVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
// twitter timeline settings
// let hashtag = "#Swift" // set the username here
var hashtag: String?
let number = "5" // set the number of tweets in the timeline here
// Twitter Account
let accountStore = ACAccountStore()
let twitterType = ACAccountStore().accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
var twitterAccount: ACAccount?
// Array of Tweets
var tweets = [Tweet]()
// TableView
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// get Twitter Account Access
accountStore.requestAccessToAccountsWithType(twitterType, options: nil) {
success, error in
if success {
let alleAccounts = self.accountStore.accountsWithAccountType(self.twitterType)
if alleAccounts.count > 0 {
self.twitterAccount = alleAccounts.last as ACAccount?
}
// self.getTwitterTimeline()
}else{
println(error.localizedDescription)
}
}
}
// Mark: - IBAction: loadTimelineForHashtag
@IBAction func loadTimelineForHashtag(sender: UIBarButtonItem) {
var alert = UIAlertController(title: "Eingabe", message: "Bitte geben Sie einen Twitter Hashtag ein", preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler(){
textField in
textField.textAlignment = .Left
textField.placeholder = "Hashtag"
textField.becomeFirstResponder()
}
alert.addAction(UIAlertAction(title: "Abbrechen", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Hinzufügen", style: .Default, handler: {
action in
// do sth.
self.hashtag = (alert.textFields![0] as UITextField).text
self.getTwitterTimeline()
self.navigationItem.title = "Tweets for \(self.hashtag!)"
}))
presentViewController(alert, animated: true, completion: nil)
}
// Mark: - Twitter API Requests
func getTwitterTimeline(){
let url = NSURL(string: "https://api.twitter.com/1.1/search/tweets.json")!
if hashtag != nil { // unwrapping optional
let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: url, parameters: ["q": hashtag!, "count": number])
request.account = twitterAccount
request.performRequestWithHandler { data, response, error in
if response.statusCode == 200 {
let stringData = NSString(data: data, encoding: NSUTF8StringEncoding)
let json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as [String: AnyObject]
let statuses = json["statuses"] as [[String: AnyObject]]
for dict in statuses {
let text = dict["text"] as String
let user = dict["user"] as [String: AnyObject]
let username = user["screen_name"] as String
let retweet_count = dict["retweet_count"] as Int
let favorite_count = dict["favorite_count"] as Int
let lang = dict["lang"] as String
let neuerTweet = Tweet(text: text, user: username, retweet_count: retweet_count, favorite_count: favorite_count, lang: lang)
dispatch_async(dispatch_get_main_queue()) {
self.tweets.append(neuerTweet)
self.tableView.reloadData()
}
}
}
else {
println("\(response.statusCode): Verbindung zu Twitter fehlgeschlagen: \(error)")
}
}
}
}
// MARK: - TableView methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("HashtagTweets", forIndexPath: indexPath) as UITableViewCell
let aktuellerTweet = tweets[indexPath.row]
let titel = "\(aktuellerTweet.text)"
let untertitel = aktuellerTweet.user
cell.textLabel?.text = titel
cell.detailTextLabel?.text = untertitel
return cell
}
// MARK: - struct Tweet
struct Tweet {
var text: String
var user: String
var retweet_count: Int
var favorite_count: Int
var lang: String
}
}
| b8381d331a767959957008b9594974bc | 36.816901 | 150 | 0.582495 | false | false | false | false |
geekaurora/ReactiveListViewKit | refs/heads/master | Example/ReactiveListViewKitDemo/UI Layer/FeedList/HotUsers/HotUserCellCardView.swift | mit | 1 | //
// HotUserCellView.swift
// ReactiveListViewKit
//
// Created by Cheng Zhang on 3/4/17.
// Copyright © 2017 Cheng Zhang. All rights reserved.
//
import CZUtils
import ReactiveListViewKit
class HotUserCellCardView: CZNibLoadableView, CZFeedCellViewSizeCalculatable {
@IBOutlet var frameView: UIView?
@IBOutlet var contentView: UIView?
@IBOutlet var stackView: UIStackView?
@IBOutlet var portaitView: UIImageView?
@IBOutlet var nameLabel: UILabel?
@IBOutlet var detailsLabel: UILabel?
@IBOutlet var followButton: UIButton?
@IBOutlet var closeButton: UIButton?
private var viewModel: HotUserCellViewModel
var diffId: String {return viewModel.diffId}
var onAction: OnAction?
required init(viewModel: CZFeedViewModelable?, onAction: OnAction?) {
guard let viewModel = viewModel as? HotUserCellViewModel else {
fatalError("Incorrect ViewModel type.")
}
self.viewModel = viewModel
self.onAction = onAction
super.init(frame: .zero)
backgroundColor = .white
config(with: viewModel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Must call designated initializer `init(viewModel:onAction:)`")
}
func config(with viewModel: CZFeedViewModelable?) {
guard let viewModel = viewModel as? HotUserCellViewModel else {
fatalError("Incorrect ViewModel type.")
}
if let portraitUrl = viewModel.portraitUrl {
portaitView?.cz_setImage(with: portraitUrl)
portaitView?.roundToCircle()
}
detailsLabel?.text = viewModel.fullName
nameLabel?.text = ""
followButton?.roundCorner(2)
closeButton?.roundCorner(2)
frameView?.roundCorner(2)
}
func config(with viewModel: CZFeedViewModelable?, prevViewModel: CZFeedViewModelable?) {}
static func sizeThatFits(_ containerSize: CGSize, viewModel: CZFeedViewModelable) -> CGSize {
return CZFacadeViewHelper.sizeThatFits(containerSize,
viewModel: viewModel,
viewClass: HotUserCellCardView.self,
isHorizontal: true)
}
@IBAction func tappedFollow(_ sender: UIButton) {
onAction?(SuggestedUserAction.follow(user: viewModel.user))
}
@IBAction func tappedClose(_ sender: UIButton) {
onAction?(SuggestedUserAction.ignore(user: viewModel.user))
}
}
| 6c1d562c6a77af33cdb15d8cecbb7ed4 | 33.386667 | 97 | 0.639395 | false | false | false | false |
qualaroo/QualarooSDKiOS | refs/heads/master | QualarooTests/Network/SimpleRequestSchedulerSpec.swift | mit | 1 | //
// SimpleRequestSchedulerSpec.swift
// Qualaroo
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
import Quick
import Nimble
@testable import Qualaroo
class SimpleRequestSchedulerSpec: QuickSpec {
override func spec() {
super.spec()
describe("SimpleRequestScheduler") {
var scheduler: SimpleRequestScheduler!
beforeEach {
scheduler = SimpleRequestScheduler(reachability: nil, storage: PersistentMemory())
scheduler.removeObservers()
}
context("SimpleRequestProtocol") {
it("schedule request when asked") {
scheduler.privateQueue.isSuspended = true
scheduler.scheduleRequest(URL(string: "https://qualaroo.com")!)
let operations = scheduler.privateQueue.operations.filter { $0.isCancelled == false }
expect(operations).to(haveCount(1))
}
it("schedule two request when asked") {
scheduler.privateQueue.isSuspended = true
scheduler.scheduleRequest(URL(string: "https://qualaroo.com")!)
scheduler.scheduleRequest(URL(string: "https://qualaroo.com")!)
let operations = scheduler.privateQueue.operations.filter { $0.isCancelled == false }
expect(operations).to(haveCount(2))
}
}
}
}
}
| 1bc5a634099d6ffc6bf443e3dd867518 | 32.627907 | 95 | 0.670816 | false | false | false | false |
PSPDFKit-labs/ReactiveCocoa | refs/heads/swift-development | ReactiveCocoa/Swift/Action.swift | mit | 1 | /// Represents an action that will do some work when executed with a value of
/// type `Input`, then return zero or more values of type `Output` and/or error
/// out with an error of type `Error`. If no errors should be possible, NoError
/// can be specified for the `Error` parameter.
///
/// Actions enforce serial execution. Any attempt to execute an action multiple
/// times concurrently will return an error.
public final class Action<Input, Output, Error: ErrorType> {
private let executeClosure: Input -> SignalProducer<Output, Error>
private let eventsObserver: Signal<Event<Output, Error>, NoError>.Observer
/// A signal of all events generated from applications of the Action.
///
/// In other words, this will send every `Event` from every signal generated
/// by each SignalProducer returned from apply().
public let events: Signal<Event<Output, Error>, NoError>
/// A signal of all values generated from applications of the Action.
///
/// In other words, this will send every value from every signal generated
/// by each SignalProducer returned from apply().
public let values: Signal<Output, NoError>
/// A signal of all errors generated from applications of the Action.
///
/// In other words, this will send errors from every signal generated by
/// each SignalProducer returned from apply().
public let errors: Signal<Error, NoError>
/// Whether the action is currently executing.
public var executing: PropertyOf<Bool> {
return PropertyOf(_executing)
}
private let _executing: MutableProperty<Bool> = MutableProperty(false)
/// Whether the action is currently enabled.
public var enabled: PropertyOf<Bool> {
return PropertyOf(_enabled)
}
private let _enabled: MutableProperty<Bool> = MutableProperty(false)
/// Whether the instantiator of this action wants it to be enabled.
private let userEnabled: PropertyOf<Bool>
/// Lazy creation and storage of a UI bindable `CocoaAction``. The default behavior
/// force casts the AnyObject? input to match the action's `Input` type. This makes
/// it unsafe for use when the action is paramerterized for something like `Void`
/// input. In those cases, explicitly assign a value to this property that transforms
/// the input to suit your needs.
public lazy var unsafeCocoaAction: CocoaAction = { _ in
CocoaAction(self) { $0 as! Input }
}()
/// This queue is used for read-modify-write operations on the `_executing`
/// property.
private let executingQueue = dispatch_queue_create("org.reactivecocoa.ReactiveCocoa.Action.executingQueue", DISPATCH_QUEUE_SERIAL)
/// Whether the action should be enabled for the given combination of user
/// enabledness and executing status.
private static func shouldBeEnabled(userEnabled userEnabled: Bool, executing: Bool) -> Bool {
return userEnabled && !executing
}
/// Initializes an action that will be conditionally enabled, and create a
/// SignalProducer for each input.
public init<P: PropertyType where P.Value == Bool>(enabledIf: P, _ execute: Input -> SignalProducer<Output, Error>) {
executeClosure = execute
userEnabled = PropertyOf(enabledIf)
(events, eventsObserver) = Signal<Event<Output, Error>, NoError>.pipe()
values = events.map { $0.value }.ignoreNil()
errors = events.map { $0.error }.ignoreNil()
_enabled <~ enabledIf.producer
.combineLatestWith(executing.producer)
.map(Action.shouldBeEnabled)
}
/// Initializes an action that will be enabled by default, and create a
/// SignalProducer for each input.
public convenience init(_ execute: Input -> SignalProducer<Output, Error>) {
self.init(enabledIf: ConstantProperty(true), execute)
}
deinit {
sendCompleted(eventsObserver)
}
/// Creates a SignalProducer that, when started, will execute the action
/// with the given input, then forward the results upon the produced Signal.
///
/// If the action is disabled when the returned SignalProducer is started,
/// the produced signal will send `ActionError.NotEnabled`, and nothing will
/// be sent upon `values` or `errors` for that particular signal.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func apply(input: Input) -> SignalProducer<Output, ActionError<Error>> {
return SignalProducer { observer, disposable in
var startedExecuting = false
dispatch_sync(self.executingQueue) {
if self._enabled.value {
self._executing.value = true
startedExecuting = true
}
}
if !startedExecuting {
sendError(observer, .NotEnabled)
return
}
self.executeClosure(input).startWithSignal { signal, signalDisposable in
disposable.addDisposable(signalDisposable)
signal.observe { event in
observer(event.mapError { .ProducerError($0) })
sendNext(self.eventsObserver, event)
}
}
disposable.addDisposable {
self._executing.value = false
}
}
}
}
/// Wraps an Action for use by a GUI control (such as `NSControl` or
/// `UIControl`), with KVO, or with Cocoa Bindings.
public final class CocoaAction: NSObject {
/// The selector that a caller should invoke upon a CocoaAction in order to
/// execute it.
public static let selector: Selector = "execute:"
/// Whether the action is enabled.
///
/// This property will only change on the main thread, and will generate a
/// KVO notification for every change.
public var enabled: Bool {
return _enabled
}
/// Whether the action is executing.
///
/// This property will only change on the main thread, and will generate a
/// KVO notification for every change.
public var executing: Bool {
return _executing
}
private var _enabled = false
private var _executing = false
private let _execute: AnyObject? -> ()
private let disposable = CompositeDisposable()
/// Initializes a Cocoa action that will invoke the given Action by
/// transforming the object given to execute().
public init<Input, Output, Error>(_ action: Action<Input, Output, Error>, _ inputTransform: AnyObject? -> Input) {
_execute = { input in
let producer = action.apply(inputTransform(input))
producer.start()
}
super.init()
disposable += action.enabled.producer
.observeOn(UIScheduler())
.start(next: { [weak self] value in
self?.willChangeValueForKey("enabled")
self?._enabled = value
self?.didChangeValueForKey("enabled")
})
disposable += action.executing.producer
.observeOn(UIScheduler())
.start(next: { [weak self] value in
self?.willChangeValueForKey("executing")
self?._executing = value
self?.didChangeValueForKey("executing")
})
}
/// Initializes a Cocoa action that will invoke the given Action by
/// always providing the given input.
public convenience init<Input, Output, Error>(_ action: Action<Input, Output, Error>, input: Input) {
self.init(action, { _ in input })
}
/// Initializes a Cocoa action that will invoke the given Action with the
/// object given to execute(), if it can be downcast successfully, or nil
/// otherwise.
public convenience init<Input: AnyObject, Output, Error>(_ action: Action<Input?, Output, Error>) {
self.init(action, { $0 as? Input })
}
deinit {
disposable.dispose()
}
/// Attempts to execute the underlying action with the given input, subject
/// to the behavior described by the initializer that was used.
@IBAction public func execute(input: AnyObject?) {
_execute(input)
}
public override class func automaticallyNotifiesObserversForKey(key: String) -> Bool {
return false
}
}
/// The type of error that can occur from Action.apply, where `E` is the type of
/// error that can be generated by the specific Action instance.
public enum ActionError<E: ErrorType>: ErrorType {
/// The producer returned from apply() was started while the Action was
/// disabled.
case NotEnabled
/// The producer returned from apply() sent the given error.
case ProducerError(E)
}
public func == <E: Equatable>(lhs: ActionError<E>, rhs: ActionError<E>) -> Bool {
switch (lhs, rhs) {
case (.NotEnabled, .NotEnabled):
return true
case let (.ProducerError(left), .ProducerError(right)):
return left == right
default:
return false
}
}
| bb89bb2efadefd1b3035918b14321253 | 33.572034 | 131 | 0.723373 | false | false | false | false |
apple/swift-driver | refs/heads/main | Sources/SwiftDriver/Execution/ProcessProtocol.swift | apache-2.0 | 1 | //===--------------- ProessProtocol.swift - Swift Subprocesses ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import class TSCBasic.Process
import struct TSCBasic.ProcessResult
import class Foundation.FileHandle
import struct Foundation.Data
/// Abstraction for functionality that allows working with subprocesses.
public protocol ProcessProtocol {
/// The PID of the process.
///
/// Clients that don't really launch a process can return
/// a negative number to represent a "quasi-pid".
///
/// - SeeAlso: https://github.com/apple/swift/blob/main/docs/DriverParseableOutput.rst#quasi-pids
var processID: TSCBasic.Process.ProcessID { get }
/// Wait for the process to finish execution.
@discardableResult
func waitUntilExit() throws -> ProcessResult
static func launchProcess(
arguments: [String],
env: [String: String]
) throws -> Self
static func launchProcessAndWriteInput(
arguments: [String],
env: [String: String],
inputFileHandle: FileHandle
) throws -> Self
}
extension TSCBasic.Process: ProcessProtocol {
public static func launchProcess(
arguments: [String],
env: [String: String]
) throws -> TSCBasic.Process {
let process = Process(arguments: arguments, environment: env)
try process.launch()
return process
}
public static func launchProcessAndWriteInput(
arguments: [String],
env: [String: String],
inputFileHandle: FileHandle
) throws -> TSCBasic.Process {
let process = Process(arguments: arguments, environment: env)
let processInputStream = try process.launch()
var input: Data
// Write out the contents of the input handle and close the input stream
repeat {
input = inputFileHandle.availableData
processInputStream.write(input)
} while (input.count > 0)
processInputStream.flush()
try processInputStream.close()
return process
}
}
| f52ca5e6918affafcd5f6b3b61e6dcad | 31.069444 | 99 | 0.686444 | false | false | false | false |
CodaFi/swift | refs/heads/master | test/IDE/complete_property_delegate_attribute.swift | apache-2.0 | 2 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AFTER_PAREN | %FileCheck %s -check-prefix=AFTER_PAREN
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_MyEnum_NODOT | %FileCheck %s -check-prefix=ARG_MyEnum_NODOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_MyEnum_DOT | %FileCheck %s -check-prefix=ARG_MyEnum_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_MyEnum_NOBINDING | %FileCheck %s -check-prefix=ARG_MyEnum_NOBINDING
enum MyEnum {
case east, west
}
@propertyWrapper
struct MyStruct {
var value: MyEnum
init(initialValue: MyEnum) {}
init(arg1: MyEnum, arg2: Int) {}
}
var globalInt: Int = 1
var globalMyEnum: MyEnum = .east
struct TestStruct {
@MyStruct(#^AFTER_PAREN^#
var test1
// AFTER_PAREN: Begin completions, 2 items
// AFTER_PAREN-DAG: Decl[Constructor]/CurrNominal: ['(']{#initialValue: MyEnum#}[')'][#MyStruct#]; name=initialValue: MyEnum
// AFTER_PAREN-DAG: Decl[Constructor]/CurrNominal: ['(']{#arg1: MyEnum#}, {#arg2: Int#}[')'][#MyStruct#]; name=arg1: MyEnum, arg2: Int
// AFTER_PAREN: End completions
@MyStruct(arg1: #^ARG_MyEnum_NODOT^#
var test2
// ARG_MyEnum_NODOT: Begin completions
// ARG_MyEnum_NODOT-DAG: Decl[Struct]/CurrModule: TestStruct[#TestStruct#]; name=TestStruct
// ARG_MyEnum_NODOT-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: globalMyEnum[#MyEnum#]; name=globalMyEnum
// ARG_MyEnum_NODOT: End completions
@MyStruct(arg1: .#^ARG_MyEnum_DOT^#
var test3
// ARG_MyEnum_DOT: Begin completions, 3 items
// ARG_MyEnum_DOT-DAG: Decl[EnumElement]/CurrNominal/TypeRelation[Identical]: east[#MyEnum#]; name=east
// ARG_MyEnum_DOT-DAG: Decl[EnumElement]/CurrNominal/TypeRelation[Identical]: west[#MyEnum#]; name=west
// ARG_MyEnum_DOT-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): MyEnum#})[#(into: inout Hasher) -> Void#];
// ARG_MyEnum_DOT: End completions
@MyStruct(arg1: MyEnum.#^ARG_MyEnum_NOBINDING^#)
// ARG_MyEnum_NOBINDING: Begin completions
// ARG_MyEnum_NOBINDING-DAG: Decl[EnumElement]/CurrNominal: east[#MyEnum#];
// ARG_MyEnum_NOBINDING-DAG: Decl[EnumElement]/CurrNominal: west[#MyEnum#];
// ARG_MyEnum_NOBINDING: End completions
}
| c76805c8e4c9a4c001c48495b1517fc9 | 48.208333 | 162 | 0.723539 | false | true | false | false |
malt03/Balblair | refs/heads/master | Example/Balblair/QiitaRequest.swift | mit | 1 | //
// QiitaRequest.swift
// ApiClient
//
// Created by Koji Murata on 2016/08/04.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import Foundation
import Balblair
struct QiitaRequest: MyApiRequest {
typealias ResultType = [QiitaResult]
var encodeType: EncodeType { return .json }
let method = Balblair.Method.get
let path = "api/v2/items"
let parameters = QiitaParameters()
}
struct QiitaResult: Decodable {
let title: String
}
struct QiitaParameters: Encodable {
let page = 1
let per_page = 21
}
protocol MyApiRequest: ApiRequest {}
extension MyApiRequest {
func didFailure(error: ErrorModel<MyErrorResultType>) {}
func didSuccess(result: Self.ResultType) {}
func willBeginRequest(parameters: Self.ParametersType) {}
}
struct MyErrorResultType: Decodable {
}
| 019dd8b6c0a52e988c8a30742b825ae3 | 18.780488 | 59 | 0.727497 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Comments/EditCommentMultiLineCell.swift | gpl-2.0 | 1 | import Foundation
protocol EditCommentMultiLineCellDelegate: AnyObject {
func textViewHeightUpdated()
func textUpdated(_ updatedText: String?)
}
class EditCommentMultiLineCell: UITableViewCell, NibReusable {
// MARK: - Properties
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var textViewMinHeightConstraint: NSLayoutConstraint!
weak var delegate: EditCommentMultiLineCellDelegate?
// MARK: - View
override func awakeFromNib() {
super.awakeFromNib()
configureCell()
}
func configure(text: String? = nil) {
textView.text = text
adjustHeight()
}
}
// MARK: - UITextViewDelegate
extension EditCommentMultiLineCell: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
delegate?.textUpdated(textView.text)
adjustHeight()
}
}
// MARK: - Private Extension
private extension EditCommentMultiLineCell {
func configureCell() {
textView.font = .preferredFont(forTextStyle: .body)
textView.textColor = .text
textView.backgroundColor = .clear
}
func adjustHeight() {
let originalHeight = textView.frame.size.height
textView.sizeToFit()
let textViewHeight = ceilf(Float(max(textView.frame.size.height, textViewMinHeightConstraint.constant)))
textView.frame.size.height = CGFloat(textViewHeight)
if textViewHeight != Float(originalHeight) {
delegate?.textViewHeightUpdated()
}
}
}
| e700004c6a4af1a8f188e7a042c8dbc2 | 23.387097 | 112 | 0.686508 | false | false | false | false |
StefanLage/SLPagingViewSwift | refs/heads/master | SLPagingViewSwift/SLPagingViewSwift.swift | mit | 3 | //
// PagingView.swift
// TestSwift
//
// Created by Stefan Lage on 09/01/15.
// Copyright (c) 2015 Stefan Lage. All rights reserved.
//
import UIKit
public enum SLNavigationSideItemsStyle: Int {
case SLNavigationSideItemsStyleOnBounds = 40
case SLNavigationSideItemsStyleClose = 30
case SLNavigationSideItemsStyleNormal = 20
case SLNavigationSideItemsStyleFar = 10
case SLNavigationSideItemsStyleDefault = 0
case SLNavigationSideItemsStyleCloseToEachOne = -40
}
public typealias SLPagingViewMoving = ((subviews: [UIView])-> ())
public typealias SLPagingViewMovingRedefine = ((scrollView: UIScrollView, subviews: NSArray)-> ())
public typealias SLPagingViewDidChanged = ((currentPage: Int)-> ())
public class SLPagingViewSwift: UIViewController, UIScrollViewDelegate {
// MARK: - Public properties
var views = [Int : UIView]()
public var currentPageControlColor: UIColor?
public var tintPageControlColor: UIColor?
public var pagingViewMoving: SLPagingViewMoving?
public var pagingViewMovingRedefine: SLPagingViewMovingRedefine?
public var didChangedPage: SLPagingViewDidChanged?
public var navigationSideItemsStyle: SLNavigationSideItemsStyle = .SLNavigationSideItemsStyleDefault
// MARK: - Private properties
private var SCREENSIZE: CGSize {
return UIScreen.mainScreen().bounds.size
}
private var scrollView: UIScrollView!
private var pageControl: UIPageControl!
private var navigationBarView: UIView = UIView()
private var navItems: [UIView] = []
private var needToShowPageControl: Bool = false
private var isUserInteraction: Bool = false
private var indexSelected: Int = 0
// MARK: - Constructors
public required init(coder decoder: NSCoder) {
super.init(coder: decoder)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Here you can init your properties
}
// MARK: - Constructors with items & views
public convenience init(items: [UIView], views: [UIView]) {
self.init(items: items, views: views, showPageControl:false, navBarBackground:UIColor.whiteColor())
}
public convenience init(items: [UIView], views: [UIView], showPageControl: Bool){
self.init(items: items, views: views, showPageControl:showPageControl, navBarBackground:UIColor.whiteColor())
}
/*
* SLPagingViewController's constructor
*
* @param items should contain all subviews of the navigation bar
* @param navBarBackground navigation bar's background color
* @param views all subviews corresponding to each page
* @param showPageControl inform if we need to display the page control in the navigation bar
*
* @return Instance of SLPagingViewController
*/
public init(items: [UIView], views: [UIView], showPageControl: Bool, navBarBackground: UIColor) {
super.init(nibName: nil, bundle: nil)
needToShowPageControl = showPageControl
navigationBarView.backgroundColor = navBarBackground
isUserInteraction = true
for (i, v) in enumerate(items) {
let vSize: CGSize = (v as? UILabel)?._slpGetSize() ?? v.frame.size
let originX = (self.SCREENSIZE.width/2.0 - vSize.width/2.0) + CGFloat(i * 100)
v.frame = CGRectMake(originX, 8, vSize.width, vSize.height)
v.tag = i
let tap = UITapGestureRecognizer(target: self, action: "tapOnHeader:")
v.addGestureRecognizer(tap)
v.userInteractionEnabled = true
self.navigationBarView.addSubview(v)
self.navItems.append(v)
}
for (i, view) in enumerate(views) {
view.tag = i
self.views[i] = view
}
}
// MARK: - Constructors with controllers
public convenience init(controllers: [UIViewController]){
self.init(controllers: controllers, showPageControl: true, navBarBackground: UIColor.whiteColor())
}
public convenience init(controllers: [UIViewController], showPageControl: Bool){
self.init(controllers: controllers, showPageControl: true, navBarBackground: UIColor.whiteColor())
}
/*
* SLPagingViewController's constructor
*
* Use controller's title as a navigation item
*
* @param controllers view controllers containing sall subviews corresponding to each page
* @param navBarBackground navigation bar's background color
* @param showPageControl inform if we need to display the page control in the navigation bar
*
* @return Instance of SLPagingViewController
*/
public convenience init(controllers: [UIViewController], showPageControl: Bool, navBarBackground: UIColor){
var views = [UIView]()
var items = [UILabel]()
for ctr in controllers {
let item = UILabel()
item.text = ctr.title
views.append(ctr.view)
items.append(item)
}
self.init(items: items, views: views, showPageControl:showPageControl, navBarBackground:navBarBackground)
}
// MARK: - Constructors with items & controllers
public convenience init(items: [UIView], controllers: [UIViewController]){
self.init(items: items, controllers: controllers, showPageControl: true, navBarBackground: UIColor.whiteColor())
}
public convenience init(items: [UIView], controllers: [UIViewController], showPageControl: Bool){
self.init(items: items, controllers: controllers, showPageControl: showPageControl, navBarBackground: UIColor.whiteColor())
}
/*
* SLPagingViewController's constructor
*
* @param items should contain all subviews of the navigation bar
* @param navBarBackground navigation bar's background color
* @param controllers view controllers containing sall subviews corresponding to each page
* @param showPageControl inform if we need to display the page control in the navigation bar
*
* @return Instance of SLPagingViewController
*/
public convenience init(items: [UIView], controllers: [UIViewController], showPageControl: Bool, navBarBackground: UIColor){
var views = [UIView]()
for ctr in controllers {
views.append(ctr.view)
}
self.init(items: items, views: views, showPageControl:showPageControl, navBarBackground:navBarBackground)
}
// MARK: - Life cycle
public override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setupPagingProcess()
self.setCurrentIndex(self.indexSelected, animated: false)
}
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.navigationBarView.frame = CGRectMake(0, 0, self.SCREENSIZE.width, 44)
}
// MARK: - Public methods
/*
* Update the state of the UserInteraction on the navigation bar
*
* @param activate state you want to set to UserInteraction
*/
public func updateUserInteractionOnNavigation(active: Bool){
self.isUserInteraction = active
}
/*
* Set the current index page and scroll to its position
*
* @param index of the wanted page
* @param animated animate the moving
*/
public func setCurrentIndex(index: Int, animated: Bool){
// Be sure we got an existing index
if(index < 0 || index > self.navigationBarView.subviews.count-1){
var exc = NSException(name: "Index out of range", reason: "The index is out of range of subviews's countsd!", userInfo: nil)
exc.raise()
}
self.indexSelected = index
// Get the right position and update it
let xOffset = CGFloat(index) * self.SCREENSIZE.width
self.scrollView.setContentOffset(CGPointMake(xOffset, self.scrollView.contentOffset.y), animated: animated)
}
// MARK: - Internal methods
private func setupPagingProcess() {
var frame: CGRect = CGRectMake(0, 0, SCREENSIZE.width, self.view.frame.height)
self.scrollView = UIScrollView(frame: frame)
self.scrollView.backgroundColor = UIColor.clearColor()
self.scrollView.pagingEnabled = true
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.delegate = self
self.scrollView.bounces = false
self.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: -80, right: 0)
self.view.addSubview(self.scrollView)
// Adds all views
self.addViews()
if(self.needToShowPageControl){
// Make the page control
self.pageControl = UIPageControl(frame: CGRectMake(0, 35, 0, 0))
self.pageControl.numberOfPages = self.navigationBarView.subviews.count
self.pageControl.currentPage = 0
if self.currentPageControlColor != nil {
self.pageControl.currentPageIndicatorTintColor = self.currentPageControlColor
}
if self.tintPageControlColor != nil {
self.pageControl.pageIndicatorTintColor = self.tintPageControlColor
}
self.navigationBarView.addSubview(self.pageControl)
}
self.navigationController?.navigationBar.addSubview(self.navigationBarView)
}
// Loads all views
private func addViews() {
if self.views.count > 0 {
let width = SCREENSIZE.width * CGFloat(self.views.count)
let height = self.view.frame.height
self.scrollView.contentSize = CGSize(width: width, height: height)
var i: Int = 0
while let v = views[i] {
v.frame = CGRectMake(self.SCREENSIZE.width * CGFloat(i), 0, self.SCREENSIZE.width, self.SCREENSIZE.height)
self.scrollView.addSubview(v)
i++
}
}
}
private func sendNewIndex(scrollView: UIScrollView){
let xOffset = Float(scrollView.contentOffset.x)
var currentIndex = (Int(roundf(xOffset)) % (self.navigationBarView.subviews.count * Int(self.SCREENSIZE.width))) / Int(self.SCREENSIZE.width)
if self.needToShowPageControl && self.pageControl.currentPage != currentIndex {
self.pageControl.currentPage = currentIndex
self.didChangedPage?(currentPage: currentIndex)
}
}
func getOriginX(vSize: CGSize, idx: CGFloat, distance: CGFloat, xOffset: CGFloat) -> CGFloat{
var result = self.SCREENSIZE.width / 2.0 - vSize.width/2.0
result += (idx * distance)
result -= xOffset / (self.SCREENSIZE.width / distance)
return result
}
// Scroll to the view tapped
func tapOnHeader(recognizer: UITapGestureRecognizer){
if let key = recognizer.view?.tag, view = self.views[key] where self.isUserInteraction {
self.scrollView.scrollRectToVisible(view.frame, animated: true)
}
}
// MARK: - UIScrollViewDelegate
public func scrollViewDidScroll(scrollView: UIScrollView) {
let xOffset = scrollView.contentOffset.x
let distance = CGFloat(100 + self.navigationSideItemsStyle.rawValue)
for (i, v) in enumerate(self.navItems) {
let vSize = v.frame.size
let originX = self.getOriginX(vSize, idx: CGFloat(i), distance: CGFloat(distance), xOffset: xOffset)
v.frame = CGRectMake(originX, 8, vSize.width, vSize.height)
}
self.pagingViewMovingRedefine?(scrollView: scrollView, subviews: self.navItems)
self.pagingViewMoving?(subviews: self.navItems)
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
self.sendNewIndex(scrollView)
}
public func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
self.sendNewIndex(scrollView)
}
}
extension UILabel {
func _slpGetSize() -> CGSize? {
return (text as NSString?)?.sizeWithAttributes([NSFontAttributeName: font])
}
} | 14cea7224301427eb70488e283a3d151 | 41.083056 | 149 | 0.650482 | false | false | false | false |
yoha/Ventori | refs/heads/master | Ventori/AddViewController.swift | mit | 1 | //
// AddViewController.swift
// Ventori
//
// Created by Yohannes Wijaya on 6/8/17.
// Copyright © 2017 Corruption of Conformity. All rights reserved.
//
import UIKit
protocol AddViewControllerDelegate {
func getInventory(_ inventory: Inventory)
}
class AddViewController: UIViewController {
// MARK: - Stored Properties
var inventory: Inventory!
var counter = 0 {
willSet {
self.counterLabel.text = String(describing: newValue)
}
}
var delegate: AddViewControllerDelegate?
enum Icon: String {
case box, decrement, increment
func getName() -> String {
switch self {
case .box: return "box100"
case .decrement: return "Minus100"
case .increment: return "Plus100"
}
}
}
// MARK: - IBOutlet Properties
@IBOutlet weak var inventoryImageView: UIImageView!
@IBOutlet weak var inventoryNameTextField: UITextField!
@IBOutlet weak var counterLabel: UILabel!
@IBOutlet weak var decrementButton: UIButton!
@IBOutlet weak var incrementButton: UIButton!
// MARK: - IBAction Methods
@IBAction func cancelBarButtonItemDidTouch(_ sender: UIBarButtonItem) {
self.dismissAddViewController()
}
@IBAction func saveBarButtonItemDidTouch(_ sender: UIBarButtonItem) {
guard let validInventoryName = self.inventoryNameTextField.text, let validCounter = self.counterLabel.text else { return }
self.inventory = Inventory(name: validInventoryName, count: validCounter, image: self.inventoryImageView.image, modifiedDate: self.getCurrentDateAndTime())
self.delegate?.getInventory(self.inventory)
self.dismissAddViewController()
}
@IBAction func decrementButtonDidTouch(_ sender: UIButton) {
guard self.counter != 0 else { return }
self.counter -= 1
}
@IBAction func incrementButtonDidTouch(_ sender: UIButton) {
self.counter += 1
}
// MARK: - UIViewController Methods
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.hidesBackButton = true
self.decrementButton.setTitle(String(), for: .normal)
self.decrementButton.setImage(UIImage(named: Icon.decrement.getName()), for: .normal)
self.incrementButton.setTitle("", for: .normal)
self.incrementButton.setImage(UIImage(named: Icon.increment.getName()), for: .normal)
self.inventoryNameTextField.returnKeyType = .done
self.inventoryNameTextField.delegate = self
self.addGesturesToControlsWithin(self)
if self.presentingViewController is UINavigationController {
self.load(Inventory(name: "Inventory Name", count: "0", image: UIImage(named: Icon.box.getName()), modifiedDate: self.getCurrentDateAndTime()))
}
else {
self.load(self.inventory)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.isToolbarHidden = true
}
// MARK: - Helper Methods
func addGesturesToControlsWithin(_ viewController: AddViewController) {
let dismissKeyboardGesture = UITapGestureRecognizer(target: viewController, action: #selector(AddViewController.dismissKeyboardIfPresent))
viewController.view.addGestureRecognizer(dismissKeyboardGesture)
// -----
let tapImageViewToPresentImagePickerActionSheet = UITapGestureRecognizer(target: viewController, action: #selector(AddViewController.presentImagePickerActionSheet))
viewController.inventoryImageView.isUserInteractionEnabled = true
viewController.inventoryImageView.addGestureRecognizer(tapImageViewToPresentImagePickerActionSheet)
}
func dismissKeyboardIfPresent() {
self.inventoryNameTextField.resignFirstResponder()
}
func dismissAddViewController() {
if self.presentingViewController is UINavigationController {
self.dismiss(animated: true, completion: nil)
}
else { self.navigationController?.popViewController(animated: true) }
}
func load(_ inventory: Inventory) {
self.inventoryNameTextField.text = inventory.name
self.inventoryImageView.image = inventory.image
self.counterLabel.text = inventory.count
self.counter = Int(inventory.count)!
}
func initAndPresentCameraWith(_ imagePickerController: UIImagePickerController) {
guard UIImagePickerController.isSourceTypeAvailable(.camera) == true else {
let noCameraAlertController = UIAlertController(title: "Error: Missing Camera",
message: "The built-in camera may be malfunctioning",
preferredStyle: .alert)
let okAlertAction = UIAlertAction(title: "OK",
style: .cancel,
handler: nil)
noCameraAlertController.addAction(okAlertAction)
self.present(noCameraAlertController, animated: true, completion: nil)
return
}
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
}
func initAndPresentPhotoLibraryWith(_ imagePickerController: UIImagePickerController) {
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}
func presentImagePickerActionSheet() {
let imagePickerController = UIImagePickerController()
imagePickerController.allowsEditing = true
imagePickerController.delegate = self
let imagePickerAlertController = UIAlertController(title: "Choose Image From",
message: nil,
preferredStyle: .actionSheet)
let cameraAlertAction = UIAlertAction(title: "Camera",
style: .default) { [weak self] (_) in
guard let weakSelf = self else { return }
weakSelf.initAndPresentCameraWith(imagePickerController)
}
let photoLibraryAlertAction = UIAlertAction(title: "Photo Library",
style: .default) { [weak self] (_) in
guard let weakSelf = self else { return }
weakSelf.initAndPresentPhotoLibraryWith(imagePickerController)
}
let cancelAlertAction = UIAlertAction(title: "Cancel",
style: .cancel,
handler: nil)
let _ = [cameraAlertAction, photoLibraryAlertAction, cancelAlertAction].map { (alertAction: UIAlertAction) -> Void in
imagePickerAlertController.addAction(alertAction)
}
self.present(imagePickerAlertController, animated: true, completion: nil)
}
func setupInventoryRelatedControls() {
self.inventoryImageView.contentMode = .scaleAspectFill
self.inventoryImageView.clipsToBounds = true
self.inventoryImageView.layer.borderWidth = 0.5
self.inventoryImageView.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.50).cgColor
self.inventoryImageView.layer.cornerRadius = 5
self.decrementButton.setTitle("", for: .normal)
self.decrementButton.setBackgroundImage(UIImage(named: Icon.decrement.getName()), for: .normal)
self.incrementButton.setTitle("", for: .normal)
self.incrementButton.setBackgroundImage(UIImage(named: Icon.increment.getName()), for: .normal)
}
}
extension AddViewController: CurrentAndDateTimeProtocol {}
extension AddViewController: UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let selectedImage = info[UIImagePickerControllerEditedImage] as? UIImage else { return }
self.inventoryImageView.image = selectedImage
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
extension AddViewController: UINavigationControllerDelegate {}
extension AddViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| 3dd829b8f98f3e8df63a98c1556e323c | 40.191781 | 172 | 0.636958 | false | false | false | false |
grachro/swift-layout | refs/heads/master | add-on/AutolayoutPullArea.swift | mit | 1 | //
// AutolayoutPullArea.swift
// swift-layout
//
// Created by grachro on 2014/09/15.
// Copyright (c) 2014年 grachro. All rights reserved.
//
import UIKit
class AutolayoutPullArea:ScrollViewPullArea {
fileprivate var _minHeight:CGFloat
fileprivate var _maxHeight:CGFloat
var topConstraint:NSLayoutConstraint?
var headerConstraint:NSLayoutConstraint?
let view = UIView()
fileprivate var _layout:Layout?
var layout:Layout {
get {return _layout!}
}
var pullCallback:((_ viewHeight:CGFloat, _ pullAreaHeight:CGFloat) -> Void)? = nil
init(minHeight:CGFloat, maxHeight:CGFloat, superview:UIView) {
self._minHeight = minHeight
self._maxHeight = maxHeight
_layout = Layout.addSubView(view, superview: superview)
.horizontalCenterInSuperview()
.leftIsSameSuperview()
.rightIsSameSuperview()
.top(-self._maxHeight).fromSuperviewTop().lastConstraint(&topConstraint)
.height(self._maxHeight).lastConstraint(&headerConstraint)
}
}
//implements ScrollViewPullArea
extension AutolayoutPullArea {
func minHeight() -> CGFloat {
return _minHeight
}
func maxHeight() -> CGFloat {
return _maxHeight
}
func animationSpeed() -> TimeInterval {
return 0.4
}
func show(viewHeight:CGFloat, pullAreaHeight:CGFloat) {
if viewHeight < pullAreaHeight {
self.topConstraint?.constant = -((pullAreaHeight - viewHeight) / 2 + viewHeight)
} else {
self.topConstraint?.constant = -viewHeight
}
self.headerConstraint?.constant = viewHeight
view.superview?.layoutIfNeeded()
self.pullCallback?(viewHeight, pullAreaHeight)
view.layoutIfNeeded()
}
}
| c5be6a7cb4df2a2a8877025e7484c670 | 24.662162 | 92 | 0.621906 | false | false | false | false |
Vienta/kuafu | refs/heads/master | kuafu/kuafu/src/Controller/KFVersionsViewController.swift | mit | 1 | //
// KFVersionsViewController.swift
// kuafu
//
// Created by Vienta on 15/7/20.
// Copyright (c) 2015年 www.vienta.me. All rights reserved.
//
import UIKit
class KFVersionsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tbvVersions: UITableView!
var versions: Array<Dictionary<String,String>>!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "KF_SETTINGS_HISTORY_VERSION".localized
self.versions = [["versionTitle":APP_DISPLAY_NAME + __KUAFU_1_0 + "KF_UPDATE_DESC".localized,"publishtime":"2015年8月8日","version":__KUAFU_1_0]]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - IBActions
// MARK: - Private Methods
// MARK: - Public Methods
// MARK: - UITableViewDelegate && UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.versions.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "versionsCellIdentifier"
var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellIdentifier)
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
var rowVersionInfo: Dictionary = self.versions[indexPath.row]
cell.textLabel?.text = rowVersionInfo["versionTitle"]
cell.detailTextLabel?.text = rowVersionInfo["publishtime"]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var rowVersionInfo: Dictionary = self.versions[indexPath.row]
var version: String? = rowVersionInfo["version"]
var versionTitle: String? = rowVersionInfo["versionTitle"]
let versionDetailViewController: KFVersionDetailViewController = KFVersionDetailViewController(nibName: "KFVersionDetailViewController", bundle: nil)
versionDetailViewController.version = version
versionDetailViewController.title = versionTitle
self.navigationController?.pushViewController(versionDetailViewController, animated: true)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 66
}
}
| dc51a7d95c33f180075ea6ea56cb7688 | 38.928571 | 157 | 0.704472 | false | false | false | false |
koalaylj/code-labs | refs/heads/master | swift/apple/main.swift | mit | 2 | //
// main.swift
// apple
//
// Created by koala on 11/23/15.
// Copyright © 2015 koala. All rights reserved.
//
import Foundation
print("Hello, World!")
//1. let声明常量,var声明变量
// 各种进制的字面量表示
let decimalInteger = 17
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 in hexadecimal notation
// 更易于阅读的写法
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1
//2. 定义类型别名 typealias
typealias AudioSample = UInt16
// decompose一个tuple时,对于不想使用的元素用’_’接收
let http404Error = (404, "Not Found")
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// prints "The status code is 404
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
//3. array
var arr = ["hello", "world"]
var brr = arr
brr[0] = "haw"
print(brr) // ["haw", "world"]
print(arr ) // ["hello", "world"]
brr.insert("aaaaaa", atIndex: 0)
print(brr)
print(arr)
var threeDoubles = Double[](count: 3, repeatedValue: 0.0)
// threeDoubles is of type Double[], and equals [0.0, 0.0, 0.0]
var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
// anotherThreeDoubles is inferred as Double[], and equals [2.5, 2.5, 2.5]
| af29cd2e5e303dc0d012a20c77033b03 | 21.894737 | 74 | 0.65859 | false | false | false | false |
JuweTakeheshi/ajuda | refs/heads/master | Ajuda/VC/JUWShelterViewController.swift | mit | 1 | //
// JUWShelterViewController.swift
// Ajuda
//
// Created by Juwe Takeheshi on 9/21/17.
// Copyright © 2017 Juwe Takeheshi. All rights reserved.
//
typealias OnResultsFound = (_ result: [JUWCollectionCenter], _ product: String)->()
import UIKit
class JUWShelterViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var searchController: UISearchController!
var productSearch: String?
var onResultsFound: OnResultsFound?
override func viewDidLoad() {
super.viewDidLoad()
customizeUserInterface()
customizeNavigationBarColors()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
searchBar.becomeFirstResponder()
}
func customizeUserInterface() {
searchBar.autocapitalizationType = .none
title = "Quiero ayudar con..."
let dismissButton = UIButton()
dismissButton.setImage(UIImage(named: "closeButtonOrange"), for: .normal)
dismissButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
dismissButton.addTarget(self, action: #selector(JUWShelterViewController.cancel(_:)), for: .touchUpInside)
let dismissBarButton = UIBarButtonItem(customView: dismissButton)
navigationItem.rightBarButtonItem = dismissBarButton
}
@IBAction func cancel(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
extension JUWShelterViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText != "" {
productSearch = searchText
}
else{
productSearch = nil
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
guard let product = productSearch else {
return
}
activityIndicator.startAnimating()
activityIndicator.isHidden = false
searchBar.resignFirstResponder()
JUWCollectionCenterManager().collectionCenters(whichNeed: product) { collectionCenters in
self.onResultsFound?(collectionCenters, product)
self.dismiss(animated: true, completion: nil)
}
}
}
| 3ad2f98c68deda903d518e54a6886527 | 31.253521 | 114 | 0.679039 | false | false | false | false |
alsrgv/tensorflow | refs/heads/master | tensorflow/lite/experimental/swift/Sources/Interpreter.swift | apache-2.0 | 2 | // Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import TensorFlowLiteC
/// A TensorFlow Lite interpreter that performs inference from a given model.
public final class Interpreter {
/// The `TFL_Interpreter` C pointer type represented as an `UnsafePointer<TFL_Interpreter>`.
private typealias CInterpreter = OpaquePointer
/// Total number of input tensors associated with the model.
public var inputTensorCount: Int {
return Int(TFL_InterpreterGetInputTensorCount(cInterpreter))
}
/// Total number of output tensors associated with the model.
public var outputTensorCount: Int {
return Int(TFL_InterpreterGetOutputTensorCount(cInterpreter))
}
/// The underlying `TFL_Interpreter` C pointer.
private var cInterpreter: CInterpreter?
/// Creates a new model interpreter instance.
///
/// - Parameters:
/// - modelPath: Local file path to a TensorFlow Lite model.
/// - options: Custom configurations for the interpreter. The default is `nil` indicating that
/// the interpreter will determine the configuration options.
/// - Throws: An error if the model could not be loaded or the interpreter could not be created.
public init(modelPath: String, options: InterpreterOptions? = nil) throws {
guard let model = Model(filePath: modelPath) else { throw InterpreterError.failedToLoadModel }
let cInterpreterOptions: OpaquePointer? = try options.map { options in
guard let cOptions = TFL_NewInterpreterOptions() else {
throw InterpreterError.failedToCreateInterpreter
}
if let threadCount = options.threadCount, threadCount > 0 {
TFL_InterpreterOptionsSetNumThreads(cOptions, Int32(threadCount))
}
TFL_InterpreterOptionsSetErrorReporter(
cOptions,
{ (_, format, args) -> Void in
// Workaround for optionality differences for x86_64 (non-optional) and arm64 (optional).
let optionalArgs: CVaListPointer? = args
guard let cFormat = format,
let arguments = optionalArgs,
let message = String(cFormat: cFormat, arguments: arguments)
else {
return
}
print(String(describing: InterpreterError.tensorFlowLiteError(message)))
},
nil
)
return cOptions
}
defer { TFL_DeleteInterpreterOptions(cInterpreterOptions) }
guard let cInterpreter = TFL_NewInterpreter(model.cModel, cInterpreterOptions) else {
throw InterpreterError.failedToCreateInterpreter
}
self.cInterpreter = cInterpreter
}
deinit {
TFL_DeleteInterpreter(cInterpreter)
}
/// Invokes the interpreter to perform inference from the loaded graph.
///
/// - Throws: An error if the model was not ready because tensors were not allocated.
public func invoke() throws {
guard TFL_InterpreterInvoke(cInterpreter) == kTfLiteOk else {
throw InterpreterError.allocateTensorsRequired
}
}
/// Returns the input tensor at the given index.
///
/// - Parameters:
/// - index: The index for the input tensor.
/// - Throws: An error if the index is invalid or the tensors have not been allocated.
/// - Returns: The input tensor at the given index.
public func input(at index: Int) throws -> Tensor {
let maxIndex = inputTensorCount - 1
guard case 0...maxIndex = index else {
throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
}
guard let cTensor = TFL_InterpreterGetInputTensor(cInterpreter, Int32(index)),
let bytes = TFL_TensorData(cTensor),
let nameCString = TFL_TensorName(cTensor)
else {
throw InterpreterError.allocateTensorsRequired
}
guard let dataType = TensorDataType(type: TFL_TensorType(cTensor)) else {
throw InterpreterError.invalidTensorDataType
}
let name = String(cString: nameCString)
let rank = TFL_TensorNumDims(cTensor)
let dimensions = (0..<rank).map { Int(TFL_TensorDim(cTensor, $0)) }
let shape = TensorShape(dimensions)
let byteCount = TFL_TensorByteSize(cTensor)
let data = Data(bytes: bytes, count: byteCount)
let cQuantizationParams = TFL_TensorQuantizationParams(cTensor)
let scale = cQuantizationParams.scale
let zeroPoint = Int(cQuantizationParams.zero_point)
var quantizationParameters: QuantizationParameters? = nil
if scale != 0.0 {
quantizationParameters = QuantizationParameters(scale: scale, zeroPoint: zeroPoint)
}
let tensor = Tensor(
name: name,
dataType: dataType,
shape: shape,
data: data,
quantizationParameters: quantizationParameters
)
return tensor
}
/// Returns the output tensor at the given index.
///
/// - Parameters:
/// - index: The index for the output tensor.
/// - Throws: An error if the index is invalid, tensors haven't been allocated, or interpreter
/// hasn't been invoked for models that dynamically compute output tensors based on the values
/// of its input tensors.
/// - Returns: The output tensor at the given index.
public func output(at index: Int) throws -> Tensor {
let maxIndex = outputTensorCount - 1
guard case 0...maxIndex = index else {
throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
}
guard let cTensor = TFL_InterpreterGetOutputTensor(cInterpreter, Int32(index)),
let bytes = TFL_TensorData(cTensor),
let nameCString = TFL_TensorName(cTensor)
else {
throw InterpreterError.invokeInterpreterRequired
}
guard let dataType = TensorDataType(type: TFL_TensorType(cTensor)) else {
throw InterpreterError.invalidTensorDataType
}
let name = String(cString: nameCString)
let rank = TFL_TensorNumDims(cTensor)
let dimensions = (0..<rank).map { Int(TFL_TensorDim(cTensor, $0)) }
let shape = TensorShape(dimensions)
let byteCount = TFL_TensorByteSize(cTensor)
let data = Data(bytes: bytes, count: byteCount)
let cQuantizationParams = TFL_TensorQuantizationParams(cTensor)
let scale = cQuantizationParams.scale
let zeroPoint = Int(cQuantizationParams.zero_point)
var quantizationParameters: QuantizationParameters? = nil
if scale != 0.0 {
quantizationParameters = QuantizationParameters(scale: scale, zeroPoint: zeroPoint)
}
let tensor = Tensor(
name: name,
dataType: dataType,
shape: shape,
data: data,
quantizationParameters: quantizationParameters
)
return tensor
}
/// Resizes the input tensor at the given index to the specified tensor shape.
///
/// - Note: After resizing an input tensor, the client **must** explicitly call
/// `allocateTensors()` before attempting to access the resized tensor data or invoking the
/// interpreter to perform inference.
/// - Parameters:
/// - index: The index for the input tensor.
/// - shape: The shape that the input tensor should be resized to.
/// - Throws: An error if the input tensor at the given index could not be resized.
public func resizeInput(at index: Int, to shape: TensorShape) throws {
let maxIndex = inputTensorCount - 1
guard case 0...maxIndex = index else {
throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
}
guard TFL_InterpreterResizeInputTensor(
cInterpreter,
Int32(index),
shape.int32Dimensions,
Int32(shape.rank)
) == kTfLiteOk
else {
throw InterpreterError.failedToResizeInputTensor(index: index)
}
}
/// Copies the given data to the input tensor at the given index.
///
/// - Parameters:
/// - data: The data to be copied to the input tensor's data buffer.
/// - index: The index for the input tensor.
/// - Throws: An error if the `data.count` does not match the input tensor's `data.count` or if
/// the given index is invalid.
/// - Returns: The input tensor with the copied data.
@discardableResult
public func copy(_ data: Data, toInputAt index: Int) throws -> Tensor {
let maxIndex = inputTensorCount - 1
guard case 0...maxIndex = index else {
throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
}
guard let cTensor = TFL_InterpreterGetInputTensor(cInterpreter, Int32(index)) else {
throw InterpreterError.allocateTensorsRequired
}
let byteCount = TFL_TensorByteSize(cTensor)
guard data.count == byteCount else {
throw InterpreterError.invalidTensorDataCount(provided: data.count, required: byteCount)
}
#if swift(>=5.0)
let status = data.withUnsafeBytes {
TFL_TensorCopyFromBuffer(cTensor, $0.baseAddress, data.count)
}
#else
let status = data.withUnsafeBytes { TFL_TensorCopyFromBuffer(cTensor, $0, data.count) }
#endif // swift(>=5.0)
guard status == kTfLiteOk else { throw InterpreterError.failedToCopyDataToInputTensor }
return try input(at: index)
}
/// Allocates memory for all input tensors based on their `TensorShape`s.
///
/// - Note: This is a relatively expensive operation and should only be called after creating the
/// interpreter and/or resizing any input tensors.
/// - Throws: An error if memory could not be allocated for the input tensors.
public func allocateTensors() throws {
guard TFL_InterpreterAllocateTensors(cInterpreter) == kTfLiteOk else {
throw InterpreterError.failedToAllocateTensors
}
}
}
// MARK: - Extensions
extension String {
/// Returns a new `String` initialized by using the given format C array as a template into which
/// the remaining argument values are substituted according to the user’s default locale.
///
/// - Note: Returns `nil` if a new `String` could not be constructed from the given values.
/// - Parameters:
/// - cFormat: The format C array as a template for substituting values.
/// - arguments: A C pointer to a `va_list` of arguments to substitute into `cFormat`.
init?(cFormat: UnsafePointer<CChar>, arguments: CVaListPointer) {
var buffer: UnsafeMutablePointer<CChar>?
guard vasprintf(&buffer, cFormat, arguments) != 0, let cString = buffer else { return nil }
self.init(validatingUTF8: cString)
}
}
| 4888ac7736760ab0c52cf6fe380f75ee | 39.279851 | 100 | 0.702455 | false | false | false | false |
abertelrud/swift-package-manager | refs/heads/main | Sources/Basics/ImportScanning.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Dispatch
import class Foundation.JSONDecoder
import struct TSCBasic.AbsolutePath
import class TSCBasic.Process
private let defaultImports = ["Swift", "SwiftOnoneSupport", "_Concurrency", "_StringProcessing"]
private struct Imports: Decodable {
let imports: [String]
}
public protocol ImportScanner {
func scanImports(_ filePathToScan: AbsolutePath, callbackQueue: DispatchQueue, completion: @escaping (Result<[String], Error>) -> Void)
}
public struct SwiftcImportScanner: ImportScanner {
private let swiftCompilerEnvironment: EnvironmentVariables
private let swiftCompilerFlags: [String]
private let swiftCompilerPath: AbsolutePath
public init(swiftCompilerEnvironment: EnvironmentVariables, swiftCompilerFlags: [String], swiftCompilerPath: AbsolutePath) {
self.swiftCompilerEnvironment = swiftCompilerEnvironment
self.swiftCompilerFlags = swiftCompilerFlags
self.swiftCompilerPath = swiftCompilerPath
}
public func scanImports(_ filePathToScan: AbsolutePath,
callbackQueue: DispatchQueue,
completion: @escaping (Result<[String], Error>) -> Void) {
let cmd = [swiftCompilerPath.pathString,
filePathToScan.pathString,
"-scan-dependencies", "-Xfrontend", "-import-prescan"] + self.swiftCompilerFlags
TSCBasic.Process.popen(arguments: cmd, environment: self.swiftCompilerEnvironment, queue: callbackQueue) { result in
dispatchPrecondition(condition: .onQueue(callbackQueue))
do {
let stdout = try result.get().utf8Output()
let imports = try JSONDecoder.makeWithDefaults().decode(Imports.self, from: stdout).imports
.filter { !defaultImports.contains($0) }
callbackQueue.async {
completion(.success(imports))
}
} catch {
callbackQueue.async {
completion(.failure(error))
}
}
}
}
}
| d22e61c91d448ff3cebf3e2d37ee36fd | 39.184615 | 139 | 0.619449 | false | false | false | false |
1yvT0s/Nuke | refs/heads/master | Example/Nuke/PreheatingDemoViewController.swift | mit | 5 | //
// PreheatingDemoViewController.swift
// Nuke
//
// Created by kean on 09/13/2015.
// Copyright (c) 2015 kean. All rights reserved.
//
import UIKit
import Nuke
private let cellReuseID = "reuseID"
class PreheatingDemoViewController: UICollectionViewController, ImageCollectionViewPreheatingControllerDelegate {
var photos: [NSURL]!
var preheatController: ImageCollectionViewPreheatingController?
override func viewDidLoad() {
super.viewDidLoad()
self.photos = demoPhotosURLs
self.collectionView?.backgroundColor = UIColor.whiteColor()
self.collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: cellReuseID)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.updateItemSize()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.preheatController = ImageCollectionViewPreheatingController(collectionView: self.collectionView!)
self.preheatController?.delegate = self
self.preheatController?.updatePreheatRect()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
// Resets preheat rect and stop preheating images via delegate call.
self.preheatController?.resetPreheatRect()
self.preheatController = nil
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.updateItemSize()
}
func updateItemSize() {
let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumLineSpacing = 2.0
layout.minimumInteritemSpacing = 2.0
let itemsPerRow = 4
let side = (Double(self.view.bounds.size.width) - Double(itemsPerRow - 1) * 2.0) / Double(itemsPerRow)
layout.itemSize = CGSize(width: side, height: side)
}
// MARK: UICollectionView
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photos.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellReuseID, forIndexPath: indexPath)
cell.backgroundColor = UIColor(white: 235.0 / 255.0, alpha: 1.0)
let imageView = self.imageViewForCell(cell)
let imageURL = self.photos[indexPath.row]
imageView.setImageWithRequest(self.imageRequestWithURL(imageURL))
return cell
}
func imageRequestWithURL(URL: NSURL) -> ImageRequest {
func imageTargetSize() -> CGSize {
let size = (self.collectionViewLayout as! UICollectionViewFlowLayout).itemSize
let scale = UIScreen.mainScreen().scale
return CGSize(width: size.width * scale, height: size.height * scale)
}
return ImageRequest(URL: URL, targetSize: imageTargetSize(), contentMode: .AspectFill)
}
override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
self.imageViewForCell(cell).prepareForReuse()
}
func imageViewForCell(cell: UICollectionViewCell) -> Nuke.ImageView {
var imageView = cell.viewWithTag(15) as? Nuke.ImageView
if imageView == nil {
imageView = Nuke.ImageView(frame: cell.bounds)
imageView!.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
imageView!.tag = 15
cell.addSubview(imageView!)
}
return imageView!
}
// MARK: ImageCollectionViewPreheatingControllerDelegate
func collectionViewPreheatingController(controller: ImageCollectionViewPreheatingController, didUpdateWithAddedIndexPaths addedIndexPaths: [NSIndexPath], removedIndexPaths: [NSIndexPath]) {
func requestForIndexPaths(indexPaths: [NSIndexPath]) -> [ImageRequest] {
return indexPaths.map { return self.imageRequestWithURL(self.photos[$0.row]) }
}
Nuke.startPreheatingImages(requestForIndexPaths(addedIndexPaths))
Nuke.stopPreheatingImages(requestForIndexPaths(removedIndexPaths))
self.logAddedIndexPaths(addedIndexPaths, removeIndexPaths: removedIndexPaths)
}
func logAddedIndexPaths(addedIndexPath: [NSIndexPath], removeIndexPaths: [NSIndexPath]) {
func stringForIndexPaths(indexPaths: [NSIndexPath]) -> String {
guard indexPaths.count > 0 else {
return "()"
}
return indexPaths.map{ return "\($0.item)" }.joinWithSeparator(" ")
}
print("did change preheat rect with added indexes \(stringForIndexPaths(addedIndexPath)), removed indexes \(stringForIndexPaths(removeIndexPaths))")
}
}
| 6575407f799c12a7e2b577e0eded89c4 | 39.459677 | 193 | 0.690253 | false | false | false | false |
Ceroce/SwiftRay | refs/heads/master | SwiftRay/SwiftRay/Hitable.swift | mit | 1 | //
// Hitable.swift
// SwiftRay
//
// Created by Renaud Pradenc on 23/11/2016.
// Copyright © 2016 Céroce. All rights reserved.
//
struct HitIntersection {
let distance: Float // Distance from the origin of the ray
let position: Vec3
let normal: Vec3
let material: Material
}
protocol Hitable {
func hit(ray: Ray, distMin: Float, distMax: Float) -> HitIntersection?
func boundingBox(startTime: Float, endTime: Float) -> BoundingBox
}
func closestHit(ray: Ray, hitables: [Hitable]) -> HitIntersection? {
var closerIntersection: HitIntersection? = nil
var closestSoFar: Float = Float.infinity
for hitable in hitables {
if let intersection = hitable.hit(ray: ray, distMin: 0.001, distMax: closestSoFar) {
if intersection.distance < closestSoFar {
closestSoFar = intersection.distance
closerIntersection = intersection
}
}
}
return closerIntersection
}
/*func closestHit(ray: Ray, hitables: [Hitable]) -> HitIntersection? {
for hitable in hitables { // There is only one
return hitable.hit(ray: ray, distMin: 0.001, distMax: Float.infinity)
}
return nil
}*/
| df7796f5090971f038a21b15024d9136 | 27.761905 | 92 | 0.654801 | false | false | false | false |
volodg/iAsync.social | refs/heads/master | Pods/ReactiveKit/ReactiveKit/Disposables/BlockDisposable.swift | mit | 1 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/// A disposable that executes the given block upon disposing.
public final class BlockDisposable: DisposableType {
public var isDisposed: Bool {
return handler == nil
}
private var handler: (() -> ())?
private let lock = RecursiveLock(name: "com.ReactiveKit.ReactiveKit.BlockDisposable")
public init(_ handler: () -> ()) {
self.handler = handler
}
public func dispose() {
lock.lock()
handler?()
handler = nil
lock.unlock()
}
}
public class DeinitDisposable: DisposableType {
public var otherDisposable: DisposableType? = nil
public var isDisposed: Bool {
return otherDisposable == nil
}
public init(disposable: DisposableType) {
otherDisposable = disposable
}
public func dispose() {
otherDisposable?.dispose()
}
deinit {
otherDisposable?.dispose()
}
}
| 7527e8140e0a3aef1e7985a972985ebc | 29.328358 | 87 | 0.708169 | false | false | false | false |
che1404/RGViperChat | refs/heads/master | RGViperChat/CreateChat/DataManager/API/CreateChatAPIDataManager.swift | mit | 1 | //
// Created by Roberto Garrido
// Copyright (c) 2017 Roberto Garrido. All rights reserved.
//
import Foundation
import FirebaseDatabase
import FirebaseAuth
class CreateChatAPIDataManager: CreateChatAPIDataManagerInputProtocol {
let root = Database.database().reference()
init() {}
func fetchUsers(completion: @escaping (Result<[User]>) -> Void) {
guard let currentUser = Auth.auth().currentUser else {
completion(.failure(NSError(domain: "createChat", code: -1, userInfo: [NSLocalizedDescriptionKey: "User not logged in"])))
return
}
root.child("User").observeSingleEvent(of: .value, with: { snapshot in
if let userDictionaries = snapshot.value as? [String: Any] {
var users: [User] = []
for userDictionaryWithKey in userDictionaries where currentUser.uid != userDictionaryWithKey.key {
if let userDictionary = userDictionaryWithKey.value as? [String: Any] {
if let username = userDictionary["name"] as? String {
let user = User(username: username, userID: userDictionaryWithKey.key)
users.append(user)
}
}
}
completion(.success(users))
} else {
completion(.failure(NSError(domain: "fetchUsers", code: -1, userInfo: [NSLocalizedDescriptionKey: "Couldn't fetch users"])))
}
})
}
func createChat(withUser user: User, completion: @escaping (Result<Chat>) -> Void) {
guard let currentUser = Auth.auth().currentUser else {
completion(.failure(NSError(domain: "createChat", code: -1, userInfo: [NSLocalizedDescriptionKey: "User not logged in"])))
return
}
// Get current user display name
root.child("User/\(currentUser.uid)/name").observeSingleEvent(of: .value, with: { snapshot in
if let currentUsername = snapshot.value as? String {
// Create chat, and add users to the chat
let chatDictionary = [
"users": [
currentUser.uid: currentUsername,
user.userID: user.username
]
]
let chatID = self.root.child("Chat").childByAutoId().key
self.root.child("Chat/\(chatID)").setValue(chatDictionary, withCompletionBlock: { error, reference in
if error == nil {
// Add chat to current user
let chatJoinTimestamp = Date().timeIntervalSince1970
self.root.child("User/\(currentUser.uid)/chats/\(chatID)").setValue(chatJoinTimestamp, withCompletionBlock: { error, reference in
if error != nil {
completion(.failure(NSError(domain: "createChat", code: -1, userInfo: [NSLocalizedDescriptionKey: error!.localizedDescription])))
} else {
// Add chat to the other participant user
self.root.child("User/\(user.userID)/chats/\(chatID)").setValue(chatJoinTimestamp, withCompletionBlock: { error, reference in
if error != nil {
completion(.failure(NSError(domain: "createChat", code: -1, userInfo: [NSLocalizedDescriptionKey: error!.localizedDescription])))
} else {
completion(.success(Chat(chatID: reference.key, displayName: user.username, senderID: currentUser.uid, senderDisplayName: currentUsername, receiverID: user.userID, lastMessage: "")))
}
})
}
})
} else {
completion(.failure(NSError(domain: "createChat", code: -1, userInfo: [NSLocalizedDescriptionKey: "Error creating chat"])))
}
})
}
})
}
}
| 0f08e3f5029dd7a6d4dece592bafacf9 | 49.409639 | 222 | 0.536807 | false | false | false | false |
szukuro/spacecat-swift | refs/heads/master | Space Cat/HudNode.swift | mit | 1 | //
// HudNode.swift
// Space Cat
//
// Created by László Györi on 28/07/14.
// Copyright (c) 2014 László Györi. All rights reserved.
//
import UIKit
import SpriteKit
class HudNode: SKNode {
var lives : NSInteger = MaxLives
var score : NSInteger = 0
}
extension HudNode {
class func hudAtPosition(position:CGPoint, frame:CGRect) -> HudNode {
let hud = self.node() as HudNode
hud.position = position
hud.zPosition = 10
hud.name = "HUD"
let catHead = SKSpriteNode(imageNamed: "HUD_cat_1")
catHead.position = CGPointMake(30, -10)
hud.addChild(catHead)
var lastLifeBar : SKSpriteNode?
for var i = 0; i < hud.lives; ++i {
let lifeBar = SKSpriteNode(imageNamed: "HUD_life_1")
lifeBar.name = "Life\(i + 1)"
hud.addChild(lifeBar)
if (lastLifeBar) {
lifeBar.position = CGPointMake(lastLifeBar!.position.x + 10, lastLifeBar!.position.y)
}
else {
lifeBar.position = CGPointMake(catHead.position.x + 30, catHead.position.y)
}
lastLifeBar = lifeBar
}
let scoreLabel = SKLabelNode(fontNamed: "Futura-CondensedExtraBold")
scoreLabel.name = "Score"
scoreLabel.text = "\(hud.score)"
scoreLabel.fontSize = 20
scoreLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Right
scoreLabel.position = CGPointMake(frame.size.width - 20,
-10)
hud.addChild(scoreLabel)
return hud
}
func addPoints(points:Int) {
self.score += points
let scoreLabel = self.childNodeWithName("Score") as SKLabelNode
scoreLabel.text = "\(self.score)"
}
func loseLife() -> Bool {
if (self.lives > 0) {
let lifeNodeName = "Life\(self.lives)"
let lifeToRemove = self.childNodeWithName(lifeNodeName)
lifeToRemove.removeFromParent()
self.lives--
}
return self.lives == 0
}
} | 15fc084627137d067ba92aefea521d5e | 27 | 101 | 0.556574 | false | false | false | false |
darina/omim | refs/heads/master | iphone/Maps/UI/Search/Tabs/CategoriesTab/SearchCategoryCell.swift | apache-2.0 | 5 | final class SearchCategoryCell: MWMTableViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
private var category: String = ""
func update(with category: String) {
self.category = category
iconImageView.mwm_name = String(format: "ic_%@", category)
titleLabel.text = L(category)
}
override func applyTheme() {
super.applyTheme()
iconImageView.mwm_name = String(format: "ic_%@", category)
}
}
| 872ce035bd491d56f537b644fffef5fc | 28.5 | 62 | 0.701271 | false | false | false | false |
a2/RxSwift | refs/heads/master | RxExample/RxExample/Services/ImageService.swift | mit | 11 | //
// ImageService.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
#if os(iOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
protocol ImageService {
func imageFromURL(URL: NSURL) -> Observable<Image>
}
class DefaultImageService: ImageService {
static let sharedImageService = DefaultImageService() // Singleton
let $: Dependencies = Dependencies.sharedDependencies
// 1rst level cache
let imageCache = NSCache()
// 2nd level cache
let imageDataCache = NSCache()
private init() {
// cost is approx memory usage
self.imageDataCache.totalCostLimit = 10 * MB
self.imageCache.countLimit = 20
}
func decodeImage(imageData: NSData) -> Observable<Image> {
return just(imageData)
.observeOn($.backgroundWorkScheduler)
.map { data in
let maybeImage = Image(data: data)
if maybeImage == nil {
// some error
throw apiError("Decoding image error")
}
let image = maybeImage!
return image
}
.observeOn($.mainScheduler)
}
func imageFromURL(URL: NSURL) -> Observable<Image> {
return deferred {
let maybeImage = self.imageDataCache.objectForKey(URL) as? Image
let decodedImage: Observable<Image>
// best case scenario, it's already decoded an in memory
if let image = maybeImage {
decodedImage = just(image)
}
else {
let cachedData = self.imageDataCache.objectForKey(URL) as? NSData
// does image data cache contain anything
if let cachedData = cachedData {
decodedImage = self.decodeImage(cachedData)
}
else {
// fetch from network
decodedImage = self.$.URLSession.rx_data(NSURLRequest(URL: URL))
.doOn(next: { data in
self.imageDataCache.setObject(data, forKey: URL)
})
.flatMap(self.decodeImage)
}
}
return decodedImage.doOn(next: { image in
self.imageCache.setObject(image, forKey: URL)
})
}.observeOn($.mainScheduler)
}
}
| 3bbf1ddeac7f5de85f553497946b8b0c | 27.5 | 84 | 0.527436 | false | false | false | false |
Onix-Systems/ios-mazazine-reader | refs/heads/master | MazazineReader/MasterViewController.swift | apache-2.0 | 1 | // Copyright 2017 Onix-Systems
// 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
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem
}
override func viewWillAppear(_ animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! Date
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object as AnyObject?
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let object = objects[indexPath.row] as! Date
cell.textLabel!.text = object.description
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
objects.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .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.
}
}
}
| 746f7b77f3be7eec288a9c8b29121b6c | 36.658537 | 136 | 0.689443 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | refs/heads/master | Source/IrregularBorderView.swift | apache-2.0 | 3 | //
// IrregularBorderStyle.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 26/10/2015.
// Copyright © 2015 edX. All rights reserved.
//
import UIKit
struct CellPosition : OptionSetType {
let rawValue : UInt
static let Top = CellPosition(rawValue: 1 << 0)
static let Bottom = CellPosition(rawValue: 1 << 1)
var roundedCorners : UIRectCorner {
var result = UIRectCorner()
if self.contains(CellPosition.Top) {
result = result.union([.TopLeft, .TopRight])
}
if self.contains(CellPosition.Bottom) {
result = result.union([.BottomLeft, .BottomRight])
}
return result
}
}
struct IrregularBorderStyle {
let corners : UIRectCorner
let base : BorderStyle
init(corners : UIRectCorner, base : BorderStyle) {
self.corners = corners
self.base = base
}
init(position : CellPosition, base : BorderStyle) {
self.init(corners: position.roundedCorners, base: base)
}
}
class IrregularBorderView : UIImageView {
let cornerMaskView = UIImageView()
init() {
super.init(frame : CGRectZero)
self.addSubview(cornerMaskView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var style : IrregularBorderStyle? {
didSet {
if let style = style {
let radius = style.base.cornerRadius.value(self)
self.cornerMaskView.image = renderMaskWithCorners(style.corners, cornerRadii: CGSizeMake(radius, radius))
self.maskView = cornerMaskView
self.image = renderBorderWithEdges(style.corners, style : style.base)
}
else {
self.maskView = nil
self.image = nil
}
}
}
private func renderMaskWithCorners(corners : UIRectCorner, cornerRadii : CGSize) -> UIImage {
let size = CGSizeMake(cornerRadii.width * 2 + 1, cornerRadii.height * 2 + 1)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIColor.blackColor().setFill()
let path = UIBezierPath(roundedRect: CGRect(origin: CGPointZero, size: size), byRoundingCorners: corners, cornerRadii: cornerRadii)
path.fill()
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!.resizableImageWithCapInsets(UIEdgeInsets(top: cornerRadii.height, left: cornerRadii.width, bottom: cornerRadii.height, right: cornerRadii.width))
}
private func renderBorderWithEdges(corners : UIRectCorner, style : BorderStyle) -> UIImage? {
let radius = style.cornerRadius.value(self)
let size = CGSizeMake(radius * 2 + 1, radius * 2 + 1)
guard let color = style.color else {
return nil
}
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setStroke()
let path = UIBezierPath(roundedRect: CGRect(origin: CGPointZero, size: size), byRoundingCorners: corners, cornerRadii: CGSizeMake(radius, radius))
path.lineWidth = style.width.value
path.stroke()
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!.resizableImageWithCapInsets(UIEdgeInsets(top: radius, left: radius, bottom: radius, right: radius))
}
override func layoutSubviews() {
super.layoutSubviews()
self.maskView?.frame = self.bounds
}
}
| a7e6fec56d00a6de5fb00c8845f05739 | 32.351852 | 168 | 0.633259 | false | false | false | false |
JV17/MyCal-iWatch | refs/heads/master | MyCal-Calculator/MyCalViewController.swift | mit | 1 | //
// MyCalViewController.swift
// MyCal-Calculator
//
// Created by Jorge Valbuena on 2015-04-17.
// Copyright (c) 2015 Jorge Valbuena. All rights reserved.
//
import UIKit
import QuartzCore
import MessageUI
import WatchConnectivity
//MARK: Structs
/// Holds all the screen sizes within a struct
struct ScreenSize
{
static let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width
static let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
/// The device types iPhone 4, iPhone5, iPhone6 & iPhone6+
struct DeviceType
{
static let IS_IPHONE_4_OR_LESS = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
static let IS_IPHONE_5 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
static let IS_IPHONE_6 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
static let IS_IPHONE_6P = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
}
/// Controllers identifiers
struct identifiers {
static let backgroundColor: String = "backgroundColor"
static let numberColor: String = "numberColor"
static let operationColor: String = "operationColor"
static let resetColors: String = "reset"
}
/// Table view constants values
struct TableViewConstants {
static let numRows: Int = 1
static let numSections: Int = 5
}
//MARK:
//MARK: Implementation
@available(iOS 9.0, *)
class MyCalViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MFMailComposeViewControllerDelegate, WCSessionDelegate {
//MARK: Lazy Initialization
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: CGRectZero, style: .Plain)
tableView.backgroundColor = .clearColor()
tableView.separatorStyle = .None
tableView.separatorColor = .grayColor()
tableView.bounces = true
tableView.scrollEnabled = true
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "tableViewCell")
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.showsVerticalScrollIndicator = false
tableView.showsHorizontalScrollIndicator = false
return tableView
}()
private lazy var imagesArray: Array<UIImage> = {
let array = Array<UIImage>()
return array
}()
private lazy var selectedRowView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.jv_colorWithHexString("#DBDDDE").colorWithAlphaComponent(0.7)
return view
}()
private lazy var imageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "appIconBig"))
return imageView
}()
private lazy var appHelper: MyCalHelper = {
let appHelper = MyCalHelper()
return appHelper
}()
private lazy var bgColorController: MyCalColorPickerViewController = {
let bgColorController = MyCalColorPickerViewController(title: "Choose a background color", identifier: identifiers.backgroundColor)
return bgColorController
}()
private lazy var numbersColorController: MyCalColorPickerViewController = {
let numbersColorController = MyCalColorPickerViewController(title: "Choose the numbers color", identifier: identifiers.numberColor)
return numbersColorController
}()
private lazy var operationsColorController: MyCalColorPickerViewController = {
let operationsColorController = MyCalColorPickerViewController(title: "Choose the operations color", identifier: identifiers.operationColor)
return operationsColorController
}()
private lazy var transitionManager: TransitionManager = {
let transitionManager = TransitionManager()
return transitionManager
}()
private let session : WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil
private var titleLabel: UILabel?
private var versionLabel: UILabel?
//MARK: Constants
let rowHeight: CGFloat = 50.0
let heightHeader: CGFloat = 15.0
let heightFooter: CGFloat = 0.0
//MARK:
//MARK: Initializers
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.configureWCSession()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.configureWCSession()
}
override func viewDidLoad() {
super.viewDidLoad()
// setting view controller
self.commonInit()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if(tableView.respondsToSelector(Selector("separatorInset"))) {
tableView.separatorInset = UIEdgeInsetsZero
}
if(tableView.respondsToSelector(Selector("layoutMargins"))) {
tableView.layoutMargins = UIEdgeInsetsZero
}
}
private func commonInit() {
// setting gradient background
let colors: [AnyObject] = [UIColor.jv_colorWithHexString("#FF5E3A").CGColor,
UIColor.jv_colorWithHexString("#FF2A68").CGColor]
self.appHelper.applyGradientFromColors(colors, view: view)
self.imagesArray = [UIImage(named: "background_color-50")!,
UIImage(named: "brush-50")!,
UIImage(named: "roller_brush-50")!,
UIImage(named: "message_group-50")!]
self.selectedRowView.frame = CGRectMake(0, 0, view.frame.size.width, rowHeight)
self.view.addSubview(tableView)
self.applyTableViewAutoLayout()
}
private func labelWithFrmae(frame: CGRect, text: String) -> UILabel
{
let label = UILabel(frame: frame)
label.backgroundColor = .clearColor()
label.font = UIFont(name: "Lato-Light", size: 20)
label.textColor = .blackColor()
label.textAlignment = .Center
label.numberOfLines = 1
label.text = text
return label
}
private func configureWCSession() {
session?.delegate = self;
session?.activateSession()
}
private func applyTableViewAutoLayout() {
let leadingConstraint = NSLayoutConstraint(item: tableView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 20)
let trailingConstraint = NSLayoutConstraint(item: tableView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: -20)
let topConstraint = NSLayoutConstraint(item: tableView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 16)
let bottomConstraint = NSLayoutConstraint(item: tableView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: -10)
view.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
}
//MARK:
//MARK: TableView delegate and datasource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("tableViewCell")!
if(cell.respondsToSelector(Selector("separatorInset"))) {
cell.separatorInset = UIEdgeInsetsZero
}
if(cell.respondsToSelector(Selector("preservesSuperviewLayoutMargins"))) {
cell.preservesSuperviewLayoutMargins = false
}
if(cell.respondsToSelector(Selector("layoutMargins"))) {
cell.layoutMargins = UIEdgeInsetsZero
}
// setting up cell
cell.layer.cornerRadius = 10.0
cell.layer.masksToBounds = true
cell.selectedBackgroundView = selectedRowView
cell.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
cell.textLabel?.font = UIFont(name: "Lato-Light", size: 22)
cell.textLabel?.textColor = .whiteColor() //colorWithHexString("#DBDDDE")
cell.accessoryType = .DisclosureIndicator
if(indexPath.section == 0) {
cell.layer.cornerRadius = 0.0
cell.layer.masksToBounds = false
cell.selectedBackgroundView = nil
cell.backgroundColor = UIColor.clearColor()
cell.accessoryType = .None
cell.selectionStyle = .None
let imgFrame: CGSize = self.imageView.frame.size
self.imageView.frame = CGRectMake(tableView.frame.width/2-imgFrame.width/2, 5, imgFrame.width, imgFrame.height)
self.imageView.layer.cornerRadius = 10.0
self.imageView.clipsToBounds = true
cell.addSubview(imageView)
titleLabel = labelWithFrmae(CGRectMake(0, CGRectGetMaxY(imageView.frame), tableView.frame.size.width, 30), text: "Version 1.0")
cell.addSubview(titleLabel!)
versionLabel = labelWithFrmae(CGRectMake(0, CGRectGetMaxY(titleLabel!.frame), tableView.frame.size.width, 30), text: "MyCal Calculator Settings")
cell.addSubview(versionLabel!)
}
else if(indexPath.section == 1) {
cell.textLabel?.text = "Numbers color"//"Background color"
cell.textLabel?.alpha = 0.9
cell.imageView?.image = imagesArray[0]
cell.imageView?.alpha = 0.9
}
else if(indexPath.section == 2) {
cell.textLabel?.text = "Operations color"
cell.textLabel?.alpha = 0.9
cell.imageView?.image = imagesArray[1]
cell.imageView?.alpha = 0.9
}
else if(indexPath.section == 3) {
cell.textLabel?.text = "Reset colors"
cell.textLabel?.alpha = 0.9
cell.imageView?.image = imagesArray[2]
cell.imageView?.alpha = 0.9
}
else if(indexPath.section == 4) {
cell.textLabel?.text = "Contact Support"
cell.textLabel?.alpha = 0.9
cell.imageView?.image = imagesArray[3]
cell.imageView?.alpha = 0.9
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// selected row code
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if(indexPath.section == 1) {
self.numbersColorController.transitioningDelegate = self.transitionManager
self.numbersColorController.title = identifiers.numberColor
self.presentViewController(numbersColorController, animated: true, completion: nil)
}
else if(indexPath.section == 2) {
self.operationsColorController.transitioningDelegate = self.transitionManager
self.operationsColorController.title = identifiers.operationColor
self.presentViewController(operationsColorController, animated: true, completion: nil)
}
else if(indexPath.section == 3) {
// passing notification to app watch
self.sendMessageWithData(NSKeyedArchiver.archivedDataWithRootObject(UIColor.clearColor()), identifier: identifiers.resetColors)
}
else if(indexPath.section == 4) {
// open mail composer
self.sendEmailButtonTapped()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// number of rows
return TableViewConstants.numRows
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if(indexPath.section == 0) {
return 260;
}
return rowHeight
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// number of sections
return TableViewConstants.numSections
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// header for tableview
return UIView.init();
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// height for header
return heightHeader
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
// footer for tableview
return UIView.init()
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// height for footer
return heightFooter
}
//MARK:
//MARK: Helper functions
private func sendEmailButtonTapped() {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
private func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["[email protected]"])
mailComposerVC.setSubject("MyCal - Apple Watch Support")
//mailComposerVC.setMessageBody("Sending e-mail in-app!", isHTML: false)
return mailComposerVC
}
private func showSendMailErrorAlert() {
let alertController = UIAlertController.init(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: .Alert)
let defaultAction = UIAlertAction.init(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
private func infoButtonPressed(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://www.jorgedeveloper.com")!)
}
private func sendMessageWithData(data: NSData, identifier: String) {
let applicationData = ["color" : data, "identifier" : identifier]
if let session = session where session.reachable {
session.sendMessage(applicationData,
replyHandler: { replyData in
print(replyData)
}, errorHandler: { error in
print(error)
let alertController = UIAlertController.init(title: "Fail Color Transfer", message: "Sorry, we couldn't update the color in your watch because of an error. " + "Error: " + error.description, preferredStyle: .Alert)
let defaultAction = UIAlertAction.init(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
})
}
}
}
| f8d24bb843bcf1f40f0bb7d7e64746e6 | 35.949772 | 234 | 0.647986 | false | false | false | false |
onmyway133/Github.swift | refs/heads/master | Carthage/Checkouts/Sugar/Source/Shared/GrandCentralDispatch.swift | mit | 1 | import Foundation
public enum DispatchQueue {
case Main, Interactive, Initiated, Utility, Background, Custom(dispatch_queue_t)
}
private func getQueue(queue queueType: DispatchQueue = .Main) -> dispatch_queue_t {
let queue: dispatch_queue_t
switch queueType {
case .Main:
queue = dispatch_get_main_queue()
case .Interactive:
queue = dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)
case .Initiated:
queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
case .Utility:
queue = dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)
case .Background:
queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
case .Custom(let userQueue):
queue = userQueue
}
return queue
}
public func delay(delay:Double, queue queueType: DispatchQueue = .Main, closure: () -> Void) {
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))),
getQueue(queue: queueType),
closure
)
}
public func dispatch(queue queueType: DispatchQueue = .Main, closure: () -> Void) {
dispatch_async(getQueue(queue: queueType), {
closure()
})
}
| 66afccf02e880091fea15e6d9db2e0b6 | 27.1 | 94 | 0.704626 | false | false | false | false |
jmieville/ToTheMoonAndBack-PitchPerfect | refs/heads/master | PitchPerfect/PlaySoundsViewController+Audio.swift | mit | 1 | //
// PlaySoundsViewController.swift
// PitchPerfect
//
// Created by Jean-Marc Kampol Mieville on 5/23/2559 BE.
// Copyright © 2559 Jean-Marc Kampol Mieville. All rights reserved.
//
import UIKit
import AVFoundation
extension PlaySoundsViewController: AVAudioPlayerDelegate {
//Alerts Struct
struct Alerts {
static let DismissAlert = "Dismiss"
static let RecordingDisabledTitle = "Recording Disabled"
static let RecordingDisabledMessage = "You've disabled this app from recording your microphone. Check Settings."
static let RecordingFailedTitle = "Recording Failed"
static let RecordingFailedMessage = "Something went wrong with your recording."
static let AudioRecorderError = "Audio Recorder Error"
static let AudioSessionError = "Audio Session Error"
static let AudioRecordingError = "Audio Recording Error"
static let AudioFileError = "Audio File Error"
static let AudioEngineError = "Audio Engine Error"
}
// raw values correspond to sender tags
enum PlayingState { case Playing, NotPlaying }
// MARK: Audio Functions
func setupAudio() {
// initialize (recording) audio file
do {
audioFile = try AVAudioFile(forReading: recordedAudioURL as URL)
} catch {
showAlert(title: Alerts.AudioFileError, message: String(describing: error))
}
print("Audio has been setup")
}
func playSound(rate: Float? = nil, pitch: Float? = nil, echo: Bool = false, reverb: Bool = false) {
// initialize audio engine components
audioEngine = AVAudioEngine()
// node for playing audio
audioPlayerNode = AVAudioPlayerNode()
audioEngine.attach(audioPlayerNode)
// node for adjusting rate/pitch
let changeRatePitchNode = AVAudioUnitTimePitch()
if let pitch = pitch {
changeRatePitchNode.pitch = pitch
}
if let rate = rate {
changeRatePitchNode.rate = rate
}
audioEngine.attach(changeRatePitchNode)
// node for echo
let echoNode = AVAudioUnitDistortion()
echoNode.loadFactoryPreset(.multiEcho1)
audioEngine.attach(echoNode)
// node for reverb
let reverbNode = AVAudioUnitReverb()
reverbNode.loadFactoryPreset(.cathedral)
reverbNode.wetDryMix = 50
audioEngine.attach(reverbNode)
// connect nodes
if echo == true && reverb == true {
connectAudioNodes(nodes: audioPlayerNode, changeRatePitchNode, echoNode, reverbNode, audioEngine.outputNode)
} else if echo == true {
connectAudioNodes(nodes: audioPlayerNode, changeRatePitchNode, echoNode, audioEngine.outputNode)
} else if reverb == true {
connectAudioNodes(nodes: audioPlayerNode, changeRatePitchNode, reverbNode, audioEngine.outputNode)
} else {
connectAudioNodes(nodes: audioPlayerNode, changeRatePitchNode, audioEngine.outputNode)
}
// schedule to play and start the engine!
audioPlayerNode.stop()
audioPlayerNode.scheduleFile(audioFile, at: nil) {
var delayInSeconds: Double = 0
if let lastRenderTime = self.audioPlayerNode.lastRenderTime, let playerTime = self.audioPlayerNode.playerTime(forNodeTime: lastRenderTime) {
if let rate = rate {
delayInSeconds = Double(self.audioFile.length - playerTime.sampleTime) / Double(self.audioFile.processingFormat.sampleRate) / Double(rate)
} else {
delayInSeconds = Double(self.audioFile.length - playerTime.sampleTime) / Double(self.audioFile.processingFormat.sampleRate)
}
}
// schedule a stop timer for when audio finishes playing
self.stopTimer = Timer(timeInterval: delayInSeconds, target: self, selector: #selector(PlaySoundsViewController.stopAudio), userInfo: nil, repeats: false)
RunLoop.main.add(self.stopTimer!, forMode: RunLoopMode.defaultRunLoopMode)
}
do {
try audioEngine.start()
} catch {
showAlert(title: Alerts.AudioEngineError, message: String(describing: error))
return
}
// play the recording!
audioPlayerNode.play()
}
// MARK: Connect List of Audio Nodes
func connectAudioNodes(nodes: AVAudioNode...) {
for x in 0..<nodes.count-1 {
audioEngine.connect(nodes[x], to: nodes[x+1], format: audioFile.processingFormat)
}
}
func stopAudio() {
if let stopTimer = stopTimer {
stopTimer.invalidate()
}
configureUI(playState: .NotPlaying)
if let audioPlayerNode = audioPlayerNode {
audioPlayerNode.stop()
}
if let audioEngine = audioEngine {
audioEngine.stop()
audioEngine.reset()
}
}
// MARK: UI Functions
func configureUI(playState: PlayingState) {
switch(playState) {
case .Playing:
setPlayButtonsEnabled(enabled: false)
stopButton.isEnabled = true
case .NotPlaying:
setPlayButtonsEnabled(enabled: true)
stopButton.isEnabled = false
}
}
func setPlayButtonsEnabled(enabled: Bool) {
snailButton.isEnabled = enabled
chipmunkButton.isEnabled = enabled
rabbitButton.isEnabled = enabled
darthVaderButton.isEnabled = enabled
echoButton.isEnabled = enabled
revertButton.isEnabled = enabled
}
func showAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Alerts.DismissAlert, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
| 6f6d6ef1aa1bbe372765e5021d15c055 | 33.657303 | 166 | 0.622953 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Modules/CreateRoom/EnterNewRoomDetails/Cells/ChooseAvatarTableViewCell.swift | apache-2.0 | 1 | //
// Copyright 2020 New Vector Ltd
//
// 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
import Reusable
protocol ChooseAvatarTableViewCellDelegate: AnyObject {
func chooseAvatarTableViewCellDidTapChooseAvatar(_ cell: ChooseAvatarTableViewCell, sourceView: UIView)
func chooseAvatarTableViewCellDidTapRemoveAvatar(_ cell: ChooseAvatarTableViewCell)
}
class ChooseAvatarTableViewCell: UITableViewCell {
@IBOutlet private weak var avatarImageView: UIImageView! {
didSet {
avatarImageView.layer.cornerRadius = avatarImageView.frame.width/2
}
}
@IBOutlet private weak var chooseAvatarButton: UIButton!
@IBOutlet private weak var removeAvatarButton: UIButton! {
didSet {
removeAvatarButton.imageView?.contentMode = .scaleAspectFit
}
}
weak var delegate: ChooseAvatarTableViewCellDelegate?
@IBAction private func chooseAvatarButtonTapped(_ sender: UIButton) {
delegate?.chooseAvatarTableViewCellDidTapChooseAvatar(self, sourceView: sender)
}
@IBAction private func removeAvatarButtonTapped(_ sender: UIButton) {
delegate?.chooseAvatarTableViewCellDidTapRemoveAvatar(self)
}
func configure(withViewModel viewModel: ChooseAvatarTableViewCellVM) {
if let image = viewModel.avatarImage {
avatarImageView.image = image
removeAvatarButton.isHidden = false
} else {
avatarImageView.image = Asset.Images.captureAvatar.image
removeAvatarButton.isHidden = true
}
}
}
extension ChooseAvatarTableViewCell: NibReusable {}
extension ChooseAvatarTableViewCell: Themable {
func update(theme: Theme) {
backgroundView = UIView()
backgroundView?.backgroundColor = theme.backgroundColor
}
}
| 41ba4e2e718fd9951454f49019756ba0 | 32.485714 | 107 | 0.72099 | false | false | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART | refs/heads/master | bluefruitconnect/Common/UartManager.swift | mit | 1 | //
// UartManager.swift
// Bluefruit Connect
//
// Created by Antonio García on 06/02/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import Foundation
class UartManager: NSObject {
enum UartNotifications : String {
case DidSendData = "didSendData"
case DidReceiveData = "didReceiveData"
case DidBecomeReady = "didBecomeReady"
}
// Constants
private static let UartServiceUUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e" // UART service UUID
static let RxCharacteristicUUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
private static let TxCharacteristicUUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
private static let TxMaxCharacters = 20
// Manager
static let sharedInstance = UartManager()
// Bluetooth Uart
private var uartService: CBService?
private var rxCharacteristic: CBCharacteristic?
private var txCharacteristic: CBCharacteristic?
private var txWriteType = CBCharacteristicWriteType.WithResponse
var blePeripheral: BlePeripheral? {
didSet {
if blePeripheral?.peripheral.identifier != oldValue?.peripheral.identifier {
// Discover UART
resetService()
if let blePeripheral = blePeripheral {
DLog("Uart: discover services")
blePeripheral.peripheral.discoverServices([CBUUID(string: UartManager.UartServiceUUID)])
}
}
}
}
// Data
var dataBuffer = [UartDataChunk]()
var dataBufferEnabled = Config.uartShowAllUartCommunication
override init() {
super.init()
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: #selector(didDisconnectFromPeripheral(_:)), name: BleManager.BleNotifications.DidDisconnectFromPeripheral.rawValue, object: nil)
}
deinit {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver(self, name: BleManager.BleNotifications.DidDisconnectFromPeripheral.rawValue, object: nil)
}
func didDisconnectFromPeripheral(notification : NSNotification) {
blePeripheral = nil
resetService()
}
private func resetService() {
uartService = nil
rxCharacteristic = nil
txCharacteristic = nil
}
func sendDataWithCrc(data : NSData) {
let len = data.length
var dataBytes = [UInt8](count: len, repeatedValue: 0)
var crc: UInt8 = 0
data.getBytes(&dataBytes, length: len)
for i in dataBytes { //add all bytes
crc = crc &+ i
}
crc = ~crc //invert
let dataWithChecksum = NSMutableData(data: data)
dataWithChecksum.appendBytes(&crc, length: 1)
sendData(dataWithChecksum)
}
func sendData(data: NSData) {
let dataChunk = UartDataChunk(timestamp: CFAbsoluteTimeGetCurrent(), mode: .TX, data: data)
sendChunk(dataChunk)
}
func sendChunk(dataChunk: UartDataChunk) {
if let txCharacteristic = txCharacteristic, blePeripheral = blePeripheral {
let data = dataChunk.data
if dataBufferEnabled {
blePeripheral.uartData.sentBytes += data.length
dataBuffer.append(dataChunk)
}
// Split data in txmaxcharacters bytes packets
var offset = 0
repeat {
let chunkSize = min(data.length-offset, UartManager.TxMaxCharacters)
let chunk = NSData(bytesNoCopy: UnsafeMutablePointer<UInt8>(data.bytes)+offset, length: chunkSize, freeWhenDone:false)
if Config.uartLogSend {
DLog("send: \(hexString(chunk))")
}
blePeripheral.peripheral.writeValue(chunk, forCharacteristic: txCharacteristic, type: txWriteType)
offset+=chunkSize
}while(offset<data.length)
NSNotificationCenter.defaultCenter().postNotificationName(UartNotifications.DidSendData.rawValue, object: nil, userInfo:["dataChunk" : dataChunk]);
}
else {
DLog("Error: sendChunk with uart not ready")
}
}
private func receivedData(data: NSData) {
let dataChunk = UartDataChunk(timestamp: CFAbsoluteTimeGetCurrent(), mode: .RX, data: data)
receivedChunk(dataChunk)
}
private func receivedChunk(dataChunk: UartDataChunk) {
if Config.uartLogReceive {
DLog("received: \(hexString(dataChunk.data))")
}
if dataBufferEnabled {
blePeripheral?.uartData.receivedBytes += dataChunk.data.length
dataBuffer.append(dataChunk)
}
NSNotificationCenter.defaultCenter().postNotificationName(UartNotifications.DidReceiveData.rawValue, object: nil, userInfo:["dataChunk" : dataChunk]);
}
func isReady() -> Bool {
return txCharacteristic != nil && rxCharacteristic != nil// && rxCharacteristic!.isNotifying
}
func clearData() {
dataBuffer.removeAll()
blePeripheral?.uartData.receivedBytes = 0
blePeripheral?.uartData.sentBytes = 0
}
}
// MARK: - CBPeripheralDelegate
extension UartManager: CBPeripheralDelegate {
func peripheral(peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
DLog("UartManager: resetService because didModifyServices")
resetService()
}
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
guard blePeripheral != nil else {
return
}
if uartService == nil {
if let services = peripheral.services {
var found = false
var i = 0
while (!found && i < services.count) {
let service = services[i]
if (service.UUID.UUIDString .caseInsensitiveCompare(UartManager.UartServiceUUID) == .OrderedSame) {
found = true
uartService = service
peripheral.discoverCharacteristics([CBUUID(string: UartManager.RxCharacteristicUUID), CBUUID(string: UartManager.TxCharacteristicUUID)], forService: service)
}
i += 1
}
}
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
guard blePeripheral != nil else {
return
}
//DLog("uart didDiscoverCharacteristicsForService")
if let uartService = uartService where rxCharacteristic == nil || txCharacteristic == nil {
if rxCharacteristic == nil || txCharacteristic == nil {
if let characteristics = uartService.characteristics {
var found = false
var i = 0
while !found && i < characteristics.count {
let characteristic = characteristics[i]
if characteristic.UUID.UUIDString .caseInsensitiveCompare(UartManager.RxCharacteristicUUID) == .OrderedSame {
rxCharacteristic = characteristic
}
else if characteristic.UUID.UUIDString .caseInsensitiveCompare(UartManager.TxCharacteristicUUID) == .OrderedSame {
txCharacteristic = characteristic
txWriteType = characteristic.properties.contains(.WriteWithoutResponse) ? .WithoutResponse:.WithResponse
DLog("Uart: detected txWriteType: \(txWriteType.rawValue)")
}
found = rxCharacteristic != nil && txCharacteristic != nil
i += 1
}
}
}
// Check if characteristics are ready
if (rxCharacteristic != nil && txCharacteristic != nil) {
// Set rx enabled
peripheral.setNotifyValue(true, forCharacteristic: rxCharacteristic!)
// Send notification that uart is ready
NSNotificationCenter.defaultCenter().postNotificationName(UartNotifications.DidBecomeReady.rawValue, object: nil, userInfo:nil)
DLog("Uart: did become ready")
}
}
}
func peripheral(peripheral: CBPeripheral, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
guard blePeripheral != nil else {
return
}
DLog("didUpdateNotificationStateForCharacteristic")
/*
if characteristic == rxCharacteristic {
if error != nil {
DLog("Uart RX isNotifying error: \(error)")
}
else {
if characteristic.isNotifying {
DLog("Uart RX isNotifying: true")
// Send notification that uart is ready
NSNotificationCenter.defaultCenter().postNotificationName(UartNotifications.DidBecomeReady.rawValue, object: nil, userInfo:nil)
}
else {
DLog("Uart RX isNotifying: false")
}
}
}
*/
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
guard blePeripheral != nil else {
return
}
if characteristic == rxCharacteristic && characteristic.service == uartService {
if let characteristicDataValue = characteristic.value {
receivedData(characteristicDataValue)
}
}
}
} | a2dd9f83e003240b4e434986a8793024 | 36.032847 | 183 | 0.589691 | false | false | false | false |
robertoseidenberg/MixerBox | refs/heads/master | SampleApp/SampleApp/ViewController+Layout.swift | mit | 1 | import MixerBox
extension ViewController {
func updateColorPreview() {
zoom.backgroundColor = UIColor(hsb: hsbMixer.hsb)
}
func updateHSBSliders(hsb: HSB, labelsOnly: Bool = false) {
if labelsOnly == false {
hueSlider.value = 360 * hsb.hue
saturationSlider.value = 100 * hsb.saturation
brightnessSlider.value = 100 * hsb.brightness
}
hueLabel.text = String(Int(hueSlider.value))
saturationLabel.text = String(Int(saturationSlider.value))
brightnessLabel.text = String(Int(brightnessSlider.value))
}
func updateRGBSliders(rgb: RGB, labelsOnly: Bool = false) {
if labelsOnly == false {
redSlider.value = 255 * rgb.red
greenSlider.value = 255 * rgb.green
blueSlider.value = 255 * rgb.blue
}
redLabel.text = String(Int(redSlider.value))
greenLabel.text = String(Int(greenSlider.value))
blueLabel.text = String(Int(blueSlider.value))
}
}
| 681c1d2e8d5dab9da1239417b8aae908 | 27.088235 | 62 | 0.66911 | false | false | false | false |
sarahspins/Loop | refs/heads/master | Loop/Models/MLabService.swift | apache-2.0 | 2 | //
// mLabService.swift
// Loop
//
// Created by Nate Racklyeft on 7/3/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
private let mLabAPIHost = NSURL(string: "https://api.mongolab.com/api/1/databases")!
struct MLabService: ServiceAuthentication {
var credentials: [ServiceCredential]
let title: String = NSLocalizedString("mLab", comment: "The title of the mLab service")
init(databaseName: String?, APIKey: String?) {
credentials = [
ServiceCredential(
title: NSLocalizedString("Database", comment: "The title of the mLab database name credential"),
placeholder: "nightscoutdb",
isSecret: false,
keyboardType: .ASCIICapable,
value: databaseName
),
ServiceCredential(
title: NSLocalizedString("API Key", comment: "The title of the mLab API Key credential"),
placeholder: nil,
isSecret: false,
keyboardType: .ASCIICapable,
value: APIKey
)
]
if databaseName != nil && APIKey != nil {
isAuthorized = true
}
}
var databaseName: String? {
return credentials[0].value
}
var APIKey: String? {
return credentials[1].value
}
private(set) var isAuthorized: Bool = false
mutating func verify(completion: (success: Bool, error: ErrorType?) -> Void) {
guard let APIURL = APIURLForCollection("") else {
completion(success: false, error: nil)
return
}
NSURLSession.sharedSession().dataTaskWithURL(APIURL) { (_, response, error) in
var error: ErrorType? = error
if error == nil, let response = response as? NSHTTPURLResponse where response.statusCode >= 300 {
error = LoopError.ConnectionError
}
self.isAuthorized = error == nil
completion(success: self.isAuthorized, error: error)
}.resume()
}
mutating func reset() {
credentials[0].value = nil
credentials[1].value = nil
isAuthorized = false
}
private func APIURLForCollection(collection: String) -> NSURL? {
guard let databaseName = databaseName, APIKey = APIKey else {
return nil
}
let APIURL = mLabAPIHost.URLByAppendingPathComponent("\(databaseName)/collections").URLByAppendingPathComponent(collection)
let components = NSURLComponents(URL: APIURL, resolvingAgainstBaseURL: true)!
var items = components.queryItems ?? []
items.append(NSURLQueryItem(name: "apiKey", value: APIKey))
components.queryItems = items
return components.URL
}
func uploadTaskWithData(data: NSData, inCollection collection: String) -> NSURLSessionTask? {
guard let URL = APIURLForCollection(collection) else {
return nil
}
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
return NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: data)
}
}
extension KeychainManager {
func setMLabDatabaseName(databaseName: String?, APIKey: String?) throws {
let credentials: InternetCredentials?
if let username = databaseName, password = APIKey {
credentials = InternetCredentials(username: username, password: password, URL: mLabAPIHost)
} else {
credentials = nil
}
try replaceInternetCredentials(credentials, forURL: mLabAPIHost)
}
func getMLabCredentials() -> (databaseName: String, APIKey: String)? {
do {
let credentials = try getInternetCredentials(URL: mLabAPIHost)
return (databaseName: credentials.username, APIKey: credentials.password)
} catch {
return nil
}
}
}
| 213a1492f23614bc2769fa5f41da760f | 30.46875 | 131 | 0.618669 | false | false | false | false |
cdtschange/SwiftMKit | refs/heads/master | SwiftMKit/UI/View/RangeSlider/RangeSliderThumbLayer.swift | mit | 1 | //
// RangeSliderThumbLayer.swift
// CustomControl
//
// Created by chenyh on 16/7/4.
// Copyright © 2016年 chenyh. All rights reserved.
//
import UIKit
import QuartzCore
/// Range slider track layer. Responsible for drawing the horizontal track
public class RangeSliderTrackLayer: CALayer {
/// owner slider
weak var rangeSlider: RangeSlider?
/// draw the track between 2 thumbs
///
/// - Parameter ctx: current graphics context
override public func draw(in ctx: CGContext) {
if let slider = rangeSlider {
// Clip
var orgRect = bounds
if slider.trackHeight > 0 {
orgRect.y = orgRect.y + (orgRect.h - slider.trackHeight)/2
orgRect.h = slider.trackHeight
}
let cornerRadius = orgRect.height * slider.curvaceousness / 2.0
let path = UIBezierPath(roundedRect: orgRect, cornerRadius: cornerRadius)
ctx.addPath(path.cgPath)
// Fill the track
ctx.setFillColor(slider.trackTintColor.cgColor)
ctx.addPath(path.cgPath)
ctx.fillPath()
let lowerValuePosition = CGFloat(slider.positionForValue(value: slider.lowerValue))
let upperValuePosition = CGFloat(slider.positionForValue(value: slider.upperValue))
// Fill the lower track range
ctx.setFillColor(slider.lowerTrackHighlightTintColor.cgColor)
let lowerRect = CGRect(x: 0.0 , y: orgRect.y, width: lowerValuePosition - 0, height: orgRect.height)
let lowerPath = UIBezierPath(roundedRect: lowerRect, cornerRadius: cornerRadius)
ctx.addPath(lowerPath.cgPath)
ctx.fillPath()
// Fill the upper track range
ctx.setFillColor(slider.upperTrackHighlightTintColor.cgColor)
let upperRect = CGRect(x: upperValuePosition, y: orgRect.y, width: orgRect.width - upperValuePosition, height: orgRect.height)
let upperPath = UIBezierPath(roundedRect: upperRect, cornerRadius: cornerRadius)
ctx.addPath(upperPath.cgPath)
ctx.fillPath()
// Fill the highlighted range
ctx.setFillColor(slider.trackHighlightTintColor.cgColor)
let rect = CGRect(x: lowerValuePosition, y: orgRect.y, width: upperValuePosition - lowerValuePosition, height: orgRect.height)
ctx.fill(rect)
}
}
}
public class RangeSliderThumbLayer: CALayer {
/// owner slider
weak var rangeSlider: RangeSlider?
/// whether this thumb is currently highlighted i.e. touched by user
public var highlighted: Bool = false {
didSet {
setNeedsDisplay()
}
}
/// stroke color
public var strokeColor: UIColor = UIColor.gray {
didSet {
setNeedsDisplay()
}
}
/// highlightedColor color
public var highlightedColor: UIColor = UIColor(white: 0.0, alpha: 0.1) {
didSet {
setNeedsDisplay()
}
}
/// line width
public var lineWidth: CGFloat = 0.5 {
didSet {
setNeedsDisplay()
}
}
/// image
public var image: UIImage?{
didSet {
setNeedsDisplay()
}
}
override public func draw(in ctx: CGContext) {
// Clip
if let slider = rangeSlider {
// clip
let thumbFrame = bounds.insetBy(dx: 0.0, dy: 0.0)
let cornerRadius = thumbFrame.height * slider.curvaceousness / 2.0
let thumbPath = UIBezierPath(roundedRect: thumbFrame, cornerRadius: cornerRadius)
// Image
if image != nil {
ctx.saveGState()
ctx.translateBy(x: 0, y: image!.size.height)
ctx.scaleBy(x: 1.0, y: -1.0)
ctx.draw(image!.cgImage!, in: CGRect(x: (bounds.w - image!.size.width)/2, y: -(bounds.h - image!.size.height)/2, w: image!.size.width, h: image!.size.height))
ctx.restoreGState()
}else{
// Fill
ctx.setFillColor(slider.thumbTintColor.cgColor)
ctx.addPath(thumbPath.cgPath)
ctx.fillPath()
// Outline
ctx.setStrokeColor(strokeColor.cgColor)
ctx.setLineWidth(lineWidth)
ctx.addPath(thumbPath.cgPath)
ctx.strokePath()
}
if highlighted {
ctx.setFillColor(highlightedColor.cgColor)
ctx.addPath(thumbPath.cgPath)
ctx.fillPath()
}
}
}
}
| f96c112942bfd9bbbca1760aea0cf22e | 33.273381 | 174 | 0.570109 | false | false | false | false |
zhenghuadong11/firstGitHub | refs/heads/master | 旅游app_useSwift/旅游app_useSwift/MYHeaderForBuyView.swift | apache-2.0 | 1 | //
// MYHeaderForBuyView.swift
// 旅游app_useSwift
//
// Created by zhenghuadong on 16/4/18.
// Copyright © 2016年 zhenghuadong. All rights reserved.
//
import Foundation
import UIKit
class MYHeaderForBuyView:UIView {
var _moneyLabel:UILabel = UILabel()
var _buyButton:UIButton = UIButton()
var _viewController:UIViewController?
override func layoutSubviews() {
_moneyLabel.snp_makeConstraints { (make) in
make.top.bottom.equalTo(self)
make.left.equalTo(self).offset(10)
make.width.equalTo(self).multipliedBy(0.3)
}
_buyButton.snp_makeConstraints { (make) in
make.top.right.equalTo(self).offset(10)
make.bottom.equalTo(self).offset(-10)
make.width.equalTo(self).multipliedBy(0.35)
}
}
func buyButtonClick() -> Void {
if MYMineModel._shareMineModel.name == nil
{
_loginClick(_viewController!)
}
if MYMineModel._shareMineModel.name == nil
{
return
}
MYZhifuModel.shareZhifuModel().user = MYMineModel._shareMineModel.name
let zhifuDataViewController = MYZhifuDataSelectViewController()
zhifuDataViewController.presentViewController = _viewController
_viewController?.presentViewController(zhifuDataViewController, animated: true, completion: nil)
}
override func didMoveToSuperview() {
self.addSubview(_moneyLabel)
self.addSubview(_buyButton)
_buyButton.addTarget(self, action: #selector(buyButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
_buyButton.backgroundColor = UIColor.orangeColor()
_buyButton.setTitle("购买", forState: UIControlState.Normal)
}
}
| d14ebb06a2ab50df87b06b50d143dcae | 31.818182 | 118 | 0.643767 | false | false | false | false |
yageek/LazyBug | refs/heads/develop | LazyBug/LazyServerClient.swift | mit | 1 | //
// LazyServerClient.swift
// LazyBug
//
// Created by Yannick Heinrich on 10.05.17.
//
//
import Foundation
import ProcedureKit
import ProcedureKitNetwork
import Compression
import SwiftProtobuf
enum NetworkError: Error {
case compression
case apiError
}
final class ConvertFeedbackProcedure: Procedure, OutputProcedure {
let formatter: DateFormatter = {
let dateFormatter = DateFormatter()
let enUSPosixLocale = Locale(identifier: "en_US_POSIX")
dateFormatter.locale = enUSPosixLocale
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return dateFormatter
}()
let feedback: Feedback
var output: Pending<ProcedureResult<Data>> = .pending
init(feedback: Feedback) {
self.feedback = feedback
super.init()
name = "net.yageek.lazybug.convertFeedback.\(feedback.identifier ?? "Unknown")"
}
override func execute() {
guard !isCancelled else { self.finish(); return }
do {
var request = Lazybug_Feedback()
request.identifier = feedback.identifier!
request.creationDate = formatter.string(from: feedback.createdDate! as Date)
request.content = feedback.content!
if let meta = feedback.meta {
request.meta = meta as Data
}
request.snapshot = feedback.snapshot! as Data
let data = try request.serializedData()
self.finish(withResult: .success(data))
} catch let error {
Log.error("Error during marshalling: \(error)")
self.finish(withError: error)
}
}
}
final class CompressDataProcedure: Procedure, InputProcedure, OutputProcedure {
private var compressBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 4096)
var input: Pending<Data> = .pending
var output: Pending<ProcedureResult<Data>> = .pending
override func execute() {
guard !isCancelled else { self.finish(); return }
guard let data = input.value else {
self.finish(withError: ProcedureKitError.dependenciesFailed())
return
}
var result: Int = 0
data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in
result = compression_encode_buffer(compressBuffer, 4096, bytes, data.count, nil, COMPRESSION_LZFSE)
}
if result == 0 {
self.finish(withError: NetworkError.compression)
} else {
let data = Data(bytes: compressBuffer, count: result)
self.finish(withResult: .success(data))
}
}
}
final class ValidAPICode: Procedure, InputProcedure {
var input: Pending<HTTPPayloadResponse<Data>> = .pending
override func execute() {
guard !isCancelled else { self.finish(); return }
guard let result = input.value else {
self.finish(withError: ProcedureKitError.requirementNotSatisfied())
return
}
switch result.response.statusCode {
case 200..<300:
self.finish()
default:
self.finish(withError: NetworkError.apiError)
}
}
}
final class LazyServerClient: FeedbackServerClient {
let queue: ProcedureQueue = {
let queue = ProcedureQueue()
queue.qualityOfService = .background
queue.name = "net.yageek.lazybug.lazyserverclient"
return queue
}()
let url: URL
init(url: URL) {
self.url = url
}
func sendFeedback(feedback: Feedback, completion: @escaping (Error?) -> Void) {
var httpRequest = URLRequest(url: url.appendingPathComponent("/feedbacks"))
httpRequest.httpMethod = "PUT"
let convert = ConvertFeedbackProcedure(feedback: feedback)
let transform = TransformProcedure { return HTTPPayloadRequest(payload: $0, request: httpRequest) }.injectResult(from: convert)
let network = NetworkUploadProcedure(session: URLSession.shared).injectResult(from: transform)
let valid = ValidAPICode().injectResult(from: network)
valid.addDidFinishBlockObserver { (_, errors) in
completion(errors.first)
}
queue.add(operations: convert, transform, network, valid)
}
}
| 388e85114cd84f36d0b62fe0fc4603d5 | 28.631944 | 135 | 0.637919 | false | false | false | false |
marklin2012/iOS_Animation | refs/heads/master | Section4/Chapter21/O2Cook_challenge/O2Cook/ViewController.swift | mit | 2 | //
// ViewController.swift
// O2Cook
//
// Created by O2.LinYi on 16/3/21.
// Copyright © 2016年 jd.com. All rights reserved.
//
import UIKit
let herbs = HerbModel.all()
class ViewController: UIViewController {
@IBOutlet var listView: UIScrollView!
@IBOutlet var bgImage: UIImageView!
var selectedImage: UIImageView?
let transition = PopAnimator()
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
if listView.subviews.count < herbs.count {
listView.viewWithTag(0)?.tag = 1000 // prevent confusion when looking up images
setupList()
}
transition.dismissCompletion = {
self.selectedImage!.hidden = false
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
// MARK: - view setup
// add all images to the list
func setupList() {
for var i=0; i < herbs.count; i++ {
// create image view
let imageView = UIImageView(image: UIImage(named: herbs[i].image))
imageView.tag = i + 100
imageView.contentMode = .ScaleAspectFill
imageView.userInteractionEnabled = true
imageView.layer.cornerRadius = 20
imageView.layer.masksToBounds = true
listView.addSubview(imageView)
// attach tap detector
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "didTapImageView:"))
}
listView.backgroundColor = UIColor.clearColor()
positionListItems()
}
// position all images inside the list
func positionListItems() {
let itemHeight: CGFloat = listView.frame.height * 1.33
let aspectRatio = UIScreen.mainScreen().bounds.height / UIScreen.mainScreen().bounds.width
let itemWidth: CGFloat = itemHeight / aspectRatio
print("width: \(itemWidth)")
let horizontalPadding: CGFloat = 10.0
for var i = 0; i < herbs.count; i++ {
let imageView = listView.viewWithTag(i+100) as! UIImageView
imageView.frame = CGRect(x: CGFloat(i+1) * horizontalPadding + CGFloat(i) * itemWidth, y: 0, width: itemWidth, height: itemHeight)
print("frame: \(imageView.frame)")
}
listView.contentSize = CGSize(width: CGFloat(herbs.count) * (itemWidth+horizontalPadding) + horizontalPadding, height: 0)
}
func didTapImageView(tap: UITapGestureRecognizer) {
selectedImage = tap.view as? UIImageView
let index = tap.view!.tag - 100
let selectedHerb = herbs[index]
//present details view controller
let herbDetails = storyboard!.instantiateViewControllerWithIdentifier("HerbDetailsViewController") as! HerbDetailsViewController
herbDetails.herb = selectedHerb
herbDetails.transitioningDelegate = self
presentViewController(herbDetails, animated: true, completion: nil)
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
coordinator.animateAlongsideTransition({ (context) -> Void in
self.bgImage.alpha = (size.width > size.height) ? 0.25 : 0.55
self.positionListItems()
}, completion: nil)
}
}
extension ViewController: UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.originFrame = selectedImage!.superview!.convertRect(selectedImage!.frame, toView: nil)
transition.presenting = true
selectedImage!.hidden = true
return transition
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.presenting = false
return transition
}
}
| b7e5d2a47b20006a5a4b640e1a8f066b | 33.780488 | 217 | 0.650771 | false | false | false | false |
macemmi/HBCI4Swift | refs/heads/master | HBCI4Swift/HBCI4Swift/Source/Orders/HBCICamtStatementsOrder.swift | gpl-2.0 | 1 | //
// HBCICamtStatementsOrder.swift
// HBCI4Swift
//
// Created by Frank Emminghaus on 01.07.20.
// Copyright © 2020 Frank Emminghaus. All rights reserved.
//
import Foundation
open class HBCICamtStatementsOrder: HBCIOrder {
public let account:HBCIAccount;
open var statements:Array<HBCIStatement>
open var dateFrom:Date?
open var dateTo:Date?
var offset:String?
var camtFormat:String?
var bookedPart:Data?
var isPartial = false;
var partNumber = 1;
public init?(message: HBCICustomMessage, account:HBCIAccount) {
self.account = account;
self.statements = Array<HBCIStatement>();
super.init(name: "CamtStatements", message: message);
if self.segment == nil {
return nil;
}
}
open func enqueue() ->Bool {
// check if order is supported
if !user.parameters.isOrderSupportedForAccount(self, number: account.number, subNumber: account.subNumber) {
logInfo(self.name + " is not supported for account " + account.number);
return false;
}
var values = Dictionary<String,Any>();
// check if SEPA version is supported (only globally for bank -
// later we check if account supports this as well
if account.iban == nil || account.bic == nil {
logInfo("Account has no IBAN or BIC information");
return false;
}
values = ["KTV.bic":account.bic!, "KTV.iban":account.iban!, "KTV.number":account.number, "KTV.KIK.country":"280", "KTV.KIK.blz":account.bankCode, "allaccounts":false];
if var date = dateFrom {
if let maxdays = user.parameters.maxStatementDays() {
let currentDate = Date();
let minDate = currentDate.addingTimeInterval((Double)((maxdays-1) * 24 * 3600 * -1));
if minDate > date {
date = minDate;
}
}
values["startdate"] = date;
}
if let date = dateTo {
values["enddate"] = date;
}
if let ofs = offset {
values["offset"] = ofs;
}
let formats = user.parameters.camtFormats();
guard formats.count > 0 else {
logInfo("No supported camt formats");
return false;
}
for format in formats {
if format.hasSuffix("052.001.02") || format.hasSuffix("052.001.08") {
camtFormat = format;
//break;
} else {
logDebug("Camt format "+format+" is not supported");
}
}
guard let format = camtFormat else {
logInfo("No supported Camt formats found");
return false;
}
values["format"] = format;
if !segment.setElementValues(values) {
logInfo("CamtStatements Order values could not be set");
return false;
}
// add to message
return msg.addOrder(self);
}
func getOutstandingPart(_ offset:String) ->Data? {
do {
if let msg = HBCICustomMessage.newInstance(msg.dialog) {
if let order = HBCICamtStatementsOrder(message: msg, account: self.account) {
order.dateFrom = self.dateFrom;
order.dateTo = self.dateTo;
order.offset = offset;
order.isPartial = true;
order.partNumber = self.partNumber + 1;
if !order.enqueue() { return nil; }
_ = try msg.send();
return order.bookedPart;
}
}
}
catch {
// we don't do anything in case of errors
}
return nil;
}
override open func updateResult(_ result: HBCIResultMessage) {
var parser:HBCICamtParser!
super.updateResult(result);
// check whether result is incomplete
self.offset = nil;
for response in result.segmentResponses {
if response.code == "3040" && response.parameters.count > 0 {
self.offset = response.parameters[0];
}
}
if camtFormat!.hasSuffix("052.001.02") {
parser = HBCICamtParser_052_001_02();
} else {
parser = HBCICamtParser_052_001_08();
}
// now parse statements
self.statements.removeAll();
for seg in resultSegments {
if let booked_list = seg.elementValuesForPath("booked.statement") as? [Data] {
for var booked in booked_list {
// check whether result is incomplete
if let offset = self.offset {
if partNumber >= 100 {
// we stop here - too many statement parts
logInfo("Too many statement parts but we still get response 3040 - we stop here")
} else {
if let part2 = getOutstandingPart(offset) {
booked.append(part2);
}
}
}
// check if we are a part or the original order
if isPartial {
self.bookedPart = booked;
} else {
if let statements = parser.parse(account, data: booked, isPreliminary: false) {
self.statements.append(contentsOf: statements);
}
}
}
}
if let notbooked = seg.elementValueForPath("notbooked") as? Data {
if let statements = parser.parse(account, data: notbooked, isPreliminary: true) {
self.statements.append(contentsOf: statements);
}
}
}
}
}
| f27f04e4efe19877a5ee815b07208e7d | 33.891429 | 175 | 0.504586 | false | false | false | false |
soso1617/iCalendar | refs/heads/master | Calendar/Utility/DateConversion.swift | mit | 1 | //
// DateConversion.swift
// Calendar
//
// Created by Zhang, Eric X. on 5/6/17.
// Copyright © 2017 ShangHe. All rights reserved.
//
import Foundation
class DateConversion {
//
// lazy init
//
static var calender: Calendar = { return Calendar.init(identifier: .gregorian) }()
//
// lazy init
//
static var timeZoneDateFormatter: DateFormatter = {
let retDateFormatter = DateFormatter.init()
//
// init dateformatter for global
//
retDateFormatter.timeStyle = .long
retDateFormatter.dateStyle = .short
//
// use current timezone for display
//
retDateFormatter.timeZone = TimeZone.current
return retDateFormatter
}()
//
// lazy init
//
static var ISO8601DateFormatter: DateFormatter = {
let retDateFormatter = DateFormatter.init()
retDateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
retDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
return retDateFormatter
}()
//
// lazy init
//
static var HHMMDateFormatter: DateFormatter = {
let retDateFormatter = DateFormatter.init()
retDateFormatter.locale = Locale.current
retDateFormatter.timeZone = TimeZone.current
retDateFormatter.dateFormat = "HH:mm"
return retDateFormatter
}()
//
// lazy init
//
static var LongDateFormatter: DateFormatter = {
let retDateFormatter = DateFormatter.init()
retDateFormatter.locale = Locale.current
retDateFormatter.timeZone = TimeZone.current
retDateFormatter.timeStyle = .none
retDateFormatter.dateStyle = .long
return retDateFormatter
}()
//
// convert kind formatter of "2016-11-30T09:20:30+08:00" to date
//
class func dateFromISO8601String(_ dateString: String) -> Date? {
return ISO8601DateFormatter.date(from: dateString)
}
//
// convert timestamp to date string
//
class func dateStringWithSystemSpecifiedTimeZoneFromTimeStamp(_ timeStamp: Double) -> String {
return timeZoneDateFormatter.string(from: Date.init(timeIntervalSince1970: timeStamp))
}
//
// convert date to date string
//
class func dateStringWithSystemSpecifiedTimeZoneFromDate(_ date: Date) -> String {
return timeZoneDateFormatter.string(from: date)
}
//
// convert date to "HH:MM"
//
class func date2MMSSFromDate(_ date: Date) -> String {
return HHMMDateFormatter.string(from: date)
}
//
// convert date to long date string
//
class func date2LongStringFromDate(_ date: Date) -> String {
return LongDateFormatter.string(from: date)
}
//
// check to date is in same day
//
class func compare2DateIsSame(_ date: Date, comparedDate: Date) -> Bool {
let component1 = self.calender.dateComponents([.year, .month, .day], from: date)
let component2 = self.calender.dateComponents([.year, .month, .day], from: comparedDate)
return ((component1.day! == component2.day!) && (component1.month! == component2.month!) && (component1.year! == component2.year!))
}
}
| 292ea761db1c4442b196171501461184 | 25.867188 | 139 | 0.59843 | false | false | false | false |
EdwaRen/Recycle_Can_iOS | refs/heads/master | Recycle_Can/Recycle Can/ViewControllerAbout.swift | mit | 1 | //
// ViewControllerAbout.swift
// Recycle Can
//
// Created by - on 2017/06/13.
// Copyright © 2017 Recycle Canada. All rights reserved.
//
import UIKit
import MessageUI
import Foundation
import Social
class ViewControllerAbout: UIViewController, MFMailComposeViewControllerDelegate {
@IBOutlet weak var logoImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if (screenHeight <= 480) {
print(screenHeight)
print(screenWidth)
print("Success!")
logoImage.alpha = 0
} else {
print("Not an iPhone 4s... or this does not work :(")
}
}
@IBAction func RateBtn(_ sender: Any) {
let alert = UIAlertController(title: "Rate This App", message: "This will open up the App Store", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Go", style: UIAlertActionStyle.default) { _ in
// Open App in AppStore
let iLink = "https://itunes.apple.com/us/app/recycle-can/id1248915926?ls=1&mt=8"
UIApplication.shared.openURL(NSURL(string: iLink)! as URL)
} )
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
@IBAction func WebBtn(_ sender: Any) {
let iLink = "http://www.recyclecan.ca"
UIApplication.shared.openURL(NSURL(string: iLink)! as URL)
}
@IBAction func FacebookBtn(_ sender: Any) {
// Check if Facebook is available
if (SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook))
{
// Create the post
let post = SLComposeViewController(forServiceType: (SLServiceTypeFacebook))
post?.setInitialText("\n\nhttps://itunes.apple.com/us/app/recycle-can/id1248915926?ls=1&mt=8")
post?.add(UIImage(named: "Screenshot_5"))
self.present(post!, animated: true, completion: nil)
} else {
// Facebook not available. Show a warning
let alert = UIAlertController(title: "Facebook", message: "Facebook not available", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
@IBAction func MailBtn(_ sender: Any) {
// Check if Mail is available
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.present(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
// mailComposerVC.setToRecipients(["[email protected]"])
mailComposerVC.setSubject("Check Out This Recycling App!")
mailComposerVC.setMessageBody("\n\n\nhttps://itunes.apple.com/us/app/recycle-can/id1248915926?ls=1&mt=8", isHTML: false)
let imageData = UIImagePNGRepresentation(UIImage(named: "Screenshot_5")!)
mailComposerVC.addAttachmentData(imageData!, mimeType: "image/png", fileName: "Image")
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
// MARK: MFMailComposeViewControllerDelegate Method
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
}
| 8ff0d31348fefdbcb6096fa846c94460 | 41.359223 | 213 | 0.659638 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/SILGen/builtins.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -parse-stdlib %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-sil -Onone -parse-stdlib %s -disable-objc-attr-requires-foundation-module | %FileCheck -check-prefix=CANONICAL %s
import Swift
protocol ClassProto : class { }
struct Pointer {
var value: Builtin.RawPointer
}
// CHECK-LABEL: sil hidden @_T08builtins3foo{{[_0-9a-zA-Z]*}}F
func foo(_ x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 {
// CHECK: builtin "cmp_eq_Int1"
return Builtin.cmp_eq_Int1(x, y)
}
// CHECK-LABEL: sil hidden @_T08builtins8load_pod{{[_0-9a-zA-Z]*}}F
func load_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden @_T08builtins8load_obj{{[_0-9a-zA-Z]*}}F
func load_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [copy] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden @_T08builtins12load_raw_pod{{[_0-9a-zA-Z]*}}F
func load_raw_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.loadRaw(x)
}
// CHECK-LABEL: sil hidden @_T08builtins12load_raw_obj{{[_0-9a-zA-Z]*}}F
func load_raw_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [copy] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.loadRaw(x)
}
// CHECK-LABEL: sil hidden @_T08builtins8load_gen{{[_0-9a-zA-Z]*}}F
func load_gen<T>(_ x: Builtin.RawPointer) -> T {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}}
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden @_T08builtins8move_pod{{[_0-9a-zA-Z]*}}F
func move_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden @_T08builtins8move_obj{{[_0-9a-zA-Z]*}}F
func move_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [take] [[ADDR]]
// CHECK-NOT: copy_value [[VAL]]
// CHECK: return [[VAL]]
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden @_T08builtins8move_gen{{[_0-9a-zA-Z]*}}F
func move_gen<T>(_ x: Builtin.RawPointer) -> T {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}}
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden @_T08builtins11destroy_pod{{[_0-9a-zA-Z]*}}F
func destroy_pod(_ x: Builtin.RawPointer) {
var x = x
// CHECK: [[XBOX:%[0-9]+]] = alloc_box
// CHECK-NOT: pointer_to_address
// CHECK-NOT: destroy_addr
// CHECK-NOT: destroy_value
// CHECK: destroy_value [[XBOX]] : ${{.*}}{
// CHECK-NOT: destroy_value
return Builtin.destroy(Builtin.Int64, x)
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T08builtins11destroy_obj{{[_0-9a-zA-Z]*}}F
func destroy_obj(_ x: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: destroy_addr [[ADDR]]
return Builtin.destroy(Builtin.NativeObject, x)
}
// CHECK-LABEL: sil hidden @_T08builtins11destroy_gen{{[_0-9a-zA-Z]*}}F
func destroy_gen<T>(_ x: Builtin.RawPointer, _: T) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: destroy_addr [[ADDR]]
return Builtin.destroy(T.self, x)
}
// CHECK-LABEL: sil hidden @_T08builtins10assign_pod{{[_0-9a-zA-Z]*}}F
func assign_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) {
var x = x
var y = y
// CHECK: alloc_box
// CHECK: alloc_box
// CHECK-NOT: alloc_box
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK-NOT: load [[ADDR]]
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK: destroy_value
// CHECK: destroy_value
// CHECK-NOT: destroy_value
Builtin.assign(x, y)
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T08builtins10assign_obj{{[_0-9a-zA-Z]*}}F
func assign_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK: destroy_value
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden @_T08builtins12assign_tuple{{[_0-9a-zA-Z]*}}F
func assign_tuple(_ x: (Builtin.Int64, Builtin.NativeObject),
y: Builtin.RawPointer) {
var x = x
var y = y
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*(Builtin.Int64, Builtin.NativeObject)
// CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]]
// CHECK: assign {{%.*}} to [[T0]]
// CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]]
// CHECK: assign {{%.*}} to [[T0]]
// CHECK: destroy_value
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden @_T08builtins10assign_gen{{[_0-9a-zA-Z]*}}F
func assign_gen<T>(_ x: T, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [take] {{%.*}} to [[ADDR]] :
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden @_T08builtins8init_pod{{[_0-9a-zA-Z]*}}F
func init_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK-NOT: load [[ADDR]]
// CHECK: store {{%.*}} to [trivial] [[ADDR]]
// CHECK-NOT: destroy_value [[ADDR]]
Builtin.initialize(x, y)
}
// CHECK-LABEL: sil hidden @_T08builtins8init_obj{{[_0-9a-zA-Z]*}}F
func init_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK-NOT: load [[ADDR]]
// CHECK: store [[SRC:%.*]] to [init] [[ADDR]]
// CHECK-NOT: destroy_value [[SRC]]
Builtin.initialize(x, y)
}
// CHECK-LABEL: sil hidden @_T08builtins8init_gen{{[_0-9a-zA-Z]*}}F
func init_gen<T>(_ x: T, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [[OTHER_LOC:%.*]] to [initialization] [[ADDR]]
// CHECK: destroy_addr [[OTHER_LOC]]
Builtin.initialize(x, y)
}
class C {}
class D {}
// CHECK-LABEL: sil hidden @_T08builtins22class_to_native_object{{[_0-9a-zA-Z]*}}F
func class_to_native_object(_ c:C) -> Builtin.NativeObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject
// CHECK-NOT: destroy_value [[C]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToNativeObject(c)
}
// CHECK-LABEL: sil hidden @_T08builtins23class_to_unknown_object{{[_0-9a-zA-Z]*}}F
func class_to_unknown_object(_ c:C) -> Builtin.UnknownObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject
// CHECK-NOT: destroy_value [[C]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToUnknownObject(c)
}
// CHECK-LABEL: sil hidden @_T08builtins32class_archetype_to_native_object{{[_0-9a-zA-Z]*}}F
func class_archetype_to_native_object<T : C>(_ t: T) -> Builtin.NativeObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject
// CHECK-NOT: destroy_value [[C]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToNativeObject(t)
}
// CHECK-LABEL: sil hidden @_T08builtins33class_archetype_to_unknown_object{{[_0-9a-zA-Z]*}}F
func class_archetype_to_unknown_object<T : C>(_ t: T) -> Builtin.UnknownObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject
// CHECK-NOT: destroy_value [[C]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToUnknownObject(t)
}
// CHECK-LABEL: sil hidden @_T08builtins34class_existential_to_native_object{{[_0-9a-zA-Z]*}}F
func class_existential_to_native_object(_ t:ClassProto) -> Builtin.NativeObject {
// CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto
// CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject
return Builtin.castToNativeObject(t)
}
// CHECK-LABEL: sil hidden @_T08builtins35class_existential_to_unknown_object{{[_0-9a-zA-Z]*}}F
func class_existential_to_unknown_object(_ t:ClassProto) -> Builtin.UnknownObject {
// CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto
// CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.UnknownObject
return Builtin.castToUnknownObject(t)
}
// CHECK-LABEL: sil hidden @_T08builtins24class_from_native_object{{[_0-9a-zA-Z]*}}F
func class_from_native_object(_ p: Builtin.NativeObject) -> C {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C
// CHECK-NOT: destroy_value [[C]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden @_T08builtins25class_from_unknown_object{{[_0-9a-zA-Z]*}}F
func class_from_unknown_object(_ p: Builtin.UnknownObject) -> C {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C
// CHECK-NOT: destroy_value [[C]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromUnknownObject(p)
}
// CHECK-LABEL: sil hidden @_T08builtins34class_archetype_from_native_object{{[_0-9a-zA-Z]*}}F
func class_archetype_from_native_object<T : C>(_ p: Builtin.NativeObject) -> T {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $T
// CHECK-NOT: destroy_value [[C]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden @_T08builtins35class_archetype_from_unknown_object{{[_0-9a-zA-Z]*}}F
func class_archetype_from_unknown_object<T : C>(_ p: Builtin.UnknownObject) -> T {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $T
// CHECK-NOT: destroy_value [[C]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromUnknownObject(p)
}
// CHECK-LABEL: sil hidden @_T08builtins41objc_class_existential_from_native_object{{[_0-9a-zA-Z]*}}F
func objc_class_existential_from_native_object(_ p: Builtin.NativeObject) -> AnyObject {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $AnyObject
// CHECK-NOT: destroy_value [[C]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden @_T08builtins42objc_class_existential_from_unknown_object{{[_0-9a-zA-Z]*}}F
func objc_class_existential_from_unknown_object(_ p: Builtin.UnknownObject) -> AnyObject {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $AnyObject
// CHECK-NOT: destroy_value [[C]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromUnknownObject(p)
}
// CHECK-LABEL: sil hidden @_T08builtins20class_to_raw_pointer{{[_0-9a-zA-Z]*}}F
func class_to_raw_pointer(_ c: C) -> Builtin.RawPointer {
// CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer
// CHECK: return [[RAW]]
return Builtin.bridgeToRawPointer(c)
}
func class_archetype_to_raw_pointer<T : C>(_ t: T) -> Builtin.RawPointer {
return Builtin.bridgeToRawPointer(t)
}
protocol CP: class {}
func existential_to_raw_pointer(_ p: CP) -> Builtin.RawPointer {
return Builtin.bridgeToRawPointer(p)
}
// CHECK-LABEL: sil hidden @_T08builtins18obj_to_raw_pointer{{[_0-9a-zA-Z]*}}F
func obj_to_raw_pointer(_ c: Builtin.NativeObject) -> Builtin.RawPointer {
// CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer
// CHECK: return [[RAW]]
return Builtin.bridgeToRawPointer(c)
}
// CHECK-LABEL: sil hidden @_T08builtins22class_from_raw_pointer{{[_0-9a-zA-Z]*}}F
func class_from_raw_pointer(_ p: Builtin.RawPointer) -> C {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C
// CHECK: [[C_COPY:%.*]] = copy_value [[C]]
// CHECK: return [[C_COPY]]
return Builtin.bridgeFromRawPointer(p)
}
func class_archetype_from_raw_pointer<T : C>(_ p: Builtin.RawPointer) -> T {
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_T08builtins20obj_from_raw_pointer{{[_0-9a-zA-Z]*}}F
func obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject
// CHECK: [[C_COPY:%.*]] = copy_value [[C]]
// CHECK: return [[C_COPY]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_T08builtins28unknown_obj_from_raw_pointer{{[_0-9a-zA-Z]*}}F
func unknown_obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.UnknownObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.UnknownObject
// CHECK: [[C_COPY:%.*]] = copy_value [[C]]
// CHECK: return [[C_COPY]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_T08builtins28existential_from_raw_pointer{{[_0-9a-zA-Z]*}}F
func existential_from_raw_pointer(_ p: Builtin.RawPointer) -> AnyObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject
// CHECK: [[C_COPY:%.*]] = copy_value [[C]]
// CHECK: return [[C_COPY]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_T08builtins9gep_raw64{{[_0-9a-zA-Z]*}}F
func gep_raw64(_ p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer {
// CHECK: [[GEP:%.*]] = index_raw_pointer
// CHECK: return [[GEP]]
return Builtin.gepRaw_Int64(p, i)
}
// CHECK-LABEL: sil hidden @_T08builtins9gep_raw32{{[_0-9a-zA-Z]*}}F
func gep_raw32(_ p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer {
// CHECK: [[GEP:%.*]] = index_raw_pointer
// CHECK: return [[GEP]]
return Builtin.gepRaw_Int32(p, i)
}
// CHECK-LABEL: sil hidden @_T08builtins3gep{{[_0-9a-zA-Z]*}}F
func gep<Elem>(_ p: Builtin.RawPointer, i: Builtin.Word, e: Elem.Type) -> Builtin.RawPointer {
// CHECK: [[P2A:%.*]] = pointer_to_address %0
// CHECK: [[GEP:%.*]] = index_addr [[P2A]] : $*Elem, %1 : $Builtin.Word
// CHECK: [[A2P:%.*]] = address_to_pointer [[GEP]]
// CHECK: return [[A2P]]
return Builtin.gep_Word(p, i, e)
}
public final class Header { }
// CHECK-LABEL: sil hidden @_T08builtins20allocWithTailElems_1{{[_0-9a-zA-Z]*}}F
func allocWithTailElems_1<T>(n: Builtin.Word, ty: T.Type) -> Header {
// CHECK: [[M:%.*]] = metatype $@thick Header.Type
// CHECK: [[A:%.*]] = alloc_ref [tail_elems $T * %0 : $Builtin.Word] $Header
// CHECK: return [[A]]
return Builtin.allocWithTailElems_1(Header.self, n, ty)
}
// CHECK-LABEL: sil hidden @_T08builtins20allocWithTailElems_3{{[_0-9a-zA-Z]*}}F
func allocWithTailElems_3<T1, T2, T3>(n1: Builtin.Word, ty1: T1.Type, n2: Builtin.Word, ty2: T2.Type, n3: Builtin.Word, ty3: T3.Type) -> Header {
// CHECK: [[M:%.*]] = metatype $@thick Header.Type
// CHECK: [[A:%.*]] = alloc_ref [tail_elems $T1 * %0 : $Builtin.Word] [tail_elems $T2 * %2 : $Builtin.Word] [tail_elems $T3 * %4 : $Builtin.Word] $Header
// CHECK: return [[A]]
return Builtin.allocWithTailElems_3(Header.self, n1, ty1, n2, ty2, n3, ty3)
}
// CHECK-LABEL: sil hidden @_T08builtins16projectTailElems{{[_0-9a-zA-Z]*}}F
func projectTailElems<T>(h: Header, ty: T.Type) -> Builtin.RawPointer {
// CHECK: bb0([[ARG1:%.*]] : $Header
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[ARG1]]
// CHECK: [[TA:%.*]] = ref_tail_addr [[ARG1_COPY]] : $Header
// CHECK: [[A2P:%.*]] = address_to_pointer [[TA]]
// CHECK: destroy_value [[ARG1_COPY]]
// CHECK: destroy_value [[ARG1]]
// CHECK: return [[A2P]]
return Builtin.projectTailElems(h, ty)
}
// CHECK: } // end sil function '_T08builtins16projectTailElemsBpAA6HeaderC1h_xm2tytlF'
// CHECK-LABEL: sil hidden @_T08builtins11getTailAddr{{[_0-9a-zA-Z]*}}F
func getTailAddr<T1, T2>(start: Builtin.RawPointer, i: Builtin.Word, ty1: T1.Type, ty2: T2.Type) -> Builtin.RawPointer {
// CHECK: [[P2A:%.*]] = pointer_to_address %0
// CHECK: [[TA:%.*]] = tail_addr [[P2A]] : $*T1, %1 : $Builtin.Word, $T2
// CHECK: [[A2P:%.*]] = address_to_pointer [[TA]]
// CHECK: return [[A2P]]
return Builtin.getTailAddr_Word(start, i, ty1, ty2)
}
// CHECK-LABEL: sil hidden @_T08builtins8condfail{{[_0-9a-zA-Z]*}}F
func condfail(_ i: Builtin.Int1) {
Builtin.condfail(i)
// CHECK: cond_fail {{%.*}} : $Builtin.Int1
}
struct S {}
@objc class O {}
@objc protocol OP1 {}
@objc protocol OP2 {}
protocol P {}
// CHECK-LABEL: sil hidden @_T08builtins10canBeClass{{[_0-9a-zA-Z]*}}F
func canBeClass<T>(_: T) {
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(O.self)
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(OP1.self)
// -- FIXME: 'OP1 & OP2' doesn't parse as a value
typealias ObjCCompo = OP1 & OP2
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(ObjCCompo.self)
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(S.self)
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(C.self)
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(P.self)
typealias MixedCompo = OP1 & P
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(MixedCompo.self)
// CHECK: builtin "canBeClass"<T>
Builtin.canBeClass(T.self)
}
// FIXME: "T.Type.self" does not parse as an expression
// CHECK-LABEL: sil hidden @_T08builtins18canBeClassMetatype{{[_0-9a-zA-Z]*}}F
func canBeClassMetatype<T>(_: T) {
// CHECK: integer_literal $Builtin.Int8, 0
typealias OT = O.Type
Builtin.canBeClass(OT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias OP1T = OP1.Type
Builtin.canBeClass(OP1T.self)
// -- FIXME: 'OP1 & OP2' doesn't parse as a value
typealias ObjCCompoT = (OP1 & OP2).Type
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(ObjCCompoT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias ST = S.Type
Builtin.canBeClass(ST.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias CT = C.Type
Builtin.canBeClass(CT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias PT = P.Type
Builtin.canBeClass(PT.self)
typealias MixedCompoT = (OP1 & P).Type
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(MixedCompoT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias TT = T.Type
Builtin.canBeClass(TT.self)
}
// CHECK-LABEL: sil hidden @_T08builtins11fixLifetimeyAA1CCF : $@convention(thin) (@owned C) -> () {
func fixLifetime(_ c: C) {
// CHECK: bb0([[ARG:%.*]] : $C):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: fix_lifetime [[ARG_COPY]] : $C
// CHECK: destroy_value [[ARG_COPY]]
// CHECK: destroy_value [[ARG]]
Builtin.fixLifetime(c)
}
// CHECK: } // end sil function '_T08builtins11fixLifetimeyAA1CCF'
// CHECK-LABEL: sil hidden @_T08builtins20assert_configuration{{[_0-9a-zA-Z]*}}F
func assert_configuration() -> Builtin.Int32 {
return Builtin.assert_configuration()
// CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32
// CHECK: return [[APPLY]] : $Builtin.Int32
}
// CHECK-LABEL: sil hidden @_T08builtins17assumeNonNegativeBwBwF
func assumeNonNegative(_ x: Builtin.Word) -> Builtin.Word {
return Builtin.assumeNonNegative_Word(x)
// CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word
// CHECK: return [[APPLY]] : $Builtin.Word
}
// CHECK-LABEL: sil hidden @_T08builtins11autoreleaseyAA1OCF : $@convention(thin) (@owned O) -> () {
// ==> SEMANTIC ARC TODO: This will be unbalanced... should we allow it?
// CHECK: bb0([[ARG:%.*]] : $O):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: autorelease_value [[ARG_COPY]]
// CHECK: destroy_value [[ARG_COPY]]
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '_T08builtins11autoreleaseyAA1OCF'
func autorelease(_ o: O) {
Builtin.autorelease(o)
}
// The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during
// diagnostics.
// CHECK-LABEL: sil hidden @_T08builtins11unreachable{{[_0-9a-zA-Z]*}}F
// CHECK: builtin "unreachable"()
// CHECK: return
// CANONICAL-LABEL: sil hidden @_T08builtins11unreachableyyF : $@convention(thin) () -> () {
func unreachable() {
Builtin.unreachable()
}
// CHECK-LABEL: sil hidden @_T08builtins15reinterpretCastBw_AA1DCAA1CCSgAFtAF_Bw1xtF : $@convention(thin) (@owned C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C)
// CHECK: bb0([[ARG1:%.*]] : $C, [[ARG2:%.*]] : $Builtin.Word):
// CHECK-NEXT: debug_value
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[ARG1_COPY1:%.*]] = copy_value [[ARG1]] : $C
// CHECK-NEXT: [[ARG1_TRIVIAL:%.*]] = unchecked_trivial_bit_cast [[ARG1_COPY1]] : $C to $Builtin.Word
// CHECK-NEXT: [[ARG1_COPY2:%.*]] = copy_value [[ARG1]] : $C
// CHECK-NEXT: [[ARG1_COPY2_CASTED:%.*]] = unchecked_ref_cast [[ARG1_COPY2]] : $C to $D
// CHECK-NEXT: [[ARG1_COPY3:%.*]] = copy_value [[ARG1]]
// CHECK-NEXT: [[ARG1_COPY3_CAST:%.*]] = unchecked_ref_cast [[ARG1_COPY3]] : $C to $Optional<C>
// CHECK-NEXT: [[ARG2_OBJ_CASTED:%.*]] = unchecked_bitwise_cast [[ARG2]] : $Builtin.Word to $C
// CHECK-NEXT: [[ARG2_OBJ_CASTED_COPIED:%.*]] = copy_value [[ARG2_OBJ_CASTED]] : $C
// CHECK-NEXT: destroy_value [[ARG1_COPY1]]
// CHECK-NEXT: destroy_value [[ARG1]]
// CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ARG1_TRIVIAL]] : $Builtin.Word, [[ARG1_COPY2_CASTED]] : $D, [[ARG1_COPY3_CAST]] : $Optional<C>, [[ARG2_OBJ_CASTED_COPIED:%.*]] : $C)
// CHECK: return [[RESULT]]
func reinterpretCast(_ c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) {
return (Builtin.reinterpretCast(c) as Builtin.Word,
Builtin.reinterpretCast(c) as D,
Builtin.reinterpretCast(c) as C?,
Builtin.reinterpretCast(x) as C)
}
// CHECK-LABEL: sil hidden @_T08builtins19reinterpretAddrOnly{{[_0-9a-zA-Z]*}}F
func reinterpretAddrOnly<T, U>(_ t: T) -> U {
// CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U
return Builtin.reinterpretCast(t)
}
// CHECK-LABEL: sil hidden @_T08builtins28reinterpretAddrOnlyToTrivial{{[_0-9a-zA-Z]*}}F
func reinterpretAddrOnlyToTrivial<T>(_ t: T) -> Int {
// CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT:%.*]] : $*T to $*Int
// CHECK: [[VALUE:%.*]] = load [trivial] [[ADDR]]
// CHECK: destroy_addr [[INPUT]]
return Builtin.reinterpretCast(t)
}
// CHECK-LABEL: sil hidden @_T08builtins27reinterpretAddrOnlyLoadable{{[_0-9a-zA-Z]*}}F
func reinterpretAddrOnlyLoadable<T>(_ a: Int, _ b: T) -> (T, Int) {
// CHECK: [[BUF:%.*]] = alloc_stack $Int
// CHECK: store {{%.*}} to [trivial] [[BUF]]
// CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]] : $*Int to $*T
// CHECK: copy_addr [[RES1]] to [initialization]
return (Builtin.reinterpretCast(a) as T,
// CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int
// CHECK: load [trivial] [[RES]]
Builtin.reinterpretCast(b) as Int)
}
// CHECK-LABEL: sil hidden @_T08builtins18castToBridgeObject{{[_0-9a-zA-Z]*}}F
// CHECK: [[BO:%.*]] = ref_to_bridge_object {{%.*}} : $C, {{%.*}} : $Builtin.Word
// CHECK: return [[BO]]
func castToBridgeObject(_ c: C, _ w: Builtin.Word) -> Builtin.BridgeObject {
return Builtin.castToBridgeObject(c, w)
}
// CHECK-LABEL: sil hidden @_T08builtins23castRefFromBridgeObject{{[_0-9a-zA-Z]*}}F
// CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C
func castRefFromBridgeObject(_ bo: Builtin.BridgeObject) -> C {
return Builtin.castReferenceFromBridgeObject(bo)
}
// CHECK-LABEL: sil hidden @_T08builtins30castBitPatternFromBridgeObject{{[_0-9a-zA-Z]*}}F
// CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word
// CHECK: destroy_value [[BO]]
func castBitPatternFromBridgeObject(_ bo: Builtin.BridgeObject) -> Builtin.Word {
return Builtin.castBitPatternFromBridgeObject(bo)
}
// CHECK-LABEL: sil hidden @_T08builtins8pinUnpin{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[ARG:%.*]] : $Builtin.NativeObject):
// CHECK-NEXT: debug_value
func pinUnpin(_ object : Builtin.NativeObject) {
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] : $Builtin.NativeObject
// CHECK-NEXT: [[HANDLE:%.*]] = strong_pin [[ARG_COPY]] : $Builtin.NativeObject
// CHECK-NEXT: debug_value
// CHECK-NEXT: destroy_value [[ARG_COPY]] : $Builtin.NativeObject
let handle : Builtin.NativeObject? = Builtin.tryPin(object)
// CHECK-NEXT: [[HANDLE_COPY:%.*]] = copy_value [[HANDLE]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: strong_unpin [[HANDLE_COPY]] : $Optional<Builtin.NativeObject>
// ==> SEMANTIC ARC TODO: This looks like a mispairing or a weird pairing.
Builtin.unpin(handle)
// CHECK-NEXT: tuple ()
// CHECK-NEXT: destroy_value [[HANDLE]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: destroy_value [[ARG]] : $Builtin.NativeObject
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]] : $()
}
// ----------------------------------------------------------------------------
// isUnique variants
// ----------------------------------------------------------------------------
// NativeObject
// CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>):
// CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Optional<Builtin.NativeObject>
// CHECK: return
func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// NativeObject nonNull
// CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.NativeObject):
// CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.NativeObject
// CHECK: return
func isUnique(_ ref: inout Builtin.NativeObject) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// NativeObject pinned
// CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>):
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Optional<Builtin.NativeObject>
// CHECK: return
func isUniqueOrPinned(_ ref: inout Builtin.NativeObject?) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// NativeObject pinned nonNull
// CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.NativeObject):
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.NativeObject
// CHECK: return
func isUniqueOrPinned(_ ref: inout Builtin.NativeObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// UnknownObject (ObjC)
// CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Optional<Builtin.UnknownObject>):
// CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Optional<Builtin.UnknownObject>
// CHECK: return
func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// UnknownObject (ObjC) nonNull
// CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.UnknownObject):
// CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.UnknownObject
// CHECK: return
func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// UnknownObject (ObjC) pinned nonNull
// CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.UnknownObject):
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.UnknownObject
// CHECK: return
func isUniqueOrPinned(_ ref: inout Builtin.UnknownObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// BridgeObject nonNull
// CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.BridgeObject
// CHECK: return
func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// BridgeObject pinned nonNull
// CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.BridgeObject
// CHECK: return
func isUniqueOrPinned(_ ref: inout Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// BridgeObject nonNull native
// CHECK-LABEL: sil hidden @_T08builtins15isUnique_native{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK: [[CAST:%.*]] = unchecked_addr_cast %0 : $*Builtin.BridgeObject to $*Builtin.NativeObject
// CHECK: return
func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUnique_native(&ref))
}
// BridgeObject pinned nonNull native
// CHECK-LABEL: sil hidden @_T08builtins23isUniqueOrPinned_native{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK: [[CAST:%.*]] = unchecked_addr_cast %0 : $*Builtin.BridgeObject to $*Builtin.NativeObject
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[CAST]] : $*Builtin.NativeObject
// CHECK: return
func isUniqueOrPinned_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned_native(&ref))
}
// ----------------------------------------------------------------------------
// Builtin.castReference
// ----------------------------------------------------------------------------
class A {}
protocol PUnknown {}
protocol PClass : class {}
// CHECK-LABEL: sil hidden @_T08builtins19refcast_generic_any{{[_0-9a-zA-Z]*}}F
// CHECK: unchecked_ref_cast_addr T in %{{.*}} : $*T to AnyObject in %{{.*}} : $*AnyObject
func refcast_generic_any<T>(_ o: T) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_T08builtins17refcast_class_anys9AnyObject_pAA1ACF :
// CHECK: bb0([[ARG:%.*]] : $A):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_CASTED:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $A to $AnyObject
// CHECK: destroy_value [[ARG]]
// CHECK: return [[ARG_COPY_CASTED]]
// CHECK: } // end sil function '_T08builtins17refcast_class_anys9AnyObject_pAA1ACF'
func refcast_class_any(_ o: A) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_T08builtins20refcast_punknown_any{{[_0-9a-zA-Z]*}}F
// CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}} : $*PUnknown to AnyObject in %{{.*}} : $*AnyObject
func refcast_punknown_any(_ o: PUnknown) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_T08builtins18refcast_pclass_anys9AnyObject_pAA6PClass_pF :
// CHECK: bb0([[ARG:%.*]] : $PClass):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_CAST:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $PClass to $AnyObject
// CHECK: destroy_value [[ARG]]
// CHECK: return [[ARG_COPY_CAST]]
// CHECK: } // end sil function '_T08builtins18refcast_pclass_anys9AnyObject_pAA6PClass_pF'
func refcast_pclass_any(_ o: PClass) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_T08builtins20refcast_any_punknown{{[_0-9a-zA-Z]*}}F
// CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}} : $*AnyObject to PUnknown in %{{.*}} : $*PUnknown
func refcast_any_punknown(_ o: AnyObject) -> PUnknown {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_T08builtins22unsafeGuaranteed_class{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : $A):
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<A>([[P_COPY]] : $A)
// CHECK: [[R:%.*]] = tuple_extract [[T]] : $(A, Builtin.Int8), 0
// CHECK: [[K:%.*]] = tuple_extract [[T]] : $(A, Builtin.Int8), 1
// CHECK: destroy_value [[R]] : $A
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: destroy_value [[P]]
// CHECK: return [[P_COPY]] : $A
// CHECK: }
func unsafeGuaranteed_class(_ a: A) -> A {
Builtin.unsafeGuaranteed(a)
return a
}
// CHECK-LABEL: _T08builtins24unsafeGuaranteed_generic{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : $T):
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T)
// CHECK: [[R:%.*]] = tuple_extract [[T]] : $(T, Builtin.Int8), 0
// CHECK: [[K:%.*]] = tuple_extract [[T]] : $(T, Builtin.Int8), 1
// CHECK: destroy_value [[R]] : $T
// CHECK: [[P_RETURN:%.*]] = copy_value [[P]]
// CHECK: destroy_value [[P]]
// CHECK: return [[P_RETURN]] : $T
// CHECK: }
func unsafeGuaranteed_generic<T: AnyObject> (_ a: T) -> T {
Builtin.unsafeGuaranteed(a)
return a
}
// CHECK_LABEL: sil hidden @_T08builtins31unsafeGuaranteed_generic_return{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : $T):
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T)
// CHECK: [[R]] = tuple_extract [[T]] : $(T, Builtin.Int8), 0
// CHECK: [[K]] = tuple_extract [[T]] : $(T, Builtin.Int8), 1
// CHECK: destroy_value [[P]]
// CHECK: [[S:%.*]] = tuple ([[R]] : $T, [[K]] : $Builtin.Int8)
// CHECK: return [[S]] : $(T, Builtin.Int8)
// CHECK: }
func unsafeGuaranteed_generic_return<T: AnyObject> (_ a: T) -> (T, Builtin.Int8) {
return Builtin.unsafeGuaranteed(a)
}
// CHECK-LABEL: sil hidden @_T08builtins19unsafeGuaranteedEnd{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : $Builtin.Int8):
// CHECK: builtin "unsafeGuaranteedEnd"([[P]] : $Builtin.Int8)
// CHECK: [[S:%.*]] = tuple ()
// CHECK: return [[S]] : $()
// CHECK: }
func unsafeGuaranteedEnd(_ t: Builtin.Int8) {
Builtin.unsafeGuaranteedEnd(t)
}
// CHECK-LABEL: sil hidden @_T08builtins10bindMemory{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : $Builtin.RawPointer, [[I:%.*]] : $Builtin.Word, [[T:%.*]] : $@thick T.Type):
// CHECK: bind_memory [[P]] : $Builtin.RawPointer, [[I]] : $Builtin.Word to $*T
// CHECK: return {{%.*}} : $()
// CHECK: }
func bindMemory<T>(ptr: Builtin.RawPointer, idx: Builtin.Word, _: T.Type) {
Builtin.bindMemory(ptr, idx, T.self)
}
| a687fd4a4e90aea40615008828fd5678 | 40.426859 | 188 | 0.634182 | false | false | false | false |
pnhechim/Fiestapp-iOS | refs/heads/master | Fiestapp/Fiestapp/ViewControllers/Matches/MatchesTableViewController.swift | mit | 1 | //
// MatchesTableViewController.swift
// Fiestapp
//
// Created by Nicolás Hechim on 2/7/17.
// Copyright © 2017 Mint. All rights reserved.
//
import UIKit
class MatchesTableViewController: UITableViewController {
let cellHeight: CGFloat = 84
let cellIdentifier = "MatchCell"
var idFiesta = String()
var idUsuarioMatch = String()
var invitados = [UsuarioModel]()
override func viewDidLoad() {
super.viewDidLoad()
ProgressOverlayView.shared.showProgressView(view)
MeGustasService.shared.obtenerMatches(idFiesta: "-KkrLG86TLQ4HcURJynY") { idUsuariosMatch in
if idUsuariosMatch.count == 0 {
ProgressOverlayView.shared.hideProgressView()
self.performSegue(withIdentifier: "segueSinMatches", sender: self)
}
self.invitados = Common.shared.initUsuariosConListaIds(ids: idUsuariosMatch)
FacebookService.shared.completarDatosInvitadosFacebook(invitados: self.invitados) { success in
self.tableView.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return invitados.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MatchTableViewCell else {
fatalError("The dequeued cell is not an instance of MatchTableViewCell.")
}
initPrototypeCell(cell: cell, invitado: invitados[indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return cellHeight
}
// MARK: - Navigation
// method to run when table view cell is tapped
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.idUsuarioMatch = self.invitados[indexPath.row].Id
let fotoPerfilInvitadoMatch = UIImageView(frame: CGRect(x: 10, y: 70, width: 250, height: 172))
fotoPerfilInvitadoMatch.image = invitados[indexPath.row].FotoPerfil.image
fotoPerfilInvitadoMatch.contentMode = .scaleAspectFit
let tap = UITapGestureRecognizer(target: self, action: #selector(self.abrirPerfil(_:)))
fotoPerfilInvitadoMatch.addGestureRecognizer(tap)
fotoPerfilInvitadoMatch.isUserInteractionEnabled = true
let spacer = "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
let alertController = UIAlertController(title: "¡Da el próximo paso!" , message: invitados[indexPath.row].Nombre + spacer, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Ver perfil", style: UIAlertActionStyle.default)
{
(result : UIAlertAction) -> Void in
FacebookService.shared.abrirPerfil(idUsuario: self.invitados[indexPath.row].Id)
})
alertController.addAction(UIAlertAction(title: "Cerrar", style: UIAlertActionStyle.cancel) {
(result : UIAlertAction) -> Void in
})
alertController.view.addSubview(fotoPerfilInvitadoMatch)
self.present(alertController, animated: true, completion: nil)
}
func initPrototypeCell(cell: MatchTableViewCell, invitado: UsuarioModel) {
cell.iconCircle.image = invitado.FotoPerfil.image
cell.iconCircle.layer.cornerRadius = cell.iconCircle.frame.height/2
cell.iconCircle.layer.masksToBounds = false
cell.iconCircle.clipsToBounds = true
cell.name.text = invitado.Nombre
cell.cardMask.layer.cornerRadius = 4
cell.contentViewCell.backgroundColor = UIColor(red: 245/255,
green: 245/255,
blue: 245/255,
alpha: 1)
cell.cardMask.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
cell.cardMask.layer.masksToBounds = false
cell.cardMask.layer.shadowOpacity = 0.8
cell.cardMask.layer.shadowOffset = CGSize(width: 0, height: 0)
}
func setIdFiesta(idFiesta: String) {
self.idFiesta = idFiesta
}
func abrirPerfil(_ sender: UITapGestureRecognizer) {
FacebookService.shared.abrirPerfil(idUsuario: idUsuarioMatch)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segueSinMatches" {
let meGustasSinResultadosViewController = segue.destination as! MeGustasSinResultadosViewController
meGustasSinResultadosViewController.setTitulo(titulo: MeGustasService.MIS_MATCHES)
meGustasSinResultadosViewController.setMensaje(mensaje: MeGustasService.SIN_MATCHES)
}
}
}
| 40ae232dd9679b692bd4b1749fdee667 | 40.503876 | 176 | 0.654277 | false | false | false | false |
JGiola/swift | refs/heads/main | benchmark/single-source/ObserverUnappliedMethod.swift | apache-2.0 | 10 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let benchmarks =
BenchmarkInfo(
name: "ObserverUnappliedMethod",
runFunction: run_ObserverUnappliedMethod,
tags: [.validation],
legacyFactor: 10)
class Observer {
@inline(never)
func receive(_ value: Int) {
}
}
protocol Sink {
func receive(_ value: Int)
}
struct Forwarder<Object>: Sink {
let object: Object
let method: (Object) -> (Int) -> ()
func receive(_ value: Int) {
method(object)(value)
}
}
class Signal {
var observers: [Sink] = []
func subscribe(_ sink: Sink) {
observers.append(sink)
}
func send(_ value: Int) {
for observer in observers {
observer.receive(value)
}
}
}
public func run_ObserverUnappliedMethod(_ iterations: Int) {
let signal = Signal()
let observer = Observer()
for _ in 0 ..< 1_000 * iterations {
let forwarder = Forwarder(object: observer, method: Observer.receive)
signal.subscribe(forwarder)
}
signal.send(1)
}
| 30925bf12bbad4ea0ee1b853622a7c0a | 22.507937 | 80 | 0.602971 | false | false | false | false |
objecthub/swift-lispkit | refs/heads/master | Sources/LispKit/Graphics/DrawingDocument.swift | apache-2.0 | 1 | //
// DrawingDocument.swift
// LispKit
//
// Created by Matthias Zenger on 01/07/2018.
// Copyright © 2018 ObjectHub. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import CoreGraphics
#if os(iOS) || os(watchOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
///
/// A `DrawingDocument` object represents a document whose pages consist of drawings.
/// For now, the main purpose of creating a `DrawingDocument` object is to save it into
/// a PDF document.
///
public final class DrawingDocument {
/// The title of the collection.
public var title: String?
/// The author of the collection.
public var author: String?
/// The creator of the collection.
public var creator: String?
/// The subject of the collection.
public var subject: String?
/// Keywords describing the collection
public var keywords: String?
/// The owner's password
public var ownerPassword: String?
/// A user password
public var userPassword: String?
/// Can this collection be printed?
public var allowsPrinting: Bool = true
/// Can this collection be copied (copy/pasted)?
public var allowsCopying: Bool = true
/// Internal representation of the various pages of the drawing collection.
public private(set) var pages: [Page]
/// Initializer
public init (title: String? = nil,
author: String? = nil,
creator: String? = nil,
subject: String? = nil,
keywords: String? = nil) {
self.pages = []
self.title = title
self.author = author
self.creator = creator
self.subject = subject
self.keywords = keywords
}
/// Append a new drawing to the collection.
public func append(_ drawing: Drawing,
flipped: Bool = false,
width: Int,
height: Int) {
self.pages.append(Page(drawing: drawing, flipped: flipped, width: width, height: height))
}
/// Save the collection as a PDF file to URL `url`.
public func saveAsPDF(url: URL) -> Bool {
// First check if we can write to the URL
var dir: ObjCBool = false
let parent = url.deletingLastPathComponent().path
guard FileManager.default.fileExists(atPath: parent, isDirectory: &dir) && dir.boolValue else {
return false
}
guard FileManager.default.isWritableFile(atPath: parent) else {
return false
}
// Define PDF document information
let pdfInfo: NSMutableDictionary = [
kCGPDFContextAllowsPrinting: (self.allowsPrinting ? kCFBooleanTrue : kCFBooleanFalse) as Any,
kCGPDFContextAllowsCopying : (self.allowsCopying ? kCFBooleanTrue : kCFBooleanFalse) as Any
]
if let title = self.title {
pdfInfo[kCGPDFContextTitle] = title
}
if let author = self.author {
pdfInfo[kCGPDFContextAuthor] = author
}
if let creator = self.creator {
pdfInfo[kCGPDFContextCreator] = creator
}
if let subject = self.subject {
pdfInfo[kCGPDFContextSubject] = subject
}
if let keywords = self.keywords {
pdfInfo[kCGPDFContextKeywords] = keywords
}
if let password = self.ownerPassword {
pdfInfo[kCGPDFContextOwnerPassword] = password
}
if let password = self.userPassword {
pdfInfo[kCGPDFContextUserPassword] = password
}
// Default media box (will be overwritten on a page by page basis)
var mediaBox = CGRect(x: 0, y: 0, width: Double(200), height: Double(200))
// Create a core graphics context suitable for creating PDF files
guard let cgc = CGContext(url as CFURL, mediaBox: &mediaBox, pdfInfo as CFDictionary) else {
return false
}
#if os(macOS)
let previous = NSGraphicsContext.current
defer {
NSGraphicsContext.current = previous
}
#endif
for page in self.pages {
page.createPDFPage(in: cgc)
}
cgc.closePDF()
return true
}
/// Representation of a page.
public struct Page {
public let drawing: Drawing
public let flipped: Bool
public let width: Int
public let height: Int
fileprivate func createPDFPage(in cgc: CGContext) {
var mediaBox = CGRect(x: 0, y: 0, width: Double(self.width), height: Double(self.height))
let pageInfo: NSDictionary = [
kCGPDFContextMediaBox : NSData(bytes: &mediaBox,
length: MemoryLayout.size(ofValue: mediaBox))
]
// Create a graphics context for drawing into the PDF page
#if os(iOS) || os(watchOS) || os(tvOS)
UIGraphicsPushContext(cgc)
defer {
UIGraphicsPopContext()
}
#elseif os(macOS)
NSGraphicsContext.current = NSGraphicsContext(cgContext: cgc, flipped: self.flipped)
#endif
// Create a new PDF page
cgc.beginPDFPage(pageInfo as CFDictionary)
cgc.saveGState()
// Flip graphics if required
if self.flipped {
cgc.translateBy(x: 0.0, y: CGFloat(self.height))
cgc.scaleBy(x: 1.0, y: -1.0)
}
// Draw the image
self.drawing.draw()
cgc.restoreGState()
// Close PDF page and document
cgc.endPDFPage()
}
}
}
| 456e9e9dc072438b2c40dd98d4f74d72 | 30.662983 | 99 | 0.65486 | false | false | false | false |
robconrad/fledger-ios | refs/heads/master | fledger-ios/ui/AppUITableViewCell.swift | mit | 1 | //
// AppUITableViewCell.swift
// fledger-ios
//
// Created by Robert Conrad on 4/14/15.
// Copyright (c) 2015 TwoSpec Inc. All rights reserved.
//
import UIKit
class AppUITableViewCell: UITableViewCell {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = AppColors.bgMain()
textLabel?.textColor = AppColors.text()
let selectedBgView = UIView()
selectedBgView.backgroundColor = AppColors.bgSelected()
selectedBackgroundView = selectedBgView
}
}
| 8e1292cb49851c72da6ff76782d5b769 | 21.92 | 63 | 0.65096 | false | false | false | false |
mixersoft/cordova-plugin-camera-roll-location | refs/heads/master | src/ios/CameraRollLocation.swift | apache-2.0 | 1 | /*
* Copyright (c) 2016 by Snaphappi, Inc. All rights reserved.
*
* @SNAPHAPPI_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @SNAPHAPPI_LICENSE_HEADER_END@
*/
// import PhotoWithLocationService;
@objc(CameraRollLocation) class CameraRollLocation : CDVPlugin {
// deprecate
@objc(getByMoments:) func getByMoments(command: CDVInvokedUrlCommand) {
return self.getCameraRoll(command: command);
}
@objc(getCameraRoll:) func getCameraRoll(command: CDVInvokedUrlCommand) {
let dateFmt = DateFormatter()
dateFmt.dateFormat = "yyyy-MM-dd"
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
// let options = command.arguments[0] as? String ?? ""
let options : [String:Any] = command.arguments[0] as! [String:Any];
// prepare params
var fromDate : Date? = nil;
var toDate : Date? = nil;
if let from = options["from"] as! NSString? {
fromDate = dateFmt.date(from: from.substring(to: 10))
print("FROM: \( from.substring(to: 10) ) => \(fromDate)")
}
if let to = options["to"] as! NSString? {
toDate = dateFmt.date(from: to.substring(to: 10))
print("TO: \( to.substring(to: 10) ) => \(toDate)")
}
// get result from CameraRoll
let cameraRoll = PhotoWithLocationService()
var data : [NSData] = []
// runInBackground
self.commandDelegate!.run(inBackground: {
let result = cameraRoll.getByMoments(from:fromDate, to:toDate);
if result.count > 0 {
// toJSON()
var asJson = ""
for o in result {
if !asJson.isEmpty {
asJson += ", "
}
asJson += "\(o.toJson())"
// data.append( NSKeyedArchiver.archivedDataWithRootObject(o) )
}
asJson = "[\(asJson)]"
pluginResult = CDVPluginResult(
status: CDVCommandStatus_OK,
messageAs: asJson
)
} else if result.count == 0 {
pluginResult = CDVPluginResult(
status: CDVCommandStatus_OK,
messageAs: "[]"
)
}
// let aDict = [result[0].uuid:result[0]]
// pluginResult = CDVPluginResult(
// status: CDVCommandStatus_OK
//// , messageAsArray: result // <NSInvalidArgumentException> Invalid type in JSON write (mappi1.CameraRollPhoto)
//// , messageAsArray: data // <NSInvalidArgumentException> Invalid type in JSON write (NSConcreteMutableData)
//// , messageAsDictionary: aDict // Invalid type in JSON write (mappi1.CameraRollPhoto)
//// , messageAsMultipart: data // returns ArrayBuffer to JS - then what?
// )
// send result in Background
self.commandDelegate!.send(
pluginResult,
callbackId: command.callbackId
)
})
}
// experimental
@objc(getImage:) func getImage(command: CDVInvokedUrlCommand) {
let uuids : [String] = command.arguments[0] as! [String];
let options : [String:Any] = command.arguments[1] as! [String:Any];
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
let cameraRoll = PhotoWithLocationService()
// runInBackground
self.commandDelegate!.run(inBackground: {
let result = cameraRoll.getImage(localIds:uuids, options:options)
// var resultStr: String
// do {
// let jsonData = try JSONSerialization.data(withJSONObject: result)
// resultStr = String(data: jsonData, encoding: .utf8)!
// } catch {
// resultStr = "error:JSONSerialization()"
// }
pluginResult = CDVPluginResult(
status: CDVCommandStatus_OK,
messageAs: result
)
self.commandDelegate!.send(
pluginResult,
callbackId: command.callbackId
)
})
}
}
| 51b90e6df34e3ee0e060141e24717f0a | 33.057143 | 128 | 0.618289 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.