repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
koher/EasyImagy | Sources/EasyImagy/Util.swift | 1 | 970 | internal func clamp<T: Comparable>(_ x: T, lower: T, upper: T) -> T {
return min(max(x, lower), upper)
}
extension Range {
internal func isSuperset(of other: Range<Bound>) -> Bool {
return lowerBound <= other.lowerBound && other.upperBound <= upperBound || other.isEmpty
}
}
internal func range<R: RangeExpression>(from range: R, relativeTo collection: Range<Int>) -> Range<Int> where R.Bound == Int {
let all = Int.min ..< Int.max
let boundedRange: Range<Int> = range.relative(to: all)
let lowerBound: Int
let upperBound: Int
if boundedRange.lowerBound == .min {
lowerBound = Swift.max(boundedRange.lowerBound, collection.lowerBound)
} else {
lowerBound = boundedRange.lowerBound
}
if boundedRange.upperBound == .max {
upperBound = Swift.min(collection.upperBound, boundedRange.upperBound)
} else {
upperBound = boundedRange.upperBound
}
return lowerBound..<upperBound
}
| mit |
brentsimmons/Evergreen | Shared/Exporters/OPMLExporter.swift | 1 | 755 | //
// OPMLExporter.swift
// NetNewsWire
//
// Created by Brent Simmons on 12/22/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import Account
import RSCore
struct OPMLExporter {
static func OPMLString(with account: Account, title: String) -> String {
let escapedTitle = title.escapingSpecialXMLCharacters
let openingText =
"""
<?xml version="1.0" encoding="UTF-8"?>
<!-- OPML generated by NetNewsWire -->
<opml version="1.1">
<head>
<title>\(escapedTitle)</title>
</head>
<body>
"""
let middleText = account.OPMLString(indentLevel: 0)
let closingText =
"""
</body>
</opml>
"""
let opml = openingText + middleText + closingText
return opml
}
}
| mit |
Mayfleet/SimpleChat | Frontend/iOS/SimpleChat/SimpleChat/Screens/ChatList/ChatCell.swift | 1 | 5340 | //
// Created by Maxim Pervushin on 05/03/16.
// Copyright (c) 2016 Maxim Pervushin. All rights reserved.
//
import UIKit
protocol ChatCellDelegate: class {
func chatCellDidDelete(cell: ChatCell)
func chatCellDidEdit(cell: ChatCell)
func chatCellDidToggleAutoconnect(cell: ChatCell)
}
class ChatCell: UITableViewCell {
static let defaultReuseIdentifier = "ChatCell"
@IBOutlet weak var serverNameLabel: UILabel?
@IBOutlet weak var serverNotificationsLabel: UILabel?
@IBOutlet weak var leadingConstraint: NSLayoutConstraint?
@IBOutlet weak var editorContainer: UIView?
@IBOutlet weak var autoconnectButton: UIButton?
@IBOutlet weak var editButton: UIButton?
@IBOutlet weak var deleteButton: UIButton?
@IBAction func autoconnectButtonAction(sender: AnyObject) {
delegate?.chatCellDidToggleAutoconnect(self)
}
@IBAction func editButtonAction(sender: AnyObject) {
delegate?.chatCellDidEdit(self)
}
@IBAction func deleteButtonAction(sender: AnyObject) {
delegate?.chatCellDidDelete(self)
}
@objc func swipeLeftAction(sender: AnyObject) {
if !editing {
setEditing(true, animated: true)
}
}
@objc func swipeRightAction(sender: AnyObject) {
if editing {
setEditing(false, animated: true)
}
}
weak var delegate: ChatCellDelegate?
var chat: Chat? {
didSet {
serverNameLabel?.text = chat?.name
var autoconnectTitle = NSLocalizedString("Autoconnect: Off", comment: "Autoconnect Button Title: Off")
var autoconnectBackgroundColor = UIColor.flatYellowColorDark()
if let chat = chat where chat.autoconnect {
autoconnectTitle = NSLocalizedString("Autoconnect: On", comment: "Autoconnect Button Title: On")
autoconnectBackgroundColor = UIColor.flatGreenColorDark()
}
autoconnectButton?.setTitle(autoconnectTitle, forState: .Normal)
autoconnectButton?.backgroundColor = autoconnectBackgroundColor
subscribe()
}
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if let
leadingConstraint = leadingConstraint,
editorContainer = editorContainer {
layoutIfNeeded()
leadingConstraint.constant = editing ? -editorContainer.frame.size.width : 4
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: [.CurveEaseInOut], animations: {
() -> Void in
self.layoutIfNeeded()
}, completion: nil)
}
}
private func subscribe() {
unsubscribe()
if let chat = chat {
let center = NSNotificationCenter.defaultCenter()
center.addObserverForName(Chat.statusChangedNotification, object: chat, queue: nil, usingBlock: chatStatusChangedNotification)
center.addObserverForName(Chat.messagesChangedNotification, object: chat, queue: nil, usingBlock: chatMessagesChangedNotification)
}
updateUI()
}
private func unsubscribe() {
let center = NSNotificationCenter.defaultCenter()
center.removeObserver(self, name: Chat.statusChangedNotification, object: nil)
center.removeObserver(self, name: Chat.messagesChangedNotification, object: nil)
}
private func updateUI() {
guard let chat = chat else {
serverNotificationsLabel?.hidden = true
return
}
serverNotificationsLabel?.hidden = false
serverNotificationsLabel?.text = chat.messages.count > 0 ? "\(chat.messages.count)" : ""
switch chat.status {
case Chat.Status.Online:
serverNotificationsLabel?.backgroundColor = UIColor.flatGreenColorDark()
break
case Chat.Status.Offline:
serverNotificationsLabel?.backgroundColor = UIColor.flatRedColorDark()
break
}
editButton?.backgroundColor = UIColor.flatSkyBlueColorDark()
deleteButton?.backgroundColor = UIColor.flatRedColorDark()
}
private func commonInit() {
let leftSwipeRecognizer = UISwipeGestureRecognizer(target: self, action: "swipeLeftAction:")
leftSwipeRecognizer.numberOfTouchesRequired = 1
leftSwipeRecognizer.direction = .Left
addGestureRecognizer(leftSwipeRecognizer)
let rightSwipeRecognizer = UISwipeGestureRecognizer(target: self, action: "swipeRightAction:")
rightSwipeRecognizer.numberOfTouchesRequired = 1
rightSwipeRecognizer.direction = .Right
addGestureRecognizer(rightSwipeRecognizer)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
deinit {
unsubscribe()
}
}
extension ChatCell {
private func chatStatusChangedNotification(notification: NSNotification) {
updateUI()
}
private func chatMessagesChangedNotification(notification: NSNotification) {
updateUI()
}
} | mit |
remlostime/one | one/one/ViewControllers/FeedViewController.swift | 1 | 3464 | //
// FeedViewController.swift
// one
//
// Created by Kai Chen on 1/20/17.
// Copyright © 2017 Kai Chen. All rights reserved.
//
import UIKit
import Parse
class FeedViewController: UITableViewController {
var postUUIDs: [String?] = []
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "One"
loadPosts()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.titleTextAttributes =
[NSFontAttributeName: UIFont(name: "Vonique64-Bold", size: 26)!]
}
func loadPosts() {
let userid = PFUser.current()?.username
let query = PFQuery(className: Follow.modelName.rawValue)
query.whereKey(Follow.follower.rawValue, equalTo: userid!)
var following: [String?] = []
query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
for object in objects! {
following.append(object[Follow.following.rawValue] as! String?)
}
let postQuery = PFQuery(className: Post.modelName.rawValue)
postQuery.whereKey(Post.username.rawValue, containedIn: following)
postQuery.order(byDescending: "createdAt")
postQuery.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
for object in objects! {
self.postUUIDs.append(object[Post.uuid.rawValue] as! String?)
}
self.tableView.reloadData()
}
}
}
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postUUIDs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.postHeaderViewCell.rawValue, for: indexPath) as? PostHeaderViewCell
cell?.delegate = self
let uuid = postUUIDs[indexPath.row]
cell?.config(uuid!)
return cell!
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 600
}
}
extension FeedViewController: PostHeaderViewCellDelegate {
func navigateToUserPage(_ username: String?) {
guard let username = username else {
return
}
let homeVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.profileViewController.rawValue) as? ProfileViewController
homeVC?.userid = username
self.navigationController?.pushViewController(homeVC!, animated: true)
}
func showActionSheet(_ alertController: UIAlertController?) {
self.present(alertController!, animated: true, completion: nil)
}
func navigateToPostPage(_ uuid: String?) {
guard let uuid = uuid else {
return
}
let dstVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.commentViewController.rawValue) as? CommentViewController
dstVC?.hidesBottomBarWhenPushed = true
dstVC?.postUUID = uuid
self.navigationController?.pushViewController(dstVC!, animated: true)
}
}
| gpl-3.0 |
kormic/Rocket.Chat.iOS | Rocket.Chat.iOSUITests/Rocket_Chat_iOSUITests.swift | 2 | 1077 | //
// Rocket_Chat_iOSUITests.swift
// Rocket.Chat.iOSUITests
//
// Created by giorgos on 8/4/15.
// Copyright © 2015 Rocket.Chat. All rights reserved.
//
import XCTest
class Rocket_Chat_iOSUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
JakeLin/IBAnimatable | IBAnimatable.playground/Pages/Chaining Animations.xcplaygroundpage/Contents.swift | 2 | 831 | //: [Previous](@previous)
//: ## Chaining Animations
import UIKit
import PlaygroundSupport
import IBAnimatable
//: Set up the iPhone View
let iPhoneView = PhoneView()
PlaygroundPage.current.liveView = iPhoneView
//: Set up the animatable View
let view = CircleView()
iPhoneView.addSubview(view)
////: Chain your animations
view.animate(.squeezeFade(way: .in, direction: .down))
.then(.pop(repeatCount: 1))
.then(.shake(repeatCount: 1))
.then(.squeeze(way: .in, direction: .down))
.then(.wobble(repeatCount: 1))
.then(.flip(along: .x))
.then(.flip(along: .y))
.then(.slideFade(way: .out, direction: .down))
//: To apply delay, we can specify the delay before doing specifying the animationType
view.animate(.pop(repeatCount: 1))
.delay(0.3)
.then(.shake(repeatCount: 1))
//: [Next](@next)
| mit |
zvonler/PasswordElephant | external/github.com/apple/swift-protobuf/Sources/SwiftProtobuf/BinaryEncodingSizeVisitor.swift | 7 | 15208 | // Sources/SwiftProtobuf/BinaryEncodingSizeVisitor.swift - Binary size calculation support
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Visitor used during binary encoding that precalcuates the size of a
/// serialized message.
///
// -----------------------------------------------------------------------------
import Foundation
/// Visitor that calculates the binary-encoded size of a message so that a
/// properly sized `Data` or `UInt8` array can be pre-allocated before
/// serialization.
internal struct BinaryEncodingSizeVisitor: Visitor {
/// Accumulates the required size of the message during traversal.
var serializedSize: Int = 0
init() {}
mutating func visitUnknown(bytes: Data) throws {
serializedSize += bytes.count
}
mutating func visitSingularFloatField(value: Float, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize
serializedSize += tagSize + MemoryLayout<Float>.size
}
mutating func visitSingularDoubleField(value: Double, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize
serializedSize += tagSize + MemoryLayout<Double>.size
}
mutating func visitSingularInt32Field(value: Int32, fieldNumber: Int) throws {
try visitSingularInt64Field(value: Int64(value), fieldNumber: fieldNumber)
}
mutating func visitSingularInt64Field(value: Int64, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize
serializedSize += tagSize + Varint.encodedSize(of: value)
}
mutating func visitSingularUInt32Field(value: UInt32, fieldNumber: Int) throws {
try visitSingularUInt64Field(value: UInt64(value), fieldNumber: fieldNumber)
}
mutating func visitSingularUInt64Field(value: UInt64, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize
serializedSize += tagSize + Varint.encodedSize(of: value)
}
mutating func visitSingularSInt32Field(value: Int32, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize
serializedSize += tagSize + Varint.encodedSize(of: ZigZag.encoded(value))
}
mutating func visitSingularSInt64Field(value: Int64, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize
serializedSize += tagSize + Varint.encodedSize(of: ZigZag.encoded(value))
}
mutating func visitSingularFixed32Field(value: UInt32, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize
serializedSize += tagSize + MemoryLayout<UInt32>.size
}
mutating func visitSingularFixed64Field(value: UInt64, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize
serializedSize += tagSize + MemoryLayout<UInt64>.size
}
mutating func visitSingularSFixed32Field(value: Int32, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize
serializedSize += tagSize + MemoryLayout<Int32>.size
}
mutating func visitSingularSFixed64Field(value: Int64, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize
serializedSize += tagSize + MemoryLayout<Int64>.size
}
mutating func visitSingularBoolField(value: Bool, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize
serializedSize += tagSize + 1
}
mutating func visitSingularStringField(value: String, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let count = value.utf8.count
serializedSize += tagSize + Varint.encodedSize(of: Int64(count)) + count
}
mutating func visitSingularBytesField(value: Data, fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let count = value.count
serializedSize += tagSize + Varint.encodedSize(of: Int64(count)) + count
}
mutating func visitPackedFloatField(value: [Float], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<Float>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedDoubleField(value: [Double], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<Double>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedInt32Field(value: [Int32], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: v)
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedInt64Field(value: [Int64], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: v)
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedSInt32Field(value: [Int32], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: ZigZag.encoded(v))
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedSInt64Field(value: [Int64], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: ZigZag.encoded(v))
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedUInt32Field(value: [UInt32], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: v)
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedUInt64Field(value: [UInt64], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: v)
}
serializedSize +=
tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedFixed32Field(value: [UInt32], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<UInt32>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedFixed64Field(value: [UInt64], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<UInt64>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedSFixed32Field(value: [Int32], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<Int32>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedSFixed64Field(value: [Int64], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count * MemoryLayout<Int64>.size
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitPackedBoolField(value: [Bool], fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize
let dataSize = value.count
serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitSingularEnumField<E: Enum>(value: E,
fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .varint).encodedSize
serializedSize += tagSize
let dataSize = Varint.encodedSize(of: Int32(truncatingIfNeeded: value.rawValue))
serializedSize += dataSize
}
mutating func visitRepeatedEnumField<E: Enum>(value: [E],
fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .varint).encodedSize
serializedSize += value.count * tagSize
for v in value {
let dataSize = Varint.encodedSize(of: Int32(truncatingIfNeeded: v.rawValue))
serializedSize += dataSize
}
}
mutating func visitPackedEnumField<E: Enum>(value: [E],
fieldNumber: Int) throws {
guard !value.isEmpty else {
return
}
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .varint).encodedSize
serializedSize += tagSize
var dataSize = 0
for v in value {
dataSize += Varint.encodedSize(of: Int32(truncatingIfNeeded: v.rawValue))
}
serializedSize += Varint.encodedSize(of: Int64(dataSize)) + dataSize
}
mutating func visitSingularMessageField<M: Message>(value: M,
fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .lengthDelimited).encodedSize
let messageSize = try value.serializedDataSize()
serializedSize +=
tagSize + Varint.encodedSize(of: UInt64(messageSize)) + messageSize
}
mutating func visitRepeatedMessageField<M: Message>(value: [M],
fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .lengthDelimited).encodedSize
serializedSize += value.count * tagSize
for v in value {
let messageSize = try v.serializedDataSize()
serializedSize +=
Varint.encodedSize(of: UInt64(messageSize)) + messageSize
}
}
mutating func visitSingularGroupField<G: Message>(value: G, fieldNumber: Int) throws {
// The wire format doesn't matter here because the encoded size of the
// integer won't change based on the low three bits.
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .startGroup).encodedSize
serializedSize += 2 * tagSize
try value.traverse(visitor: &self)
}
mutating func visitRepeatedGroupField<G: Message>(value: [G],
fieldNumber: Int) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .startGroup).encodedSize
serializedSize += 2 * value.count * tagSize
for v in value {
try v.traverse(visitor: &self)
}
}
mutating func visitMapField<KeyType, ValueType: MapValueType>(
fieldType: _ProtobufMap<KeyType, ValueType>.Type,
value: _ProtobufMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .lengthDelimited).encodedSize
for (k,v) in value {
var sizer = BinaryEncodingSizeVisitor()
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer)
try ValueType.visitSingular(value: v, fieldNumber: 2, with: &sizer)
let entrySize = sizer.serializedSize
serializedSize += Varint.encodedSize(of: Int64(entrySize)) + entrySize
}
serializedSize += value.count * tagSize
}
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type,
value: _ProtobufEnumMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws where ValueType.RawValue == Int {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .lengthDelimited).encodedSize
for (k,v) in value {
var sizer = BinaryEncodingSizeVisitor()
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer)
try sizer.visitSingularEnumField(value: v, fieldNumber: 2)
let entrySize = sizer.serializedSize
serializedSize += Varint.encodedSize(of: Int64(entrySize)) + entrySize
}
serializedSize += value.count * tagSize
}
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type,
value: _ProtobufMessageMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws {
let tagSize = FieldTag(fieldNumber: fieldNumber,
wireFormat: .lengthDelimited).encodedSize
for (k,v) in value {
var sizer = BinaryEncodingSizeVisitor()
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer)
try sizer.visitSingularMessageField(value: v, fieldNumber: 2)
let entrySize = sizer.serializedSize
serializedSize += Varint.encodedSize(of: Int64(entrySize)) + entrySize
}
serializedSize += value.count * tagSize
}
mutating func visitExtensionFieldsAsMessageSet(
fields: ExtensionFieldValueSet,
start: Int,
end: Int
) throws {
var sizer = BinaryEncodingMessageSetSizeVisitor()
try fields.traverse(visitor: &sizer, start: start, end: end)
serializedSize += sizer.serializedSize
}
}
internal extension BinaryEncodingSizeVisitor {
// Helper Visitor to compute the sizes when writing out the extensions as MessageSets.
internal struct BinaryEncodingMessageSetSizeVisitor: SelectiveVisitor {
var serializedSize: Int = 0
init() {}
mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) throws {
var groupSize = WireFormat.MessageSet.itemTagsEncodedSize
groupSize += Varint.encodedSize(of: Int32(fieldNumber))
let messageSize = try value.serializedDataSize()
groupSize += Varint.encodedSize(of: UInt64(messageSize)) + messageSize
serializedSize += groupSize
}
// SelectiveVisitor handles the rest.
}
}
| gpl-3.0 |
kylecrawshaw/ImagrAdmin | ImagrAdmin/WorkflowSupport/WorkflowComponents/LocalizationComponent/LocalizationComponent.swift | 1 | 2448 | //
// ImageComponent.swift
// ImagrManager
//
// Created by Kyle Crawshaw on 7/12/16.
// Copyright © 2016 Kyle Crawshaw. All rights reserved.
//
import Foundation
import Cocoa
class LocalizationComponent: BaseComponent {
var keyboardLayoutName: String?
var keyboardLayoutId: String?
var countryCode: String?
var language: String?
var timezone: String?
// var locale: String?
init(id: Int!, workflowName: String!, workflowId: Int!) {
super.init(id: id, type: "localize", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = LocalizationComponentViewController()
}
init(id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) {
super.init(id: id, type: "localize", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = LocalizationComponentViewController()
self.keyboardLayoutName = dict.valueForKey("keyboard_layout_name") as? String
self.keyboardLayoutId = dict.valueForKey("keyboard_layout_id") as? String
self.timezone = dict.valueForKey("timezone") as? String
self.language = dict.valueForKey("language") as? String
if let locale = dict.valueForKey("locale") as? String {
let localeComponents = locale.characters.split{$0 == "_"}.map(String.init)
if localeComponents.count == 1 {
self.countryCode = localeComponents[0]
} else if localeComponents.count == 2 {
self.countryCode = localeComponents[1]
}
}
}
override func asDict() -> NSDictionary? {
var dict: [String: AnyObject] = [
"type": type,
]
if (keyboardLayoutName != nil) && (keyboardLayoutName != "") {
dict["keyboard_layout_name"] = keyboardLayoutName!
}
if (keyboardLayoutId != nil) && (keyboardLayoutId != "" ){
dict["keyboard_layout_id"] = Int(keyboardLayoutId!)
}
if (language != nil) && (language! != "") {
dict["language"] = language!
}
if (countryCode != nil && countryCode! != "" && language != nil) {
dict["locale"] = "\(language!)_\(countryCode!)"
}
if (timezone != nil) && (timezone != "") {
dict["timezone"] = timezone!
}
return dict
}
} | apache-2.0 |
nickbryanmiller/UniqueAccessibilityIdentifiers | Unique AccessID iOS/Unique AccessID iOS/AIDExtension.swift | 2 | 15277 | // Please Leave This Header In This File
//
// File Name: AIDExtension.swift
//
// Description:
// Creating Unique Accessibility Identifiers of every object at Runtime
//
// This is big for Native Automated Testing in conjunction with the XCTest Framework
// If you call this file the test recording software no longer has to grab the relative identifier because it
// can grab the absolute identifier making the test cases less difficult to write
//
// Developers:
// Nicholas Bryan Miller (GitHub: https://github.com/nickbryanmiller )
// Justin Rose (GitHub: https://github.com/justinjaster )
//
// Created by Nicholas Miller on 7/21/16
// Copyright © 2016 Nicholas Miller. All rights reserved.
// This code is under the Apache 2.0 License.
//
// Use:
// In the viewDidLayoutSubviews() method in each ViewController put "self.setEachIDInViewController()"
// In the viewWillDisappear() method in each ViewController put "self.removeEachIDInViewController()"
// and this file will do the rest for you
//
// Tools:
// We make use of class extensions, mirroring, and the built in view hierarchy
//
// Note:
// If you see an issue anywhere please open a merge request and we will get to it as soon as possible.
// If you would like to make an improvement anywhere open a merge request.
// If you liked anything or are curious about anything reach out to one of us.
// We like trying to improve the iOS Community :)
// If you or your company decides to take it and implement it we would LOVE to know that please!!
//
import Foundation
import UIKit
extension Array where Element: Equatable {
mutating func removeObject(object: Element) {
if let index = self.indexOf(object) {
self.removeAtIndex(index)
}
}
mutating func removeEveryObjectInArray(array: [Element]) {
for object in array {
self.removeObject(object)
}
}
mutating func removeAllOfAnObjectInArray(array: [Element], object: Element) {
for element in array {
if element == object {
self.removeObject(object)
}
}
}
}
extension String {
func removeSpaces() -> String {
let noSpaceString = self.characters.split{$0 == " "}.map{String($0)}.joinWithSeparator("")
return noSpaceString
}
func splitBy(splitter: Character) -> [String] {
let splitArray = self.characters.split{$0 == splitter}.map(String.init)
return splitArray
}
}
extension UIViewController {
// This could be a dictionary where the key is the ViewControllerName
private struct AssociatedKeys {
static var existingIDArray: [String] = []
}
func removeEachIDInViewController() {
removeEachIDForViewControllerAndView(self.view)
}
func setEachIDInViewController() {
setEachIDForViewControllerAndView(self.view)
}
private func removeEachIDForViewControllerAndView(view: UIView) {
for element in view.subviews {
if let aID = element.accessibilityIdentifier {
if aID.containsString("NJAid") {
AssociatedKeys.existingIDArray.removeObject(aID)
element.accessibilityIdentifier = nil
}
}
if element.subviews.count > 0 {
removeEachIDForViewControllerAndView(element)
}
}
}
private func setEachIDForViewControllerAndView(view: UIView) {
for element in view.subviews {
// We want to mark these with identifiers and go down their view hierarchy
if element is UITableViewCell || element is UICollectionViewCell || element is UIScrollView || element is UITableView || element is UICollectionView {
setAndCheckID(element)
}
// essentials
if element is UITextField || element is UITextView || element is UIButton || element is UISwitch || element is UISegmentedControl || element is UIWebView {
setAndCheckID(element)
}
// throw aways
else if element is UILabel || element is UIImageView || element is UINavigationBar || element is UITabBar {
}
// recursive down the view hierarchy
else if element.subviews.count > 0 {
setEachIDForViewControllerAndView(element)
}
}
}
private func setAndCheckID(element: UIView) {
if element.accessibilityIdentifier != nil && element.accessibilityIdentifier != "" {
return
}
else {
if element is UIScrollView {
element.setID(self, pageType: "Dynamic")
}
else {
element.setID(self, pageType: "Static")
}
var idString = element.getID()
let count = getDuplicateCount(idString)
if count > 0 {
idString = idString + ", Count: \(count)"
}
let finalID = "<" + idString + ">"
element.setCustomID(finalID)
AssociatedKeys.existingIDArray.append(finalID)
}
}
func getDuplicateCount(idString: String) -> Int {
var testIDString = idString
var duplicateCount = 0
if !AssociatedKeys.existingIDArray.contains("<" + testIDString + ">") {
return 0
}
else {
// This is to make sure that we do not have a duplicate. If we do it appends a number to it
// This number is increasing based on the order it was added to the xml
while AssociatedKeys.existingIDArray.contains("<" + testIDString + ">") {
testIDString = idString
duplicateCount = duplicateCount + 1
testIDString = testIDString + ", Count: \(duplicateCount)"
}
return duplicateCount
}
}
// This method is for developers to set a custom ID
// At the viewcontroller level is ideal because we can check for a duplicate
func setIDForElement(element: UIView, aID: String) {
if AssociatedKeys.existingIDArray.contains(aID) {
print("It already exists in the application")
}
else {
element.setCustomID(aID)
}
}
func getExisitingIDArray() -> [String] {
return AssociatedKeys.existingIDArray
}
func printEachID() {
for element in AssociatedKeys.existingIDArray {
print(element)
}
}
func printOutlets() {
let vcMirror = Mirror(reflecting: self)
for child in vcMirror.children {
print(child)
print(child.label)
}
}
}
extension UIView {
func setCustomID(aID: String) {
self.accessibilityIdentifier = aID
}
func getID() -> String {
if let aID = self.accessibilityIdentifier {
return aID
}
else {
return ""
}
}
private func setID(vc: UIViewController, pageType: String) {
let vcMirror = Mirror(reflecting: vc)
var id: String = "NJAid"
// let className = NSStringFromClass(vc.classForCoder).splitBy(".")[1]
let className = "\(vcMirror.subjectType)"
let grandParentOutletName = getGrandParentOutletName(vcMirror)
let parentOutletName = getParentOutletName(vcMirror)
let selfOutletName = getSelfOutletName(vcMirror)
let positionInParent = getPositionInParentView()
let title = getTitle()
let type = getType()
if className != "" {
id = id + ", ClassName: " + className
}
if grandParentOutletName != "" {
id = id + ", GPOutlet: " + grandParentOutletName
}
if parentOutletName != "" {
id = id + ", POutlet: " + parentOutletName
}
if selfOutletName != "" {
id = id + ", SelfOutlet: " + selfOutletName
}
if pageType == "Static" {
if positionInParent != "" {
id = id + ", PositionInParent: " + positionInParent
}
}
if title != "" {
id = id + ", Title: " + title
}
if type != "" {
id = id + ", Type: " + type
}
self.accessibilityIdentifier = id
}
func getGrandParentOutletName(vcMirror: Mirror) -> String {
var memoryID = ""
let selfString = "\(self.superview?.superview)"
if let firstColon = selfString.characters.indexOf(":") {
let twoAfterFirstColon = firstColon.advancedBy(2)
let beyondType = selfString.substringFromIndex(twoAfterFirstColon)
if let firstSemicolon = beyondType.characters.indexOf(";") {
memoryID = beyondType.substringToIndex(firstSemicolon)
}
}
for child in vcMirror.children {
if memoryID != "" && "\(child.value)".containsString(memoryID) {
if let childLabel = child.label {
return childLabel
}
}
}
return ""
}
func getParentOutletName(vcMirror: Mirror) -> String {
var memoryID = ""
let selfString = "\(self.superview)"
if let firstColon = selfString.characters.indexOf(":") {
let twoAfterFirstColon = firstColon.advancedBy(2)
let beyondType = selfString.substringFromIndex(twoAfterFirstColon)
if let firstSemicolon = beyondType.characters.indexOf(";") {
memoryID = beyondType.substringToIndex(firstSemicolon)
}
}
for child in vcMirror.children {
if memoryID != "" && "\(child.value)".containsString(memoryID) {
if let childLabel = child.label {
return childLabel
}
}
}
return ""
}
func getSelfOutletName(vcMirror: Mirror) -> String {
var memoryID = ""
let selfString = "\(self)"
if let firstColon = selfString.characters.indexOf(":") {
let twoAfterFirstColon = firstColon.advancedBy(2)
let beyondType = selfString.substringFromIndex(twoAfterFirstColon)
if let firstSemicolon = beyondType.characters.indexOf(";") {
memoryID = beyondType.substringToIndex(firstSemicolon)
}
}
for child in vcMirror.children {
if memoryID != "" && "\(child.value)".containsString(memoryID) {
if let childLabel = child.label {
return childLabel
}
}
}
return ""
}
private func getTitle() -> String {
var title: String = ""
if let myButton = self as? UIButton {
if let buttonTitle = myButton.currentTitle {
title = buttonTitle.removeSpaces()
}
}
else if let myLabel = self as? UILabel {
if let labelTitle = myLabel.text {
title = labelTitle.removeSpaces()
}
}
else if let myTextField = self as? UITextField {
if let textFieldTitle = myTextField.placeholder {
title = textFieldTitle.removeSpaces()
}
}
else if let myNavigationBar = self as? UINavigationBar {
if let navigationBarTitle = myNavigationBar.topItem?.title {
title = navigationBarTitle.removeSpaces()
}
}
return title
}
func getType() -> String {
var elementType: String = ""
switch self {
case is UIButton:
elementType = "UIButton"
case is UILabel:
elementType = "UILabel"
case is UIImageView:
elementType = "UIImageView"
case is UITextView:
elementType = "UITextView"
case is UITextField:
elementType = "UITextField"
case is UISegmentedControl:
elementType = "UISegmentedControl"
case is UISwitch:
elementType = "UISwitch"
case is UINavigationBar:
elementType = "UINavigationBar"
case is UITabBar:
elementType = "UITabBar"
case is UIWebView:
elementType = "UIWebView"
case is UITableViewCell:
elementType = "UITableViewCell"
case is UICollectionViewCell:
elementType = "UICollectionViewCell"
case is UITableView:
elementType = "UITableView"
case is UICollectionView:
elementType = "UICollectionView"
default:
elementType = "UIView"
}
return elementType
}
private func getPositionInParentView() -> String {
var positionInParent: String = ""
if let parentView = self.superview {
let parentViewHeightDividedByThree = parentView.bounds.height / 3
let parentViewWidthDividedByThree = parentView.bounds.width / 3
let subviewCenterX = self.center.x
let subviewCenterY = self.center.y
if subviewCenterY <= parentViewHeightDividedByThree {
if subviewCenterX <= parentViewWidthDividedByThree {
positionInParent = "TopLeft"
}
else if subviewCenterX > parentViewWidthDividedByThree && subviewCenterX < parentViewWidthDividedByThree * 2 {
positionInParent = "TopMiddle"
}
else if subviewCenterX >= parentViewWidthDividedByThree * 2 {
positionInParent = "TopRight"
}
}
else if subviewCenterY > parentViewHeightDividedByThree && subviewCenterY < parentViewHeightDividedByThree * 2 {
if subviewCenterX <= parentViewWidthDividedByThree {
positionInParent = "MiddleLeft"
}
else if subviewCenterX > parentViewWidthDividedByThree && subviewCenterX < parentViewWidthDividedByThree * 2 {
positionInParent = "MiddleMiddle"
}
else if subviewCenterX >= parentViewWidthDividedByThree * 2 {
positionInParent = "MiddleRight"
}
}
else if subviewCenterY >= parentViewHeightDividedByThree * 2 {
if subviewCenterX <= parentViewWidthDividedByThree {
positionInParent = "BottomLeft"
}
else if subviewCenterX > parentViewWidthDividedByThree && subviewCenterX < parentViewWidthDividedByThree * 2 {
positionInParent = "BottomMiddle"
}
else if subviewCenterX >= parentViewWidthDividedByThree * 2 {
positionInParent = "BottomRight"
}
}
}
return positionInParent
}
}
| apache-2.0 |
keyOfVv/KEYUI | KEYUI/sources/KEYButton/KEYButton.swift | 1 | 8706 | //
// KEYButton.swift
// KEYButton
//
// Created by Ke Yang on 4/20/16.
// Copyright © 2016 com.sangebaba. All rights reserved.
//
/*
* 功能:
* - 可自定义图片与标题的相对位置, 包括左右对调和上下排列.
*
*/
import UIKit
@objc public enum LayoutType: Int {
case normal
case leftTitleRightImage
case topTitleBottomImage
case topImageBottomTitle
}
open class KEYButton: UIButton {
// MARK: stored property
/// size of title
fileprivate var ttlF = CGRect.zero
/// size of image
fileprivate var imgF = CGRect.zero
/// layout type
open var layoutType = LayoutType.normal {
didSet { self.setNeedsLayout() }
}
/// border line width
open var borderWidth = 0.0 {
didSet {
self.setNeedsDisplay()
}
}
/// border line color
open var borderColor = UIColor.black {
didSet { self.setNeedsDisplay() }
}
/// fill color
open var fillColor = UIColor.clear {
didSet { self.setNeedsDisplay() }
}
/// rounding corners
open var roundingCorners: UIRectCorner = UIRectCorner.allCorners {
didSet { self.setNeedsDisplay() }
}
// MARK: computed property
/// animation images
open var animationImages: [UIImage]? {
set {
self.setImage(newValue?.first, for: UIControlState())
self.imageView?.animationImages = newValue
}
get {
return self.imageView?.animationImages
}
}
/// animation duration
open var animationDuration: TimeInterval {
set {
self.imageView?.animationDuration = newValue
}
get {
return self.imageView?.animationDuration ?? 0
}
}
/// animation repeat count
open var animationRepeatCount: Int {
set {
self.imageView?.animationRepeatCount = newValue
}
get {
return self.imageView?.animationRepeatCount ?? 0
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public convenience init(layoutType: LayoutType) {
self.init(frame: CGRect.zero)
self.layoutType = layoutType
}
open override func layoutSubviews() {
super.layoutSubviews()
// 1. cal image bounds
if let img = self.currentImage {
imgF = CGRect(x: 0.0, y: 0.0, width: img.size.width, height: img.size.height)
}
// 2. cal title bounds
if let ttl = self.currentTitle, let font = self.titleLabel?.font {
ttlF = (ttl as NSString).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil)
}
// 3. layout subviews
switch layoutType {
// 3.1
case .leftTitleRightImage: // w = 120, h = 60
// 3.1.1 cal title frame
// default horizontal margin of title
let hTtlMrgDef = max((frame.width - imgF.width - ttlF.width) * 0.5, 0.0)
// default vertical margin of title
let vTtlMrgDef = max((frame.height - ttlF.height) * 0.5, 0.0)
// ttlX/Y/W/H
let ttlX = contentEdgeInsets.left + titleEdgeInsets.left + hTtlMrgDef
let ttlY = contentEdgeInsets.top + titleEdgeInsets.top + vTtlMrgDef
let ttlW = max(min(frame.width - ttlX - contentEdgeInsets.right - titleEdgeInsets.right, ttlF.width), 0.0)
let ttlH = max(min(frame.height - ttlY - contentEdgeInsets.bottom - titleEdgeInsets.bottom, ttlF.height), 0.0)
let newTtlF = CGRect(x: ttlX, y: ttlY, width: ttlW, height: ttlH)
// 3.1.2 cal image frame
// default vertical margin of image
let vImgMrgDef = (frame.height - imgF.height) * 0.5
// imgX/Y/W/H
let imgX = contentEdgeInsets.left + imageEdgeInsets.left + hTtlMrgDef + ttlF.width
let imgY = contentEdgeInsets.top + imageEdgeInsets.top + vImgMrgDef
let imgW = max(min(frame.width - imgX - contentEdgeInsets.right - imageEdgeInsets.right, imgF.width), 0.0)
let imgH = max(min(frame.height - imgY - contentEdgeInsets.bottom - imageEdgeInsets.bottom, imgF.height), 0.0)
let newImgF = CGRect(x: imgX, y: imgY, width: imgW, height: imgH)
self.titleLabel?.frame = newTtlF
self.imageView?.frame = newImgF
// print("\noverall frame = \(frame)\ntitle frame = \(ttlF)\nimage frame = \(imgF)\ndefault title margin H = \(hTtlMrgDef)\ndefault title margi V = \(vTtlMrgDef)\ntitle frame = \(newTtlF)")
break
// 3.2
case .topImageBottomTitle:
// 3.2.1 cal image frame
// default horizontal margin of image
let hImgMrgDef = max((frame.width - imgF.width) * 0.5, 0.0)
// default vertical margin of image
let vImgMrgDef = max((frame.height - imgF.height - ttlF.height) * 0.5, 0.0)
// imgX/Y/W/H
let imgX = contentEdgeInsets.left + imageEdgeInsets.left + hImgMrgDef
let imgY = contentEdgeInsets.top + imageEdgeInsets.top + vImgMrgDef
let imgW = max(min(frame.width - imgX - contentEdgeInsets.right - imageEdgeInsets.right, imgF.width), 0.0)
let imgH = max(min(frame.height - imgY - contentEdgeInsets.bottom - imageEdgeInsets.bottom, imgF.height), 0.0)
let newImgF = CGRect(x: imgX, y: imgY, width: imgW, height: imgH)
// 3.2.2 cal title frame
// default horizontal margin of title
let hTtlMrgDef = max((frame.width - ttlF.width) * 0.5, 0.0)
// ttlX/Y/W/H
let ttlX = contentEdgeInsets.left + titleEdgeInsets.left + hTtlMrgDef
let ttlY = contentEdgeInsets.top + titleEdgeInsets.top + vImgMrgDef + imgF.height
let ttlW = max(min(frame.width - ttlX - contentEdgeInsets.right - titleEdgeInsets.right, ttlF.width), 0.0)
let ttlH = max(min(frame.height - ttlY - contentEdgeInsets.bottom - titleEdgeInsets.bottom, ttlF.height), 0.0)
let newTtlF = CGRect(x: ttlX, y: ttlY, width: ttlW, height: ttlH)
self.titleLabel?.frame = newTtlF
self.imageView?.frame = newImgF
break
case .topTitleBottomImage:
// 3.2.1 cal title frame
// default horizontal margin of title
let hTtlMrgDef = max((frame.width - ttlF.width) * 0.5, 0.0)
// default vertical margin of title
let vTtlMrgDef = max((frame.height - ttlF.height - imgF.height) * 0.5, 0.0)
// ttlX/Y/W/H
let ttlX = contentEdgeInsets.left + titleEdgeInsets.left + hTtlMrgDef
let ttlY = contentEdgeInsets.top + titleEdgeInsets.top + vTtlMrgDef
let ttlW = max(min(frame.width - ttlX - contentEdgeInsets.right - titleEdgeInsets.right, ttlF.width), 0.0)
let ttlH = max(min(frame.height - ttlY - contentEdgeInsets.bottom - titleEdgeInsets.bottom, ttlF.height), 0.0)
let newTtlF = CGRect(x: ttlX, y: ttlY, width: ttlW, height: ttlH)
// 3.2.2 cal image frame
// default horizontal margin of image
let hImgMrgDef = max((frame.width - imgF.width) * 0.5, 0.0)
// imgX/Y/W/H
let imgX = contentEdgeInsets.left + imageEdgeInsets.left + hImgMrgDef
let imgY = contentEdgeInsets.top + imageEdgeInsets.top + vTtlMrgDef + ttlF.height
let imgW = max(min(frame.width - imgX - contentEdgeInsets.right - imageEdgeInsets.right, imgF.width), 0.0)
let imgH = max(min(frame.height - imgY - contentEdgeInsets.bottom - imageEdgeInsets.bottom, imgF.height), 0.0)
let newImgF = CGRect(x: imgX, y: imgY, width: imgW, height: imgH)
self.titleLabel?.frame = newTtlF
self.imageView?.frame = newImgF
break
default:
break
}
}
}
// MARK: -
extension KEYButton {
open override func draw(_ rect: CGRect) {
super.draw(rect)
if borderWidth > 0 {
// 1. draw border
// 1.1 cal rect for border path
let bW = rect.width - CGFloat(borderWidth)
let bH = rect.height - CGFloat(borderWidth)
let bCR = max(self.layer.cornerRadius - CGFloat(borderWidth) * 0.5, 0.0)
let bX = CGFloat(borderWidth) * 0.5
let bY = bX
let borderP = UIBezierPath(roundedRect: CGRect(x: bX, y: bY, width: bW, height: bH),
byRoundingCorners: roundingCorners,
cornerRadii: CGSize(width: bCR, height: bCR))
borderP.lineWidth = CGFloat(borderWidth)
borderColor.setStroke()
borderP.stroke()
// 2. fill within border
let fW = bW - CGFloat(borderWidth)
let fH = bH - CGFloat(borderWidth)
let fX = CGFloat(borderWidth)
let fY = fX
let fCR = max(self.layer.cornerRadius - CGFloat(borderWidth), 0.0)
let fP = UIBezierPath(roundedRect: CGRect(x: fX, y: fY, width: fW, height: fH),
byRoundingCorners: roundingCorners,
cornerRadii: CGSize(width: fCR, height: fCR))
self.backgroundColor = UIColor.clear
fillColor.setFill()
fP.fill()
}
}
public func startAnimating() {
self.imageView?.startAnimating()
}
public func stopAnimating() {
self.imageView?.stopAnimating()
}
public func isAnimating() -> Bool {
return self.imageView?.isAnimating ?? false
}
}
| mit |
RCacheaux/BitbucketKit | Carthage/Checkouts/Swinject/Carthage/Checkouts/Quick/Sources/QuickTests/FunctionalTests/SharedExamples+BeforeEachTests.swift | 5 | 1869 | import XCTest
import Quick
import Nimble
#if SWIFT_PACKAGE
import QuickTestHelpers
#endif
var specBeforeEachExecutedCount = 0
var sharedExamplesBeforeEachExecutedCount = 0
class FunctionalTests_SharedExamples_BeforeEachTests_SharedExamples: QuickConfiguration {
override class func configure(configuration: Configuration) {
sharedExamples("a group of three shared examples with a beforeEach") {
beforeEach { sharedExamplesBeforeEachExecutedCount += 1 }
it("passes once") {}
it("passes twice") {}
it("passes three times") {}
}
}
}
class FunctionalTests_SharedExamples_BeforeEachSpec: QuickSpec {
override func spec() {
beforeEach { specBeforeEachExecutedCount += 1 }
it("executes the spec beforeEach once") {}
itBehavesLike("a group of three shared examples with a beforeEach")
}
}
class SharedExamples_BeforeEachTests: XCTestCase, XCTestCaseProvider {
var allTests: [(String, () -> Void)] {
return [
("testBeforeEachOutsideOfSharedExamplesExecutedOnceBeforeEachExample", testBeforeEachOutsideOfSharedExamplesExecutedOnceBeforeEachExample),
("testBeforeEachInSharedExamplesExecutedOnceBeforeEachSharedExample", testBeforeEachInSharedExamplesExecutedOnceBeforeEachSharedExample),
]
}
func testBeforeEachOutsideOfSharedExamplesExecutedOnceBeforeEachExample() {
specBeforeEachExecutedCount = 0
qck_runSpec(FunctionalTests_SharedExamples_BeforeEachSpec.self)
XCTAssertEqual(specBeforeEachExecutedCount, 4)
}
func testBeforeEachInSharedExamplesExecutedOnceBeforeEachSharedExample() {
sharedExamplesBeforeEachExecutedCount = 0
qck_runSpec(FunctionalTests_SharedExamples_BeforeEachSpec.self)
XCTAssertEqual(sharedExamplesBeforeEachExecutedCount, 3)
}
}
| apache-2.0 |
matrix-org/matrix-ios-sdk | MatrixSDK/Space/MXSpaceStore.swift | 1 | 1204 | //
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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
/// `MXSpaceStore` instances are used to store the spaces related data into a permanent store
protocol MXSpaceStore {
/// Stores the given graph
/// - Parameters:
/// - spaceGraphData: space graph to be stored
/// - Returns: `true` if the data has been stored properly.`false` otherwise
func store(spaceGraphData: MXSpaceGraphData) -> Bool
/// Loads graph data from store
/// - Returns:an instance of `MXSpaceGraphData` if the data has been restored succesfully. `nil` otherwise
func loadSpaceGraphData() -> MXSpaceGraphData?
}
| apache-2.0 |
sarvex/SwiftRecepies | Graphics/Constructing Resizable Images/Constructing Resizable Images/AppDelegate.swift | 1 | 1300 | //
// AppDelegate.swift
// Constructing Resizable Images
//
// Created by Vandad Nahavandipoor on 6/24/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
}
| isc |
tkersey/top | top/Cell.swift | 1 | 566 | import UIKit
class Cell: UITableViewCell {
@IBOutlet weak var detailsLabel: UILabel!
@IBOutlet weak var thumbnailImage: ImageView!
@IBOutlet weak var titleLabel: UILabel!
}
// MARK: - Configure
extension Cell {
func configure(with row: Row) {
detailsLabel.text = "u/\(row.author) ⦿ \(row.createdAt.timeAgoString()) ⦿ \(row.numberOfComments) comment\(row.numberOfComments > 1 ? "s" : "")"
thumbnailImage.image = row.thumbnail
thumbnailImage.fullScreenImage = row.previewImage
titleLabel.text = row.title
}
}
| mit |
thebluepotato/AlamoFuzi | Pods/Alamofire/Source/Validation.swift | 1 | 9789 | //
// Validation.swift
//
// Copyright (c) 2014-2018 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
extension Request {
// MARK: Helper Types
fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason
/// Used to represent whether a validation succeeded or failed.
public typealias ValidationResult = AFResult<Void>
fileprivate struct MIMEType {
let type: String
let subtype: String
var isWildcard: Bool { return type == "*" && subtype == "*" }
init?(_ string: String) {
let components: [String] = {
let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines)
let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)]
return split.components(separatedBy: "/")
}()
if let type = components.first, let subtype = components.last {
self.type = type
self.subtype = subtype
} else {
return nil
}
}
func matches(_ mime: MIMEType) -> Bool {
switch (type, subtype) {
case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
return true
default:
return false
}
}
}
// MARK: Properties
fileprivate var acceptableStatusCodes: Range<Int> { return 200..<300 }
fileprivate var acceptableContentTypes: [String] {
if let accept = request?.value(forHTTPHeaderField: "Accept") {
return accept.components(separatedBy: ",")
}
return ["*/*"]
}
// MARK: Status Code
fileprivate func validate<S: Sequence>(
statusCode acceptableStatusCodes: S,
response: HTTPURLResponse)
-> ValidationResult
where S.Iterator.Element == Int
{
if acceptableStatusCodes.contains(response.statusCode) {
return .success(Void())
} else {
let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode)
return .failure(AFError.responseValidationFailed(reason: reason))
}
}
// MARK: Content Type
fileprivate func validate<S: Sequence>(
contentType acceptableContentTypes: S,
response: HTTPURLResponse,
data: Data?)
-> ValidationResult
where S.Iterator.Element == String
{
guard let data = data, data.count > 0 else { return .success(Void()) }
guard
let responseContentType = response.mimeType,
let responseMIMEType = MIMEType(responseContentType)
else {
for contentType in acceptableContentTypes {
if let mimeType = MIMEType(contentType), mimeType.isWildcard {
return .success(Void())
}
}
let error: AFError = {
let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes))
return AFError.responseValidationFailed(reason: reason)
}()
return .failure(error)
}
for contentType in acceptableContentTypes {
if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
return .success(Void())
}
}
let error: AFError = {
let reason: ErrorReason = .unacceptableContentType(
acceptableContentTypes: Array(acceptableContentTypes),
responseContentType: responseContentType
)
return AFError.responseValidationFailed(reason: reason)
}()
return .failure(error)
}
}
// MARK: -
extension DataRequest {
/// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the
/// request was valid.
public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
/// Validates that the response has a status code in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter range: The range of acceptable status codes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
return validate { [unowned self] _, response, _ in
return self.validate(statusCode: acceptableStatusCodes, response: response)
}
}
/// Validates that the response has a content type in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
return validate { [unowned self] _, response, data in
return self.validate(contentType: acceptableContentTypes(), response: response, data: data)
}
}
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
/// type matches any specified in the Accept HTTP header field.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - returns: The request.
@discardableResult
public func validate() -> Self {
let contentTypes: () -> [String] = { [unowned self] in
return self.acceptableContentTypes
}
return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
}
}
// MARK: -
extension DownloadRequest {
/// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a
/// destination URL, and returns whether the request was valid.
public typealias Validation = (
_ request: URLRequest?,
_ response: HTTPURLResponse,
_ fileURL: URL?)
-> ValidationResult
/// Validates that the response has a status code in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter range: The range of acceptable status codes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
return validate { [unowned self] (_, response, _) in
return self.validate(statusCode: acceptableStatusCodes, response: response)
}
}
/// Validates that the response has a content type in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
return validate { [unowned self] (_, response, fileURL) in
guard let validFileURL = fileURL else {
return .failure(AFError.responseValidationFailed(reason: .dataFileNil))
}
do {
let data = try Data(contentsOf: validFileURL)
return self.validate(contentType: acceptableContentTypes(), response: response, data: data)
} catch {
return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL)))
}
}
}
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
/// type matches any specified in the Accept HTTP header field.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - returns: The request.
@discardableResult
public func validate() -> Self {
let contentTypes = { [unowned self] in
return self.acceptableContentTypes
}
return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
}
}
| mit |
protoman92/SwiftUtilities | SwiftUtilitiesTests/test/date/DatesTest.swift | 1 | 2667 | //
// DateUtilTest.swift
// SwiftUtilitiesTests
//
// Created by Hai Pham on 2/11/16.
// Copyright © 2016 Swiften. All rights reserved.
//
import XCTest
@testable import SwiftUtilities
public final class DatesTest: XCTestCase {
/// Test date comparison methods and ensure they work correctly.
public func test_dateComparison_shouldSucceed() {
/// Setup
let calendar = Calendar.current
/// Test date comparison using parameters. This closure accepts three
/// arguments, the first being the starting Date, to/from which an
/// offset value - the second argument - will be added/subtracted.
/// The third argument is a Calendar.Component instance that will
/// be used for granularity comparison.
let testDateComparison: (Date, Int, Calendar.Component) -> Void = {
/// Setup
let date = $0
// When
let fDate = calendar.date(byAdding: $2, value: -$1, to: $0)!
let sDate = calendar.date(byAdding: $2, value: $1, to: $0)!
// Then
/// Comparing from the Date instance itself.
XCTAssertTrue(date.sameAs(date: date))
XCTAssertTrue(date.notLaterThan(date: date))
XCTAssertTrue(date.notEarlierThan(date: date))
XCTAssertTrue(date.laterThan(date: fDate))
XCTAssertTrue(date.notEarlierThan(date: fDate))
XCTAssertTrue(date.earlierThan(date: sDate))
XCTAssertTrue(date.notLaterThan(date: sDate))
/// Comparing using a Calendar instance.
XCTAssertTrue(calendar.notLaterThan(compare: date, to: date, granularity: $2))
XCTAssertTrue(calendar.notEarlierThan(compare: date, to: date, granularity: $2))
XCTAssertTrue(calendar.notEarlierThan(compare: date, to: fDate, granularity: $2))
XCTAssertTrue(calendar.notLaterThan(compare: date, to: sDate, granularity: $2))
XCTAssertTrue(calendar.laterThan(compare: date, to: fDate, granularity: $2))
XCTAssertTrue(calendar.notLaterThan(compare: date, to: sDate, granularity: $2))
}
// When
for i in 1...1000 {
let dateComponents = DateComponents.random()
let date = calendar.date(from: dateComponents)!
let offset = Int.randomBetween(1, i)
let calendarComponent = Calendar.Component.random()
testDateComparison(date, offset, calendarComponent)
}
}
public func test_randomBetween_shouldWork() {
/// Setup
let startDate = Date.random()!
let endDate = startDate.addingTimeInterval(100000000)
/// When
for _ in 0..<1000 {
let randomized = Date.randomBetween(startDate, endDate)!
/// Then
XCTAssertTrue(randomized >= startDate)
XCTAssertTrue(randomized <= endDate)
}
}
}
| apache-2.0 |
JRG-Developer/ObservableType | ObservableType/Library/Updatable.swift | 1 | 1901 | //
// Updatable.swift
// ObservableType
//
// Created by Joshua Greene on 1/17/17.
// Copyright © 2017 Joshua Greene. 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.
@available(*, deprecated, renamed: "Updatable")
public typealias Updating = Updatable
/// `Updatable` defines a class that can be updated with a newer version (e.g. from a newer server response).
public protocol Updatable: class, Hashable {
/// Use this method to update the current model with a new version.
///
/// - Parameter newVersion: The new model version
/// - Returns: `true` if the model was updated or `false` otherwise
@discardableResult func update(with newVersion: Self) -> Bool
/// The unique identifier for this object, which is used to determine which model should be updated in a collection.
var identifier: String { get }
}
| mit |
terryokay/learnAnimationBySwift | learnAnimation/learnAnimation/BackgroundLineView.swift | 1 | 4337 | //
// BackgroundLineView.swift
// learnAnimation
//
// Created by likai on 2017/4/17.
// Copyright © 2017年 terry. All rights reserved.
//
import UIKit
class BackgroundLineView: UIView {
var lineWidth : CGFloat{
get{ return backgroundView.lineWidth}
set(newVal){
backgroundView.lineWidth = newVal
backgroundView.setNeedsDisplay()
}
}
var lineGap : CGFloat {
get {return backgroundView.lineGap}
set(newVal){
backgroundView.lineGap = newVal
backgroundView.setNeedsDisplay()
}
}
var lineColor : UIColor{
get{return backgroundView.lineColor}
set(newVal){
backgroundView.lineColor = newVal
backgroundView.setNeedsDisplay()
}
}
var rotate : CGFloat {
get {return backgroundView.rotate}
set(newVal){
backgroundView.rotate = newVal
backgroundView.setNeedsDisplay()
}
}
convenience init(frame:CGRect, lineWidth : CGFloat, lineGap : CGFloat,lineColor : UIColor, rotate : CGFloat){
self.init(frame: frame)
self.lineWidth = lineWidth
self.lineGap = lineGap
self.lineColor = lineColor
self.rotate = rotate
}
override func layoutSubviews() {
super.layoutSubviews()
setupBackgroundView()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.masksToBounds = true
self.addSubview(backgroundView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate let backgroundView = LineBackground(length: 0)
fileprivate func setupBackgroundView(){
let drawLength = sqrt(self.bounds.size.width * self.bounds.size.width + self.bounds.size.height * self.bounds.size.height)
backgroundView.frame = CGRect(x: 0, y: 0, width: drawLength, height: drawLength)
backgroundView.center = CGPoint(x: self.bounds.size.width / 2.0, y: self.bounds.size.height / 2.0)
backgroundView.setNeedsDisplay()
}
}
private class LineBackground : UIView{
fileprivate var rotate : CGFloat = 0
fileprivate var lineWidth : CGFloat = 5
fileprivate var lineGap : CGFloat = 3
fileprivate var lineColor : UIColor = UIColor.gray
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(length : CGFloat){
self.init(frame: CGRect(x: 0, y: 0, width: length, height: length))
}
override func draw(_ rect: CGRect) {
super.draw(rect)
guard self.bounds.size.width > 0 && self.bounds.size.height > 0 else{
return
}
let context = UIGraphicsGetCurrentContext()
let width = self.bounds.size.width
let height = self.bounds.size.height
let drawLength = sqrt(width * width + height * height)
let outerX = (drawLength - width) / 2.0
let outerY = (drawLength - height) / 2.0
let tmpLineWidth = lineWidth <= 0 ? 5 : lineWidth
let tmpLineGap = lineGap <= 0 ? 3 : lineGap
var red : CGFloat = 0
var green : CGFloat = 0
var blue : CGFloat = 0
var alpha : CGFloat = 0
context?.translateBy(x: 0.5 * drawLength, y: 0.5 * drawLength)
context?.rotate(by: rotate)
context?.translateBy(x: -0.5 * drawLength, y: -0.5 * drawLength)
lineColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
context?.setFillColor(red: red, green: green, blue: blue, alpha: alpha)
var currentX = -outerX
while currentX < drawLength{
context?.addRect(CGRect(x: currentX, y: -outerY, width: tmpLineWidth, height: drawLength))
currentX += tmpLineWidth + tmpLineGap
}
context?.fillPath()
}
}
| mit |
tqtifnypmb/armature | Sources/Armature/Utils/String+BytesConvert.swift | 1 | 1583 | //
// String+BytesConvert.swift
// Armature
//
// The MIT License (MIT)
//
// Copyright (c) 2016 tqtifnypmb
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
extension String {
func toBytes(inout buffer: [UInt8]) -> Bool {
return self.getBytes(&buffer,
maxLength: buffer.capacity,
usedLength: nil,
encoding: NSUTF8StringEncoding,
options: .AllowLossy,
range: Range(start: self.startIndex, end: self.endIndex),
remainingRange: nil)
}
}
| mit |
ttlock/iOS_TTLock_Demo | Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/DFUSelector/DFUServiceSelector.swift | 2 | 3375 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
internal protocol DFUStarterPeripheralDelegate : BasePeripheralDelegate {
/**
Callback called when a DFU service has been found on a remote device.
- parameter ExecutorType: The type of the seleceted executor.
- returns: The executor type based on the found DFU Service:
SecureDFUExecutor or LegacyDFUExecutor.
*/
func peripheralDidSelectedExecutor(_ ExecutorType: DFUExecutorAPI.Type)
}
/**
This class has a responsibility to connect to a given peripheral and
determin which DFU implementation should be used based on the services
found on the device.
*/
internal class DFUServiceSelector : BaseDFUExecutor, DFUStarterPeripheralDelegate {
typealias DFUPeripheralType = DFUStarterPeripheral
internal let initiator: DFUServiceInitiator
internal let logger: LoggerHelper
internal let controller: DFUServiceController
internal let peripheral: DFUStarterPeripheral
internal var error: (error: DFUError, message: String)?
init(initiator: DFUServiceInitiator, controller: DFUServiceController) {
self.initiator = initiator
self.logger = LoggerHelper(initiator.logger, initiator.loggerQueue)
self.controller = controller
self.peripheral = DFUStarterPeripheral(initiator, logger)
self.peripheral.delegate = self
}
func start() {
delegate {
$0.dfuStateDidChange(to: .connecting)
}
peripheral.start()
}
func peripheralDidSelectedExecutor(_ ExecutorType: DFUExecutorAPI.Type) {
// Release the cyclic reference
peripheral.destroy()
let executor = ExecutorType.init(initiator, logger)
controller.executor = executor
executor.start()
}
}
| mit |
honghaoz/ZHStackView | ZHStackViewDemo/ZHStackViewDemoTests/ZHStackViewDemoTests.swift | 2 | 926 | //
// ZHStackViewDemoTests.swift
// ZHStackViewDemoTests
//
// Created by Honghao Zhang on 2014-10-17.
// Copyright (c) 2014 HonghaoZ. All rights reserved.
//
import UIKit
import XCTest
class ZHStackViewDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
Glagnar/OGCSensorThings | Pod/Classes/Swaggers/Models/FeatureOfInterest.swift | 1 | 1899 | //
// FeatureOfInterest.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class FeatureOfInterest: JSONEncodable {
/** ID is the system-generated identifier of an entity. ID is unique among the entities of the same entity type. */
public var iotId: String?
/** Self-Link is the absolute URL of an entity which is unique among all other entities. */
public var iotSelfLink: String?
/** The description about the FeatureOfInterest. */
public var description: String?
/** The encoding type of the feature property. Its value is one of the ValueCode enumeration (see Table 8-6 for the available ValueCode, GeoJSON). */
public var encodingType: String?
/** The detailed description of the feature. The data type is defined by encodingType. */
public var feature: AnyObject?
/** An Observation observes on one-and-only-one FeatureOfInterest. One FeatureOfInterest could be observed by zero-to-many Observations. */
public var observations: [Observation]?
/** link to related entities */
public var observationsiotNavigationLink: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["@iot.id"] = self.iotId
nillableDictionary["@iot.selfLink"] = self.iotSelfLink
nillableDictionary["description"] = self.description
nillableDictionary["encodingType"] = self.encodingType
nillableDictionary["feature"] = self.feature
nillableDictionary["Observations"] = self.observations?.encodeToJSON()
nillableDictionary["[email protected]"] = self.observationsiotNavigationLink
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
| apache-2.0 |
e6-1/e6-1.github.io | iOS Class/Tic-Tac-Toe/Tic-Tac-Toe/AppDelegate.swift | 1 | 2148 | //
// AppDelegate.swift
// Tic-Tac-Toe
//
// Created by Ethan Petersen on 6/5/16.
// Copyright © 2016 Rose-Hulman. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
AdamSliwakowski/TypedTableView | TypedTableViewTests/TypedTableViewTests.swift | 1 | 1015 | //
// TypedTableViewTests.swift
// TypedTableViewTests
//
// Created by Adam Śliwakowski on 20.12.2015.
// Copyright © 2015 AdamSliwakowski. All rights reserved.
//
import XCTest
@testable import TypedTableView
class TypedTableViewTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
jwfriese/FrequentFlyer | FrequentFlyer/main.swift | 1 | 361 | import UIKit
let appDelegateName = Bundle.main.object(forInfoDictionaryKey: "App Delegate Name") as! String
let unsafePointerToArgv = UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(
to: UnsafeMutablePointer<Int8>.self,
capacity: Int(CommandLine.argc)
)
UIApplicationMain(CommandLine.argc, unsafePointerToArgv, nil, appDelegateName)
| apache-2.0 |
artursDerkintis/Starfly | StarflyUITests/SFTabControllerUITests.swift | 1 | 1091 | //
// SFTabControllerUITests.swift
// Starfly
//
// Created by Arturs Derkintis on 12/8/15.
// Copyright © 2015 Starfly. All rights reserved.
//
import XCTest
class SFTabControllerUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
func testTabController() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
VBVMI/VerseByVerse-iOS | VBVMI/Model/Topic.swift | 1 | 1637 | import Foundation
import CoreData
import Decodable
extension String {
func latinize() -> String {
return self.folding(options: String.CompareOptions.diacriticInsensitive, locale: Locale.current)
}
func slugify(withSeparator separator: Character = "-") -> String {
let slugCharacterSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\(separator)")
return latinize().lowercased().components(separatedBy: slugCharacterSet.inverted).filter({ $0 != " " }).joined(separator: String(separator))
}
}
@objc(Topic)
open class Topic: _Topic {
// Custom logic goes here.
class func decodeJSON(_ JSONDict: NSDictionary, context: NSManagedObjectContext) throws -> (Topic?) {
guard let identifier = JSONDict["ID"] as? String else {
throw APIDataManagerError.missingID
}
var convertedIdentifier = identifier.replacingOccurrences(of: "+", with: " ")
convertedIdentifier = convertedIdentifier.slugify()
if convertedIdentifier.count == 0 {
return nil
}
if let name = try JSONDict => "topic" as? String , name.count > 0 {
let convertedName = name.capitalized
guard let topic = Topic.findFirstOrCreateWithDictionary(["identifier": convertedIdentifier], context: context) as? Topic else {
throw APIDataManagerError.modelCreationFailed
}
topic.identifier = convertedIdentifier
topic.name = convertedName
return topic
}
return nil
}
}
| mit |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/00557-swift-constraints-constraintsystem-getfixedtyperecursive.swift | 1 | 204 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
var : Int = (array: A? {
| mit |
qingpengchen2011/BTNavigationDropdownMenu | Source/BTNavigationDropdownMenu.swift | 3 | 22439 | //
// BTConfiguration.swift
// BTNavigationDropdownMenu
//
// Created by Pham Ba Tho on 6/30/15.
// Copyright (c) 2015 PHAM BA THO. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
// MARK: BTNavigationDropdownMenu
public class BTNavigationDropdownMenu: UIView {
// The color of menu title. Default is darkGrayColor()
public var menuTitleColor: UIColor! {
get {
return self.configuration.menuTitleColor
}
set(value) {
self.configuration.menuTitleColor = value
}
}
// The height of the cell. Default is 50
public var cellHeight: CGFloat! {
get {
return self.configuration.cellHeight
}
set(value) {
self.configuration.cellHeight = value
}
}
// The color of the cell background. Default is whiteColor()
public var cellBackgroundColor: UIColor! {
get {
return self.configuration.cellBackgroundColor
}
set(color) {
self.configuration.cellBackgroundColor = color
}
}
public var cellSeparatorColor: UIColor! {
get {
return self.configuration.cellSeparatorColor
}
set(value) {
self.configuration.cellSeparatorColor = value
}
}
// The color of the text inside cell. Default is darkGrayColor()
public var cellTextLabelColor: UIColor! {
get {
return self.configuration.cellTextLabelColor
}
set(value) {
self.configuration.cellTextLabelColor = value
}
}
// The font of the text inside cell. Default is HelveticaNeue-Bold, size 19
public var cellTextLabelFont: UIFont! {
get {
return self.configuration.cellTextLabelFont
}
set(value) {
self.configuration.cellTextLabelFont = value
self.menuTitle.font = self.configuration.cellTextLabelFont
}
}
// The color of the cell when the cell is selected. Default is lightGrayColor()
public var cellSelectionColor: UIColor! {
get {
return self.configuration.cellSelectionColor
}
set(value) {
self.configuration.cellSelectionColor = value
}
}
// The checkmark icon of the cell
public var checkMarkImage: UIImage! {
get {
return self.configuration.checkMarkImage
}
set(value) {
self.configuration.checkMarkImage = value
}
}
// The animation duration of showing/hiding menu. Default is 0.3
public var animationDuration: NSTimeInterval! {
get {
return self.configuration.animationDuration
}
set(value) {
self.configuration.animationDuration = value
}
}
// The arrow next to navigation title
public var arrowImage: UIImage! {
get {
return self.configuration.arrowImage
}
set(value) {
self.configuration.arrowImage = value
self.menuArrow.image = self.configuration.arrowImage
}
}
// The padding between navigation title and arrow
public var arrowPadding: CGFloat! {
get {
return self.configuration.arrowPadding
}
set(value) {
self.configuration.arrowPadding = value
}
}
// The color of the mask layer. Default is blackColor()
public var maskBackgroundColor: UIColor! {
get {
return self.configuration.maskBackgroundColor
}
set(value) {
self.configuration.maskBackgroundColor = value
}
}
// The opacity of the mask layer. Default is 0.3
public var maskBackgroundOpacity: CGFloat! {
get {
return self.configuration.maskBackgroundOpacity
}
set(value) {
self.configuration.maskBackgroundOpacity = value
}
}
public var didSelectItemAtIndexHandler: ((indexPath: Int) -> ())?
private var navigationController: UINavigationController?
private var configuration = BTConfiguration()
private var topSeparator: UIView!
private var menuButton: UIButton!
private var menuTitle: UILabel!
private var menuArrow: UIImageView!
private var backgroundView: UIView!
private var tableView: BTTableView!
private var items: [AnyObject]!
private var isShown: Bool!
private var menuWrapper: UIView!
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init(title: String, items: [AnyObject]) {
// Navigation controller
self.navigationController = UIApplication.sharedApplication().keyWindow?.rootViewController?.topMostViewController?.navigationController
// Get titleSize
let titleSize = (title as NSString).sizeWithAttributes([NSFontAttributeName:self.configuration.cellTextLabelFont])
// Set frame
let frame = CGRectMake(0, 0, titleSize.width + (self.configuration.arrowPadding + self.configuration.arrowImage.size.width)*2, self.navigationController!.navigationBar.frame.height)
super.init(frame:frame)
self.navigationController?.view.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
self.isShown = false
self.items = items
// Init properties
self.setupDefaultConfiguration()
// Init button as navigation title
self.menuButton = UIButton(frame: frame)
self.menuButton.addTarget(self, action: "menuButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(self.menuButton)
self.menuTitle = UILabel(frame: frame)
self.menuTitle.text = title
self.menuTitle.textColor = self.menuTitleColor
self.menuTitle.textAlignment = NSTextAlignment.Center
self.menuTitle.font = self.configuration.cellTextLabelFont
self.menuButton.addSubview(self.menuTitle)
self.menuArrow = UIImageView(image: self.configuration.arrowImage)
self.menuButton.addSubview(self.menuArrow)
let window = UIApplication.sharedApplication().keyWindow!
let menuWrapperBounds = window.bounds
// Set up DropdownMenu
self.menuWrapper = UIView(frame: CGRectMake(menuWrapperBounds.origin.x, 0, menuWrapperBounds.width, menuWrapperBounds.height))
self.menuWrapper.clipsToBounds = true
self.menuWrapper.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(UIViewAutoresizing.FlexibleHeight)
// Init background view (under table view)
self.backgroundView = UIView(frame: menuWrapperBounds)
self.backgroundView.backgroundColor = self.configuration.maskBackgroundColor
self.backgroundView.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(UIViewAutoresizing.FlexibleHeight)
// Init table view
self.tableView = BTTableView(frame: CGRectMake(menuWrapperBounds.origin.x, menuWrapperBounds.origin.y + 0.5, menuWrapperBounds.width, menuWrapperBounds.height + 300), items: items, configuration: self.configuration)
self.tableView.selectRowAtIndexPathHandler = { (indexPath: Int) -> () in
self.didSelectItemAtIndexHandler!(indexPath: indexPath)
self.setMenuTitle("\(items[indexPath])")
self.hideMenu()
self.isShown = false
self.layoutSubviews()
}
// Add background view & table view to container view
self.menuWrapper.addSubview(self.backgroundView)
self.menuWrapper.addSubview(self.tableView)
// Add Line on top
self.topSeparator = UIView(frame: CGRectMake(0, 0, menuWrapperBounds.size.width, 0.5))
self.topSeparator.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.menuWrapper.addSubview(self.topSeparator)
// Add Menu View to container view
window.addSubview(self.menuWrapper)
// By default, hide menu view
self.menuWrapper.hidden = true
}
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "frame" {
// Set up DropdownMenu
self.menuWrapper.frame.origin.y = self.navigationController!.navigationBar.frame.maxY
self.tableView.reloadData()
}
}
override public func layoutSubviews() {
self.menuTitle.sizeToFit()
self.menuTitle.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2)
self.menuArrow.sizeToFit()
self.menuArrow.center = CGPointMake(CGRectGetMaxX(self.menuTitle.frame) + self.configuration.arrowPadding, self.frame.size.height/2)
}
func setupDefaultConfiguration() {
self.menuTitleColor = self.navigationController?.navigationBar.titleTextAttributes?[NSForegroundColorAttributeName] as? UIColor // Setter
self.cellBackgroundColor = self.navigationController?.navigationBar.barTintColor
self.cellSeparatorColor = self.navigationController?.navigationBar.titleTextAttributes?[NSForegroundColorAttributeName] as? UIColor
self.cellTextLabelColor = self.navigationController?.navigationBar.titleTextAttributes?[NSForegroundColorAttributeName] as? UIColor
}
func showMenu() {
self.menuWrapper.frame.origin.y = self.navigationController!.navigationBar.frame.maxY
// Table view header
let headerView = UIView(frame: CGRectMake(0, 0, self.frame.width, 300))
headerView.backgroundColor = self.configuration.cellBackgroundColor
self.tableView.tableHeaderView = headerView
self.topSeparator.backgroundColor = self.configuration.cellSeparatorColor
// Rotate arrow
self.rotateArrow()
// Visible menu view
self.menuWrapper.hidden = false
// Change background alpha
self.backgroundView.alpha = 0
// Animation
self.tableView.frame.origin.y = -CGFloat(self.items.count) * self.configuration.cellHeight - 300
// Reload data to dismiss highlight color of selected cell
self.tableView.reloadData()
UIView.animateWithDuration(
self.configuration.animationDuration * 1.5,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.5,
options: [],
animations: {
self.tableView.frame.origin.y = CGFloat(-300)
self.backgroundView.alpha = self.configuration.maskBackgroundOpacity
}, completion: nil
)
}
func hideMenu() {
// Rotate arrow
self.rotateArrow()
// Change background alpha
self.backgroundView.alpha = self.configuration.maskBackgroundOpacity
UIView.animateWithDuration(
self.configuration.animationDuration * 1.5,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.5,
options: [],
animations: {
self.tableView.frame.origin.y = CGFloat(-200)
}, completion: nil
)
// Animation
UIView.animateWithDuration(self.configuration.animationDuration, delay: 0, options: UIViewAnimationOptions.TransitionNone, animations: {
self.tableView.frame.origin.y = -CGFloat(self.items.count) * self.configuration.cellHeight - 300
self.backgroundView.alpha = 0
}, completion: { _ in
self.menuWrapper.hidden = true
})
}
func rotateArrow() {
UIView.animateWithDuration(self.configuration.animationDuration, animations: {[weak self] () -> () in
if let selfie = self {
selfie.menuArrow.transform = CGAffineTransformRotate(selfie.menuArrow.transform, 180 * CGFloat(M_PI/180))
}
})
}
func setMenuTitle(title: String) {
self.menuTitle.text = title
}
func menuButtonTapped(sender: UIButton) {
self.isShown = !self.isShown
if self.isShown == true {
self.showMenu()
} else {
self.hideMenu()
}
}
}
// MARK: BTConfiguration
class BTConfiguration {
var menuTitleColor: UIColor?
var cellHeight: CGFloat!
var cellBackgroundColor: UIColor?
var cellSeparatorColor: UIColor?
var cellTextLabelColor: UIColor?
var cellTextLabelFont: UIFont!
var cellSelectionColor: UIColor?
var checkMarkImage: UIImage!
var arrowImage: UIImage!
var arrowPadding: CGFloat!
var animationDuration: NSTimeInterval!
var maskBackgroundColor: UIColor!
var maskBackgroundOpacity: CGFloat!
init() {
self.defaultValue()
}
func defaultValue() {
// Path for image
let bundle = NSBundle(forClass: BTConfiguration.self)
let url = bundle.URLForResource("BTNavigationDropdownMenu", withExtension: "bundle")
let imageBundle = NSBundle(URL: url!)
let checkMarkImagePath = imageBundle?.pathForResource("checkmark_icon", ofType: "png")
let arrowImagePath = imageBundle?.pathForResource("arrow_down_icon", ofType: "png")
// Default values
self.menuTitleColor = UIColor.darkGrayColor()
self.cellHeight = 50
self.cellBackgroundColor = UIColor.whiteColor()
self.cellSeparatorColor = UIColor.darkGrayColor()
self.cellTextLabelColor = UIColor.darkGrayColor()
self.cellTextLabelFont = UIFont(name: "HelveticaNeue-Bold", size: 17)
self.cellSelectionColor = UIColor.lightGrayColor()
self.checkMarkImage = UIImage(contentsOfFile: checkMarkImagePath!)
self.animationDuration = 0.5
self.arrowImage = UIImage(contentsOfFile: arrowImagePath!)
self.arrowPadding = 15
self.maskBackgroundColor = UIColor.blackColor()
self.maskBackgroundOpacity = 0.3
}
}
// MARK: Table View
class BTTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
// Public properties
var configuration: BTConfiguration!
var selectRowAtIndexPathHandler: ((indexPath: Int) -> ())?
// Private properties
private var items: [AnyObject]!
private var selectedIndexPath: Int!
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(frame: CGRect, items: [AnyObject], configuration: BTConfiguration) {
super.init(frame: frame, style: UITableViewStyle.Plain)
self.items = items
self.selectedIndexPath = 0
self.configuration = configuration
// Setup table view
self.delegate = self
self.dataSource = self
self.backgroundColor = UIColor.clearColor()
self.separatorStyle = UITableViewCellSeparatorStyle.None
self.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.tableFooterView = UIView(frame: CGRectZero)
}
// Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return self.configuration.cellHeight
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = BTTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell", configuration: self.configuration)
cell.textLabel?.text = self.items[indexPath.row] as? String
cell.checkmarkIcon.hidden = (indexPath.row == selectedIndexPath) ? false : true
return cell
}
// Table view delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedIndexPath = indexPath.row
self.selectRowAtIndexPathHandler!(indexPath: indexPath.row)
self.reloadData()
let cell = tableView.cellForRowAtIndexPath(indexPath) as? BTTableViewCell
cell?.contentView.backgroundColor = self.configuration.cellSelectionColor
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath) as? BTTableViewCell
cell?.checkmarkIcon.hidden = true
cell?.contentView.backgroundColor = self.configuration.cellBackgroundColor
}
}
// MARK: Table view cell
class BTTableViewCell: UITableViewCell {
var checkmarkIcon: UIImageView!
var cellContentFrame: CGRect!
var configuration: BTConfiguration!
init(style: UITableViewCellStyle, reuseIdentifier: String?, configuration: BTConfiguration) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.configuration = configuration
// Setup cell
cellContentFrame = CGRectMake(0, 0, (UIApplication.sharedApplication().keyWindow?.frame.width)!, self.configuration.cellHeight)
self.contentView.backgroundColor = self.configuration.cellBackgroundColor
self.selectionStyle = UITableViewCellSelectionStyle.None
self.textLabel!.textAlignment = NSTextAlignment.Left
self.textLabel!.textColor = self.configuration.cellTextLabelColor
self.textLabel!.font = self.configuration.cellTextLabelFont
self.textLabel!.frame = CGRectMake(20, 0, cellContentFrame.width, cellContentFrame.height)
// Checkmark icon
self.checkmarkIcon = UIImageView(frame: CGRectMake(cellContentFrame.width - 50, (cellContentFrame.height - 30)/2, 30, 30))
self.checkmarkIcon.hidden = true
self.checkmarkIcon.image = self.configuration.checkMarkImage
self.checkmarkIcon.contentMode = UIViewContentMode.ScaleAspectFill
self.contentView.addSubview(self.checkmarkIcon)
// Separator for cell
let separator = BTTableCellContentView(frame: cellContentFrame)
if let cellSeparatorColor = self.configuration.cellSeparatorColor {
separator.separatorColor = cellSeparatorColor
}
self.contentView.addSubview(separator)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
self.bounds = cellContentFrame
self.contentView.frame = self.bounds
}
}
// Content view of table view cell
class BTTableCellContentView: UIView {
var separatorColor: UIColor = UIColor.blackColor()
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
func initialize() {
self.backgroundColor = UIColor.clearColor()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let context = UIGraphicsGetCurrentContext()
// Set separator color of dropdown menu based on barStyle
CGContextSetStrokeColorWithColor(context, self.separatorColor.CGColor)
CGContextSetLineWidth(context, 1)
CGContextMoveToPoint(context, 0, self.bounds.size.height)
CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height)
CGContextStrokePath(context)
}
}
extension UIViewController {
// Get ViewController in top present level
var topPresentedViewController: UIViewController? {
var target: UIViewController? = self
while (target?.presentedViewController != nil) {
target = target?.presentedViewController
}
return target
}
// Get top VisibleViewController from ViewController stack in same present level.
// It should be visibleViewController if self is a UINavigationController instance
// It should be selectedViewController if self is a UITabBarController instance
var topVisibleViewController: UIViewController? {
if let navigation = self as? UINavigationController {
if let visibleViewController = navigation.visibleViewController {
return visibleViewController.topVisibleViewController
}
}
if let tab = self as? UITabBarController {
if let selectedViewController = tab.selectedViewController {
return selectedViewController.topVisibleViewController
}
}
return self
}
// Combine both topPresentedViewController and topVisibleViewController methods, to get top visible viewcontroller in top present level
var topMostViewController: UIViewController? {
return self.topPresentedViewController?.topVisibleViewController
}
}
| mit |
tmozii1/tripbee | tripbee/AppDelegate.swift | 1 | 6092 | //
// AppDelegate.swift
// tripbee
//
// Created by ParkJH on 2015. 10. 22..
// Copyright © 2015년 timworld. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "kr.co.timworld.tripbee" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("tripbee", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit |
zhangao0086/DKImagePickerController | Sources/DKImageDataManager/DKImageDataManager.swift | 1 | 14162 | //
// DKImageDataManager.swift
// DKImagePickerController
//
// Created by ZhangAo on 15/11/29.
// Copyright © 2015年 ZhangAo. All rights reserved.
//
import UIKit
import Photos
public typealias DKImageRequestID = Int32
public let DKImageInvalidRequestID: DKImageRequestID = 0
public func getImageDataManager() -> DKImageDataManager {
return DKImageDataManager.sharedInstance
}
public class DKImageDataManager {
public class func checkPhotoPermission(_ handler: @escaping (_ granted: Bool) -> Void) {
func hasPhotoPermission() -> Bool {
return PHPhotoLibrary.authorizationStatus() == .authorized
}
func needsToRequestPhotoPermission() -> Bool {
return PHPhotoLibrary.authorizationStatus() == .notDetermined
}
hasPhotoPermission() ? handler(true) : (needsToRequestPhotoPermission() ?
PHPhotoLibrary.requestAuthorization({ status in
DispatchQueue.main.async(execute: { () in
hasPhotoPermission() ? handler(true) : handler(false)
})
}) : handler(false))
}
static let sharedInstance = DKImageDataManager()
private let manager = PHCachingImageManager()
private lazy var imageRequestOptions: PHImageRequestOptions = {
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
return options
}()
private lazy var videoRequestOptions: PHVideoRequestOptions = {
let options = PHVideoRequestOptions()
options.deliveryMode = .mediumQualityFormat
options.isNetworkAccessAllowed = true
return options
}()
@discardableResult
public func fetchImage(for asset: DKAsset,
size: CGSize,
options: PHImageRequestOptions? = nil,
contentMode: PHImageContentMode = .aspectFill,
completeBlock: @escaping (_ image: UIImage?, _ info: [AnyHashable: Any]?) -> Void) -> DKImageRequestID {
return self.fetchImage(for: asset,
size: size,
options: options,
contentMode: contentMode,
oldRequestID: nil,
completeBlock: completeBlock)
}
@discardableResult
private func fetchImage(for asset: DKAsset,
size: CGSize,
options: PHImageRequestOptions?,
contentMode: PHImageContentMode,
oldRequestID: DKImageRequestID?,
completeBlock: @escaping (_ image: UIImage?, _ info: [AnyHashable: Any]?) -> Void) -> DKImageRequestID {
let requestID = oldRequestID ?? self.getSeed()
guard let originalAsset = asset.originalAsset else {
assertionFailure("Expect originalAsset")
completeBlock(nil, nil)
return requestID
}
let requestOptions = options ?? self.imageRequestOptions
let imageRequestID = self.manager.requestImage(
for: originalAsset,
targetSize: size,
contentMode: contentMode,
options: requestOptions,
resultHandler: { image, info in
self.update(requestID: requestID, with: info)
if let info = info, let isCancelled = info[PHImageCancelledKey] as? NSNumber, isCancelled.boolValue {
completeBlock(image, info)
return
}
if let isInCloud = info?[PHImageResultIsInCloudKey] as AnyObject?,
image == nil,
isInCloud.boolValue,
!requestOptions.isNetworkAccessAllowed {
if self.cancelledRequestIDs.contains(requestID) {
self.cancelledRequestIDs.remove(requestID)
completeBlock(nil, [PHImageCancelledKey : NSNumber(value: 1)])
return
}
guard let requestCloudOptions = requestOptions.copy() as? PHImageRequestOptions else {
assertionFailure("Expect PHImageRequestOptions")
completeBlock(nil, nil)
return
}
requestCloudOptions.isNetworkAccessAllowed = true
self.fetchImage(for: asset,
size: size,
options: requestCloudOptions,
contentMode: contentMode,
oldRequestID: requestID,
completeBlock: completeBlock)
} else {
completeBlock(image, info)
}
})
self.update(requestID: requestID, with: imageRequestID, old: oldRequestID)
return requestID
}
@discardableResult
public func fetchImageData(for asset: DKAsset, options: PHImageRequestOptions? = nil, completeBlock: @escaping (_ data: Data?, _ info: [AnyHashable: Any]?) -> Void) -> DKImageRequestID {
return self.fetchImageData(for: asset, options: options, oldRequestID: nil, completeBlock: completeBlock)
}
@discardableResult
private func fetchImageData(for asset: DKAsset,
options: PHImageRequestOptions?,
oldRequestID: DKImageRequestID?,
completeBlock: @escaping (_ data: Data?, _ info: [AnyHashable: Any]?) -> Void)
-> DKImageRequestID
{
let requestID = oldRequestID ?? self.getSeed()
guard let originalAsset = asset.originalAsset else {
assertionFailure("Expect originalAsset")
completeBlock(nil, nil)
return requestID
}
let requestOptions = options ?? self.imageRequestOptions
let imageRequestID = self.manager.requestImageData(
for: originalAsset,
options: requestOptions) { (data, dataUTI, orientation, info) in
self.update(requestID: requestID, with: info)
if let info = info, let isCancelled = info[PHImageCancelledKey] as? NSNumber, isCancelled.boolValue {
completeBlock(data, info)
return
}
if let isInCloud = info?[PHImageResultIsInCloudKey] as AnyObject?,
data == nil,
isInCloud.boolValue,
!requestOptions.isNetworkAccessAllowed
{
if self.cancelledRequestIDs.contains(requestID) {
self.cancelledRequestIDs.remove(requestID)
completeBlock(nil, [PHImageCancelledKey : NSNumber(value: 1)])
return
}
guard let requestCloudOptions = requestOptions.copy() as? PHImageRequestOptions else {
assertionFailure("Expect PHImageRequestOptions")
completeBlock(nil, nil)
return
}
requestCloudOptions.isNetworkAccessAllowed = true
self.fetchImageData(for: asset, options: requestCloudOptions, oldRequestID: requestID, completeBlock: completeBlock)
} else {
completeBlock(data, info)
}
}
self.update(requestID: requestID, with: imageRequestID, old: oldRequestID)
return requestID
}
@discardableResult
public func fetchAVAsset(for asset: DKAsset, options: PHVideoRequestOptions? = nil, completeBlock: @escaping (_ avAsset: AVAsset?, _ info: [AnyHashable: Any]?) -> Void) -> DKImageRequestID {
return self.fetchAVAsset(for: asset, options: options, oldRequestID: nil, completeBlock: completeBlock)
}
@discardableResult
private func fetchAVAsset(for asset: DKAsset,
options: PHVideoRequestOptions?,
oldRequestID: DKImageRequestID?,
completeBlock: @escaping (_ avAsset: AVAsset?, _ info: [AnyHashable: Any]?) -> Void)
-> DKImageRequestID
{
let requestID = oldRequestID ?? self.getSeed()
guard let originalAsset = asset.originalAsset else {
assertionFailure("Expect originalAsset")
completeBlock(nil, nil)
return requestID
}
let requestOptions = options ?? self.videoRequestOptions
let imageRequestID = self.manager.requestAVAsset(
forVideo: originalAsset,
options: requestOptions) { avAsset, audioMix, info in
self.update(requestID: requestID, with: info)
if let info = info, let isCancelled = info[PHImageCancelledKey] as? NSNumber, isCancelled.boolValue {
completeBlock(avAsset, info)
return
}
if let isInCloud = info?[PHImageResultIsInCloudKey] as AnyObject?,
avAsset == nil,
isInCloud.boolValue,
!requestOptions.isNetworkAccessAllowed
{
if self.cancelledRequestIDs.contains(requestID) {
self.cancelledRequestIDs.remove(requestID)
completeBlock(nil, [PHImageCancelledKey : NSNumber(value: 1)])
return
}
guard let requestCloudOptions = requestOptions.copy() as? PHVideoRequestOptions else {
assertionFailure("Expect PHImageRequestOptions")
completeBlock(nil, nil)
return
}
requestCloudOptions.isNetworkAccessAllowed = true
self.fetchAVAsset(for: asset, options: requestCloudOptions, oldRequestID: requestID, completeBlock: completeBlock)
} else {
completeBlock(avAsset, info)
}
}
self.update(requestID: requestID, with: imageRequestID, old: oldRequestID)
return requestID
}
public func cancelRequest(requestID: DKImageRequestID) {
self.cancelRequests(requestIDs: [requestID])
}
public func cancelRequests(requestIDs: [DKImageRequestID]) {
self.executeOnMainThread {
while self.cancelledRequestIDs.count > 100 {
let _ = self.cancelledRequestIDs.popFirst()
}
for requestID in requestIDs {
if let imageRequestID = self.requestIDs[requestID] {
self.manager.cancelImageRequest(imageRequestID)
self.cancelledRequestIDs.insert(requestID)
}
self.requestIDs[requestID] = nil
}
}
}
public func startCachingAssets(for assets: [PHAsset], targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) {
self.manager.startCachingImages(for: assets, targetSize: targetSize, contentMode: contentMode, options: options)
}
public func stopCachingAssets(for assets: [PHAsset], targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) {
self.manager.stopCachingImages(for: assets, targetSize: targetSize, contentMode: contentMode, options: options)
}
public func stopCachingForAllAssets() {
self.manager.stopCachingImagesForAllAssets()
}
// MARK: - RequestID
private var requestIDs = [DKImageRequestID : PHImageRequestID]()
private var finishedRequestIDs = Set<DKImageRequestID>()
private var cancelledRequestIDs = Set<DKImageRequestID>()
private var seed: DKImageRequestID = 0
private func getSeed() -> DKImageRequestID {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
seed += 1
return seed
}
private func update(requestID: DKImageRequestID,
with imageRequestID: PHImageRequestID?,
old oldImageRequestID: DKImageRequestID?) {
self.executeOnMainThread {
if let imageRequestID = imageRequestID {
if self.cancelledRequestIDs.contains(requestID) {
self.cancelledRequestIDs.remove(requestID)
self.manager.cancelImageRequest(imageRequestID)
} else {
if self.finishedRequestIDs.contains(requestID) {
self.finishedRequestIDs.remove(requestID)
} else {
self.requestIDs[requestID] = imageRequestID
}
}
} else {
self.requestIDs[requestID] = nil
}
}
}
private func update(requestID: DKImageRequestID, with info: [AnyHashable : Any]?) {
guard let info = info else { return }
if let isCancelled = info[PHImageCancelledKey] as? NSNumber, isCancelled.boolValue {
self.executeOnMainThread {
self.requestIDs[requestID] = nil
self.cancelledRequestIDs.remove(requestID)
}
} else if let isDegraded = (info[PHImageResultIsDegradedKey] as? NSNumber)?.boolValue {
if !isDegraded { // No more callbacks for the requested image.
self.executeOnMainThread {
if self.requestIDs[requestID] == nil {
self.finishedRequestIDs.insert(requestID)
} else {
self.requestIDs[requestID] = nil
}
}
}
}
}
private func executeOnMainThread(block: @escaping (() -> Void)) {
if Thread.isMainThread {
block()
} else {
DispatchQueue.main.async(execute: block)
}
}
}
| mit |
CodeEagle/XMan | Sources/XMan/PBXproj.swift | 1 | 11803 | //
// PBXproj.swift
// XMan
//
// Created by lincolnlaw on 2017/7/14.
//
import Foundation
final class PBXproj {
private var _projectPath: String
var source: [String : Any]
var objects: [String : Any] {
get { return source["objects"] as? [String : Any] ?? [:] }
set { source["objects"] = newValue }
}
lazy var mainGroup: PBXGroup? = {
if let mainGroupKey = _project["mainGroup"] as? String {
return PBXGroup(pbxproj: self, key: mainGroupKey)
}
return nil
}()
private var _objectVersion: String? {
return source["objectVersion"] as? String
}
private var _projectKey: String = ""
private var _project: [String : Any] {
if _projectKey.isEmpty == false {
return objects[_projectKey] as? [String : Any] ?? [:]
}
for (key, value) in objects {
guard let dict = value as? [String : Any], let isa = dict["isa"] as? String, isa == "PBXProject" else { continue }
_projectKey = key
return dict
}
return [:]
}
public func isTargetRef(for key: String) -> Bool {
var nativeTargetKeys: [String] = []
if let key = _project["productRefGroup"] as? String, let info = objects[key] as? [String : Any], let children = info["children"] as? [String] {
nativeTargetKeys = children
}
if let info = objects[key] as? [String : Any], let ref = info["fileRef"] as? String {
let result = nativeTargetKeys.contains(ref)
return result
}
return false
}
private var _targets: [PBXNativeTarget] {
guard let targetsKeys = _project["targets"] as? [String] else { return [] }
var targets: [PBXNativeTarget] = []
for key in targetsKeys {
guard let info = objects[key] as? [String : Any], let name = info["name"] as? String else { continue }
targets.append(PBXNativeTarget(pbxproj: self, key: key, name: name))
}
return targets
}
init(source: [String : Any], path: String) {
self.source = source
_projectPath = path
}
}
extension PBXproj {
func target(for name: String) -> PBXNativeTarget? {
return _targets.filter { $0.name == name }.first
}
}
// MARK: Save
extension PBXproj {
private func backupPath() -> String {
let user = ProcessInfo.processInfo.environment["USER"]
let backup = "/Users/\(String(describing: user!))/Documents/XMan"
let fm = FileManager.default
do {
if fm.fileExists(atPath: backup) == false {
try fm.createDirectory(atPath: backup, withIntermediateDirectories: false, attributes: nil)
}
let final = "\(_projectPath)/project.pbxproj"
let name = final.replacingOccurrences(of: "/", with: "_")
let backupFile = "\(backup)/\(name)"
return backupFile
} catch {
Log.error("XMan create backup path fail:\(error.localizedDescription)")
exit(0)
}
}
private func write(object: [String : Any], to path: String) {
guard let objectVersion = object["objectVersion"] as? String else { return }
let raw = (object as NSDictionary).description
let url = URL(fileURLWithPath: path)
var final = raw
if objectVersion > "46" {
final = "// !$*UTF8*$!\n\(raw)"
final = replacingQuoteForKey(in: final)
final = dealLines(in: final)
let data = final.data(using: .utf8)
do {
try data?.write(to: url)
} catch {
print(error)
}
} else {
do {
let data = try PropertyListSerialization.data(fromPropertyList: object, format: .xml, options: 0)
let d = fix(data: data)
try d.write(to: url)
} catch {
print(error.localizedDescription)
}
}
}
private func write(to path: String) {
write(object: source, to: path)
}
func restore() {
do {
let d = try Data(contentsOf: URL(fileURLWithPath: backupPath()))
let dict = try PropertyListSerialization.propertyList(from: d, options: [], format: nil)
if let map = dict as? [String : Any] {
Log.debug("write to:\(_projectPath)/project.pbxproj")
write(object: map, to: "\(_projectPath)/project.pbxproj")
Log.info("XMan Success restore project 🎉")
} else {
Log.warning("no backup value")
}
} catch {
Log.error("XMan restore error:\(error.localizedDescription)")
}
}
func backup(force: Bool = false) {
let backupFile = backupPath()
if force {
Log.info("backup project.pbxproj for first time, at \(backupFile)")
write(to: backupFile)
return
}
let fm = FileManager.default
if fm.fileExists(atPath: backupFile) {
Log.debug("backup file exists, skip backup")
return
}
Log.info("backup project.pbxproj for first time, at \(backupFile)")
write(to: backupFile)
}
func save() {
write(to: "\(_projectPath)/project.pbxproj")
}
private func fix(data: Data) -> Data {
guard let source = String(data: data, encoding: .utf8) else { return data }
var destination = ""
for c in source.unicodeScalars {
let raw = c.value
if raw < 128 {
let value = String(format: "%c", raw)
destination += value
} else {
let value = String(format: "&#%u;", raw)
destination += value
}
}
return destination.data(using: .utf8)!
}
private func replacingQuoteForKey(in content: String) -> String {
let keys = ["ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "ASSETCATALOG_COMPILER_APPICON_NAME","DEVELOPMENT_TEAM", "INFOPLIST_FILE", "LD_RUNPATH_SEARCH_PATHS","PRODUCT_BUNDLE_IDENTIFIER", "PRODUCT_NAME", "SWIFT_VERSION", "TARGETED_DEVICE_FAMILY","ALWAYS_SEARCH_USER_PATHS", "CLANG_ANALYZER_NONNULL", "CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION", "CLANG_CXX_LANGUAGE_STANDARD", "CLANG_CXX_LIBRARY", "CLANG_ENABLE_MODULES", "CLANG_ENABLE_OBJC_ARC", "CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING", "CLANG_WARN_BOOL_CONVERSION", "CLANG_WARN_COMMA", "CLANG_WARN_CONSTANT_CONVERSION", "CLANG_WARN_DIRECT_OBJC_ISA_USAGE", "CLANG_WARN_DOCUMENTATION_COMMENTS", "CLANG_WARN_EMPTY_BODY", "CLANG_WARN_ENUM_CONVERSION", "CLANG_WARN_INFINITE_RECURSION", "CLANG_WARN_INT_CONVERSION", "CLANG_WARN_OBJC_ROOT_CLASS", "CLANG_WARN_RANGE_LOOP_ANALYSIS", "CLANG_WARN_STRICT_PROTOTYPES", "CLANG_WARN_SUSPICIOUS_MOVE", "CLANG_WARN_UNGUARDED_AVAILABILITY", "CLANG_WARN_UNREACHABLE_CODE", "CLANG_WARN__DUPLICATE_METHOD_MATCH", "CODE_SIGN_IDENTITY", "COPY_PHASE_STRIP", "CURRENT_PROJECT_VERSION", "DEBUG_INFORMATION_FORMAT", "ENABLE_STRICT_OBJC_MSGSEND", "ENABLE_TESTABILITY", "GCC_C_LANGUAGE_STANDARD", "GCC_DYNAMIC_NO_PIC", "GCC_NO_COMMON_BLOCKS", "GCC_OPTIMIZATION_LEVEL", "GCC_PREPROCESSOR_DEFINITIONS", "GCC_WARN_64_TO_32_BIT_CONVERSION", "GCC_WARN_ABOUT_RETURN_TYPE", "GCC_WARN_UNDECLARED_SELECTOR", "GCC_WARN_UNINITIALIZED_AUTOS", "GCC_WARN_UNUSED_FUNCTION", "GCC_WARN_UNUSED_VARIABLE", "IPHONEOS_DEPLOYMENT_TARGET", "MTL_ENABLE_DEBUG_INFO", "ONLY_ACTIVE_ARCH", "SWIFT_ACTIVE_COMPILATION_CONDITIONS", "SWIFT_OPTIMIZATION_LEVEL", "VERSIONING_SYSTEM", "VERSION_INFO_PREFIX", "DEFINES_MODULE", "DYLIB_COMPATIBILITY_VERSION", "DYLIB_CURRENT_VERSION","DYLIB_INSTALL_NAME_BASE","INFOPLIST_FILE","INSTALL_PATH", "LD_RUNPATH_SEARCH_PATHS", "PRODUCT_BUNDLE_IDENTIFIER", "PRODUCT_NAME", "SKIP_INSTALL", "BUILT_PRODUCTS_DIR", "FRAMEWORK_SEARCH_PATHS", "XMAN_ADD_FRAMEWORK_KEYS", "MACOSX_DEPLOYMENT_TARGET", "CLANG_WARN_NON_LITERAL_NULL_CONVERSION", "CLANG_WARN_OBJC_LITERAL_CONVERSION", "COMBINE_HIDPI_IMAGES", "FRAMEWORK_VERSION", "ENABLE_NS_ASSERTIONS", "VALIDATE_PRODUCT"];
let values = ["sourcecode.c.h", "sourcecode.c.objc", "wrapper.framework", "text.plist.strings", "sourcecode.cpp.objcpp", "sourcecode.cpp.cpp", "file.xib", "image.png", "wrapper.cfbundle", "archive.ar", "text.html", "text", "wrapper.pb-project", "folder", "folder.assetcatalog", "sourcecode.swift", "wrapper.application", "file.playground", "text.script.sh", "net.daringfireball.markdown", "text.plist.xml", "file.storyboard", "text.xcconfig", "wrapper.xcconfig", "wrapper.xcdatamodel", "file.strings"]
let totalKeys = keys + values
var final = content
for key in totalKeys {
let finalKey = "\"\(key)\""
final = final.replacingOccurrences(of: finalKey, with: key)
}
return final
}
private func dealLines(in content: String) -> String {
let lines = content.components(separatedBy: "\n")
let prefixed = ["path", "GCC_WARN_ABOUT_RETURN_TYPE", "GCC_WARN_UNINITIALIZED_AUTOS", "IPHONEOS_DEPLOYMENT_TARGET", "CLANG_WARN_UNGUARDED_AVAILABILITY", "CLANG_WARN_OBJC_ROOT_CLASS", "CLANG_WARN_DIRECT_OBJC_ISA_USAGE", "PRODUCT_BUNDLE_IDENTIFIER", "SWIFT_VERSION", "INFOPLIST_FILE", "CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION", "CreatedOnToolsVersion", "MACOSX_DEPLOYMENT_TARGET"]
var parsedLines: [String] = []
for line in lines {
let raw = line.trimmingCharacters(in: .whitespacesAndNewlines)
let needParseName = raw.hasPrefix("name = \"") && ( raw.hasSuffix(".storyboard\";") || raw.hasSuffix(".framework\";"))
let needParsePath = raw.hasPrefix("path = \"") && raw.hasSuffix("\";")
var needDeal = false
for key in prefixed {
let finalKey = "\(key) = \""
if needDeal == false {
needDeal = raw.hasSuffix(finalKey) && raw.hasSuffix("\";")
if needDeal {
break
}
}
}
if needParseName || needParsePath || needDeal {
var final = line
if raw.hasPrefix("path") || raw.hasPrefix("name") || raw.hasPrefix("INFOPLIST_FILE") {
let left = raw.replacingOccurrences(of: " = ", with: "")
if left.contains("+") || left.contains("-") || left.contains(" ") {
if raw.contains(" = \"") == false {
final = line.replacingOccurrences(of: " = ", with: " = \"")
final = line.replacingOccurrences(of: ";", with: "\";")
}
}
} else {
final = line.replacingOccurrences(of: "\"", with: "")
print("final:\(final)")
final = final.replacingOccurrences(of: "\"", with: "")
print("final after:\(final)")
}
parsedLines.append(final)
} else {
parsedLines.append(line)
}
}
return parsedLines.joined(separator: "\n")
}
}
extension PBXproj {
static func uniqueId() -> String {
let raw = UUID().uuidString.replacingOccurrences(of: "-", with: "")
let final = (raw as NSString).substring(to: 24)
return final
}
static func group(for name: String) -> [String : Any] {
var info: [String : Any] = [:]
info["children"] = [String]()
info["isa"] = "PBXGroup"
info["name"] = name
info["sourceTree"] = "<group>"
return info
}
}
| mit |
rockgarden/swift_language | Playground/FibonacciSequence.playground/Pages/FibonacciSequence.xcplaygroundpage/Contents.swift | 2 | 2673 | // Thinkful Playground
// Thinkful.com
// Fibonacci Sequence
// By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.
class FibonacciSequence {
let includesZero: Bool
let values: [UInt]
init(maxNumber: UInt, includesZero: Bool) {
self.includesZero = includesZero
if maxNumber == 0 && includesZero == false {
values = []
} else if maxNumber == 0 {
values = [0]
} else {
var sequence: [UInt] = [0,1,1]
var nextNumber: UInt = 2
while nextNumber <= maxNumber {
sequence.append(nextNumber)
let lastNumber = sequence.last!
let secondToLastNumber = sequence[sequence.count-2]
let (sum, didOverflow) = UInt.addWithOverflow(lastNumber, secondToLastNumber)
if didOverflow == true {
print("Overflow! The next number is too big to store in a UInt!")
break
}
nextNumber = sum
}
if includesZero == false {
sequence.remove(at: 0)
}
values = sequence
}
}
init(numberOfItemsInSequence: UInt, includesZero: Bool) {
self.includesZero = includesZero
if numberOfItemsInSequence == 0 {
values = []
} else if numberOfItemsInSequence == 1 {
if includesZero == true {
values = [0]
} else {
values = [1]
}
} else {
var sequence: [UInt]
if includesZero == true {
sequence = [0,1]
} else {
sequence = [1,1]
}
for _ in 2 ..< Int(numberOfItemsInSequence) {
let lastNumber = sequence.last!
let secondToLastNumber = sequence[sequence.count-2]
let (nextNumber, didOverflow) = UInt.addWithOverflow(lastNumber, secondToLastNumber)
if didOverflow == true {
print("Overflow! The next number is too big to store in a UInt!")
break
}
sequence.append(nextNumber)
}
values = sequence
}
}
}
let fibonacciSequence = FibonacciSequence(maxNumber:12345, includesZero: true)
print(fibonacciSequence.values)
let anotherSequence = FibonacciSequence(numberOfItemsInSequence: 113, includesZero: true)
print(anotherSequence.values)
UInt.max
| mit |
abbeycode/Carthage | Source/CarthageKit/Project.swift | 1 | 25270 | //
// Project.swift
// Carthage
//
// Created by Alan Rogers on 12/10/2014.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import Result
import ReactiveCocoa
/// Carthage’s bundle identifier.
public let CarthageKitBundleIdentifier = NSBundle(forClass: Project.self).bundleIdentifier!
/// ~/Library/Caches/org.carthage.CarthageKit/
private let CarthageUserCachesURL: NSURL = {
let URL: Result<NSURL, NSError> = try({ (error: NSErrorPointer) -> NSURL? in
NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.CachesDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: true, error: error)
})
let fallbackDependenciesURL = NSURL.fileURLWithPath("~/.carthage".stringByExpandingTildeInPath, isDirectory:true)!
switch URL {
case .Success:
NSFileManager.defaultManager().removeItemAtURL(fallbackDependenciesURL, error: nil)
case let .Failure(error):
NSLog("Warning: No Caches directory could be found or created: \(error.value.localizedDescription). (\(error.value))")
}
return URL.value?.URLByAppendingPathComponent(CarthageKitBundleIdentifier, isDirectory: true) ?? fallbackDependenciesURL
}()
/// The file URL to the directory in which downloaded release binaries will be
/// stored.
///
/// ~/Library/Caches/org.carthage.CarthageKit/binaries/
public let CarthageDependencyAssetsURL = CarthageUserCachesURL.URLByAppendingPathComponent("binaries", isDirectory: true)
/// The file URL to the directory in which cloned dependencies will be stored.
///
/// ~/Library/Caches/org.carthage.CarthageKit/dependencies/
public let CarthageDependencyRepositoriesURL = CarthageUserCachesURL.URLByAppendingPathComponent("dependencies", isDirectory: true)
/// The relative path to a project's Cartfile.
public let CarthageProjectCartfilePath = "Cartfile"
/// The relative path to a project's Cartfile.private.
public let CarthageProjectPrivateCartfilePath = "Cartfile.private"
/// The relative path to a project's Cartfile.resolved.
public let CarthageProjectResolvedCartfilePath = "Cartfile.resolved"
/// The text that needs to exist in a GitHub Release asset's name, for it to be
/// tried as a binary framework.
public let CarthageProjectBinaryAssetPattern = ".framework"
/// MIME types allowed for GitHub Release assets, for them to be considered as
/// binary frameworks.
public let CarthageProjectBinaryAssetContentTypes = [
"application/zip"
]
/// Describes an event occurring to or with a project.
public enum ProjectEvent {
/// The project is beginning to clone.
case Cloning(ProjectIdentifier)
/// The project is beginning a fetch.
case Fetching(ProjectIdentifier)
/// The project is being checked out to the specified revision.
case CheckingOut(ProjectIdentifier, String)
/// Any available binaries for the specified release of the project are
/// being downloaded. This may still be followed by `CheckingOut` event if
/// there weren't any viable binaries after all.
case DownloadingBinaries(ProjectIdentifier, String)
}
/// Represents a project that is using Carthage.
public final class Project {
/// File URL to the root directory of the project.
public let directoryURL: NSURL
/// The file URL to the project's Cartfile.
public var cartfileURL: NSURL {
return directoryURL.URLByAppendingPathComponent(CarthageProjectCartfilePath, isDirectory: false)
}
/// The file URL to the project's Cartfile.resolved.
public var resolvedCartfileURL: NSURL {
return directoryURL.URLByAppendingPathComponent(CarthageProjectResolvedCartfilePath, isDirectory: false)
}
/// Whether to prefer HTTPS for cloning (vs. SSH).
public var preferHTTPS = true
/// Whether to use submodules for dependencies, or just check out their
/// working directories.
public var useSubmodules = false
/// Whether to download binaries for dependencies, or just check out their
/// repositories.
public var useBinaries = false
/// Sends each event that occurs to a project underneath the receiver (or
/// the receiver itself).
public let projectEvents: Signal<ProjectEvent, NoError>
private let _projectEventsObserver: Signal<ProjectEvent, NoError>.Observer
public init(directoryURL: NSURL) {
precondition(directoryURL.fileURL)
let (signal, observer) = Signal<ProjectEvent, NoError>.pipe()
projectEvents = signal
_projectEventsObserver = observer
self.directoryURL = directoryURL
}
deinit {
sendCompleted(_projectEventsObserver)
}
private typealias CachedVersions = [ProjectIdentifier: [PinnedVersion]]
/// Caches versions to avoid expensive lookups, and unnecessary
/// fetching/cloning.
private var cachedVersions: CachedVersions = [:]
private let cachedVersionsQueue = ProducerQueue(name: "org.carthage.CarthageKit.Project.cachedVersionsQueue")
/// Attempts to load Cartfile or Cartfile.private from the given directory,
/// merging their dependencies.
public func loadCombinedCartfile() -> SignalProducer<Cartfile, CarthageError> {
let cartfileURL = directoryURL.URLByAppendingPathComponent(CarthageProjectCartfilePath, isDirectory: false)
let privateCartfileURL = directoryURL.URLByAppendingPathComponent(CarthageProjectPrivateCartfilePath, isDirectory: false)
let isNoSuchFileError = { (error: CarthageError) -> Bool in
switch error {
case let .ReadFailed(_, underlyingError):
if let underlyingError = underlyingError {
return underlyingError.domain == NSCocoaErrorDomain && underlyingError.code == NSFileReadNoSuchFileError
} else {
return false
}
default:
return false
}
}
let cartfile = SignalProducer.try {
return Cartfile.fromFile(cartfileURL)
}
|> catch { error -> SignalProducer<Cartfile, CarthageError> in
if isNoSuchFileError(error) && NSFileManager.defaultManager().fileExistsAtPath(privateCartfileURL.path!) {
return SignalProducer(value: Cartfile())
}
return SignalProducer(error: error)
}
let privateCartfile = SignalProducer.try {
return Cartfile.fromFile(privateCartfileURL)
}
|> catch { error -> SignalProducer<Cartfile, CarthageError> in
if isNoSuchFileError(error) {
return SignalProducer(value: Cartfile())
}
return SignalProducer(error: error)
}
return cartfile
|> zipWith(privateCartfile)
|> tryMap { (var cartfile, privateCartfile) -> Result<Cartfile, CarthageError> in
let duplicateDeps = cartfile.duplicateProjects().map { DuplicateDependency(project: $0, locations: ["\(CarthageProjectCartfilePath)"]) }
+ privateCartfile.duplicateProjects().map { DuplicateDependency(project: $0, locations: ["\(CarthageProjectPrivateCartfilePath)"]) }
+ duplicateProjectsInCartfiles(cartfile, privateCartfile).map { DuplicateDependency(project: $0, locations: ["\(CarthageProjectCartfilePath)", "\(CarthageProjectPrivateCartfilePath)"]) }
if duplicateDeps.count == 0 {
cartfile.appendCartfile(privateCartfile)
return .success(cartfile)
}
return .failure(.DuplicateDependencies(duplicateDeps))
}
}
/// Reads the project's Cartfile.resolved.
public func loadResolvedCartfile() -> SignalProducer<ResolvedCartfile, CarthageError> {
return SignalProducer.try {
var error: NSError?
let resolvedCartfileContents = NSString(contentsOfURL: self.resolvedCartfileURL, encoding: NSUTF8StringEncoding, error: &error)
if let resolvedCartfileContents = resolvedCartfileContents {
return ResolvedCartfile.fromString(resolvedCartfileContents as String)
} else {
return .failure(.ReadFailed(self.resolvedCartfileURL, error))
}
}
}
/// Writes the given Cartfile.resolved out to the project's directory.
public func writeResolvedCartfile(resolvedCartfile: ResolvedCartfile) -> Result<(), CarthageError> {
var error: NSError?
if resolvedCartfile.description.writeToURL(resolvedCartfileURL, atomically: true, encoding: NSUTF8StringEncoding, error: &error) {
return .success(())
} else {
return .failure(.WriteFailed(resolvedCartfileURL, error))
}
}
private let gitOperationQueue = ProducerQueue(name: "org.carthage.CarthageKit.Project.gitOperationQueue")
/// Clones the given dependency to the global repositories folder, or fetches
/// inside it if it has already been cloned.
///
/// Returns a signal which will send the URL to the repository's folder on
/// disk once cloning or fetching has completed.
private func cloneOrFetchDependency(project: ProjectIdentifier) -> SignalProducer<NSURL, CarthageError> {
return cloneOrFetchProject(project, preferHTTPS: self.preferHTTPS)
|> on(next: { event, _ in
sendNext(self._projectEventsObserver, event)
})
|> map { _, URL in URL }
|> takeLast(1)
|> startOnQueue(gitOperationQueue)
}
/// Sends all versions available for the given project.
///
/// This will automatically clone or fetch the project's repository as
/// necessary.
private func versionsForProject(project: ProjectIdentifier) -> SignalProducer<PinnedVersion, CarthageError> {
let fetchVersions = cloneOrFetchDependency(project)
|> flatMap(.Merge) { repositoryURL in listTags(repositoryURL) }
|> map { PinnedVersion($0) }
|> collect
|> on(next: { newVersions in
self.cachedVersions[project] = newVersions
})
|> flatMap(.Concat) { versions in SignalProducer(values: versions) }
return SignalProducer.try {
return .success(self.cachedVersions)
}
|> promoteErrors(CarthageError.self)
|> flatMap(.Merge) { versionsByProject -> SignalProducer<PinnedVersion, CarthageError> in
if let versions = versionsByProject[project] {
return SignalProducer(values: versions)
} else {
return fetchVersions
}
}
|> startOnQueue(cachedVersionsQueue)
}
/// Attempts to resolve a Git reference to a version.
private func resolvedGitReference(project: ProjectIdentifier, reference: String) -> SignalProducer<PinnedVersion, CarthageError> {
// We don't need the version list, but this takes care of
// cloning/fetching for us, while avoiding duplication.
return versionsForProject(project)
|> then(resolveReferenceInRepository(repositoryFileURLForProject(project), reference))
|> map { PinnedVersion($0) }
}
/// Attempts to determine the latest satisfiable version of the project's
/// Carthage dependencies.
///
/// This will fetch dependency repositories as necessary, but will not check
/// them out into the project's working directory.
public func updatedResolvedCartfile() -> SignalProducer<ResolvedCartfile, CarthageError> {
let resolver = Resolver(versionsForDependency: versionsForProject, cartfileForDependency: cartfileForDependency, resolvedGitReference: resolvedGitReference)
return loadCombinedCartfile()
|> flatMap(.Merge) { cartfile in resolver.resolveDependenciesInCartfile(cartfile) }
|> collect
|> map { ResolvedCartfile(dependencies: $0) }
}
/// Updates the dependencies of the project to the latest version. The
/// changes will be reflected in the working directory checkouts and
/// Cartfile.resolved.
public func updateDependencies() -> SignalProducer<(), CarthageError> {
return updatedResolvedCartfile()
|> tryMap { resolvedCartfile -> Result<(), CarthageError> in
return self.writeResolvedCartfile(resolvedCartfile)
}
|> then(checkoutResolvedDependencies())
}
/// Installs binaries for the given project, if available.
///
/// Sends a boolean indicating whether binaries were installed.
private func installBinariesForProject(project: ProjectIdentifier, atRevision revision: String) -> SignalProducer<Bool, CarthageError> {
return SignalProducer.try {
return .success(self.useBinaries)
}
|> flatMap(.Merge) { useBinaries -> SignalProducer<Bool, CarthageError> in
if !useBinaries {
return SignalProducer(value: false)
}
let checkoutDirectoryURL = self.directoryURL.URLByAppendingPathComponent(project.relativePath, isDirectory: true)
switch project {
case let .GitHub(repository):
return GitHubCredentials.loadFromGit()
|> flatMap(.Concat) { credentials in
return self.downloadMatchingBinariesForProject(project, atRevision: revision, fromRepository: repository, withCredentials: credentials)
|> catch { error in
if credentials == nil {
return SignalProducer(error: error)
}
return self.downloadMatchingBinariesForProject(project, atRevision: revision, fromRepository: repository, withCredentials: nil)
}
}
|> flatMap(.Concat, unzipArchiveToTemporaryDirectory)
|> flatMap(.Concat) { directoryURL in
return frameworksInDirectory(directoryURL)
|> flatMap(.Merge, self.copyFrameworkToBuildFolder)
|> on(completed: {
_ = NSFileManager.defaultManager().trashItemAtURL(checkoutDirectoryURL, resultingItemURL: nil, error: nil)
})
|> then(SignalProducer(value: directoryURL))
}
|> tryMap { (temporaryDirectoryURL: NSURL) -> Result<Bool, CarthageError> in
var error: NSError?
if NSFileManager.defaultManager().removeItemAtURL(temporaryDirectoryURL, error: &error) {
return .success(true)
} else {
return .failure(.WriteFailed(temporaryDirectoryURL, error))
}
}
|> concat(SignalProducer(value: false))
|> take(1)
case .Git:
return SignalProducer(value: false)
}
}
}
/// Downloads any binaries that may be able to be used instead of a
/// repository checkout.
///
/// Sends the URL to each downloaded zip, after it has been moved to a
/// less temporary location.
private func downloadMatchingBinariesForProject(project: ProjectIdentifier, atRevision revision: String, fromRepository repository: GitHubRepository, withCredentials credentials: GitHubCredentials?) -> SignalProducer<NSURL, CarthageError> {
return releaseForTag(revision, repository, credentials)
|> filter(binaryFrameworksCanBeProvidedByRelease)
|> on(next: { release in
sendNext(self._projectEventsObserver, ProjectEvent.DownloadingBinaries(project, release.nameWithFallback))
})
|> flatMap(.Concat) { release -> SignalProducer<NSURL, CarthageError> in
return SignalProducer(values: release.assets)
|> filter(binaryFrameworksCanBeProvidedByAsset)
|> flatMap(.Concat) { asset -> SignalProducer<NSURL, CarthageError> in
let fileURL = fileURLToCachedBinary(project, release, asset)
if NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!) {
return SignalProducer(value: fileURL)
} else {
return downloadAsset(asset, credentials)
|> flatMap(.Concat) { downloadURL in cacheDownloadedBinary(downloadURL, toURL: fileURL) }
}
}
}
}
/// Copies the framework at the given URL into the current project's build
/// folder.
///
/// Sends the URL to the framework after copying.
private func copyFrameworkToBuildFolder(frameworkURL: NSURL) -> SignalProducer<NSURL, CarthageError> {
return architecturesInFramework(frameworkURL)
|> filter { arch in arch.hasPrefix("arm") }
|> map { _ in SDK.iPhoneOS }
|> concat(SignalProducer(value: SDK.MacOSX))
|> take(1)
|> map { sdk in sdk.platform }
|> map { platform in self.directoryURL.URLByAppendingPathComponent(platform.relativePath, isDirectory: true) }
|> map { platformFolderURL in platformFolderURL.URLByAppendingPathComponent(frameworkURL.lastPathComponent!) }
|> flatMap(.Merge) { destinationFrameworkURL in copyFramework(frameworkURL, destinationFrameworkURL.URLByResolvingSymlinksInPath!) }
}
/// Checks out the given project into its intended working directory,
/// cloning it first if need be.
private func checkoutOrCloneProject(project: ProjectIdentifier, atRevision revision: String, submodulesByPath: [String: Submodule]) -> SignalProducer<(), CarthageError> {
let repositoryURL = repositoryFileURLForProject(project)
let workingDirectoryURL = directoryURL.URLByAppendingPathComponent(project.relativePath, isDirectory: true)
let checkoutSignal = SignalProducer.try { () -> Result<Submodule?, CarthageError> in
var submodule: Submodule?
if var foundSubmodule = submodulesByPath[project.relativePath] {
foundSubmodule.URL = repositoryURLForProject(project, preferHTTPS: self.preferHTTPS)
foundSubmodule.SHA = revision
submodule = foundSubmodule
} else if self.useSubmodules {
submodule = Submodule(name: project.relativePath, path: project.relativePath, URL: repositoryURLForProject(project, preferHTTPS: self.preferHTTPS), SHA: revision)
}
return .success(submodule)
}
|> flatMap(.Merge) { submodule -> SignalProducer<(), CarthageError> in
if let submodule = submodule {
return addSubmoduleToRepository(self.directoryURL, submodule, GitURL(repositoryURL.path!))
|> startOnQueue(self.gitOperationQueue)
} else {
return checkoutRepositoryToDirectory(repositoryURL, workingDirectoryURL, revision: revision)
}
}
|> on(started: {
sendNext(self._projectEventsObserver, .CheckingOut(project, revision))
})
return commitExistsInRepository(repositoryURL, revision: revision)
|> promoteErrors(CarthageError.self)
|> flatMap(.Merge) { exists -> SignalProducer<NSURL, CarthageError> in
if exists {
return .empty
} else {
return self.cloneOrFetchDependency(project)
}
}
|> then(checkoutSignal)
}
/// Checks out the dependencies listed in the project's Cartfile.resolved.
public func checkoutResolvedDependencies() -> SignalProducer<(), CarthageError> {
/// Determine whether the repository currently holds any submodules (if
/// it even is a repository).
let submodulesSignal = submodulesInRepository(self.directoryURL)
|> reduce([:]) { (var submodulesByPath: [String: Submodule], submodule) in
submodulesByPath[submodule.path] = submodule
return submodulesByPath
}
return loadResolvedCartfile()
|> zipWith(submodulesSignal)
|> flatMap(.Merge) { resolvedCartfile, submodulesByPath -> SignalProducer<(), CarthageError> in
return SignalProducer(values: resolvedCartfile.dependencies)
|> flatMap(.Merge) { dependency in
let project = dependency.project
let revision = dependency.version.commitish
return self.installBinariesForProject(project, atRevision: revision)
|> flatMap(.Merge) { installed in
if installed {
return .empty
} else {
return self.checkoutOrCloneProject(project, atRevision: revision, submodulesByPath: submodulesByPath)
}
}
}
}
|> then(.empty)
}
/// Attempts to build each Carthage dependency that has been checked out.
///
/// Returns a producer-of-producers representing each scheme being built.
public func buildCheckedOutDependenciesWithConfiguration(configuration: String, forPlatform platform: Platform?) -> SignalProducer<BuildSchemeProducer, CarthageError> {
return loadResolvedCartfile()
|> flatMap(.Merge) { resolvedCartfile in SignalProducer(values: resolvedCartfile.dependencies) }
|> flatMap(.Concat) { dependency -> SignalProducer<BuildSchemeProducer, CarthageError> in
let dependencyPath = self.directoryURL.URLByAppendingPathComponent(dependency.project.relativePath, isDirectory: true).path!
if !NSFileManager.defaultManager().fileExistsAtPath(dependencyPath) {
return .empty
}
return buildDependencyProject(dependency.project, self.directoryURL, withConfiguration: configuration, platform: platform)
}
}
}
/// Constructs a file URL to where the binary corresponding to the given
/// arguments should live.
private func fileURLToCachedBinary(project: ProjectIdentifier, release: GitHubRelease, asset: GitHubRelease.Asset) -> NSURL {
// ~/Library/Caches/org.carthage.CarthageKit/binaries/ReactiveCocoa/v2.3.1/1234-ReactiveCocoa.framework.zip
return CarthageDependencyAssetsURL.URLByAppendingPathComponent("\(project.name)/\(release.tag)/\(asset.ID)-\(asset.name)", isDirectory: false)
}
/// Caches the downloaded binary at the given URL, moving it to the other URL
/// given.
///
/// Sends the final file URL upon .success.
private func cacheDownloadedBinary(downloadURL: NSURL, toURL cachedURL: NSURL) -> SignalProducer<NSURL, CarthageError> {
return SignalProducer(value: cachedURL)
|> try { fileURL in
var error: NSError?
let parentDirectoryURL = fileURL.URLByDeletingLastPathComponent!
if NSFileManager.defaultManager().createDirectoryAtURL(parentDirectoryURL, withIntermediateDirectories: true, attributes: nil, error: &error) {
return .success(())
} else {
return .failure(.WriteFailed(parentDirectoryURL, error))
}
}
|> try { newDownloadURL in
if rename(downloadURL.fileSystemRepresentation, newDownloadURL.fileSystemRepresentation) == 0 {
return .success(())
} else {
return .failure(.TaskError(.POSIXError(errno)))
}
}
}
/// Sends the URL to each framework bundle found in the given directory.
private func frameworksInDirectory(directoryURL: NSURL) -> SignalProducer<NSURL, CarthageError> {
return NSFileManager.defaultManager().carthage_enumeratorAtURL(directoryURL, includingPropertiesForKeys: [ NSURLTypeIdentifierKey ], options: NSDirectoryEnumerationOptions.SkipsHiddenFiles | NSDirectoryEnumerationOptions.SkipsPackageDescendants, catchErrors: true)
|> map { enumerator, URL in URL }
|> filter { URL in
var typeIdentifier: AnyObject?
if URL.getResourceValue(&typeIdentifier, forKey: NSURLTypeIdentifierKey, error: nil) {
if let typeIdentifier: AnyObject = typeIdentifier {
if UTTypeConformsTo(typeIdentifier as! String, kUTTypeFramework) != 0 {
return true
}
}
}
return false
}
|> filter { URL in
// Skip nested frameworks
let frameworksInURL = URL.pathComponents?.filter { pathComponent in
return (pathComponent as? String)?.pathExtension == "framework"
}
return frameworksInURL?.count == 1
}
}
/// Determines whether a Release is a suitable candidate for binary frameworks.
private func binaryFrameworksCanBeProvidedByRelease(release: GitHubRelease) -> Bool {
return !release.draft && !release.prerelease && !release.assets.isEmpty
}
/// Determines whether a release asset is a suitable candidate for binary
/// frameworks.
private func binaryFrameworksCanBeProvidedByAsset(asset: GitHubRelease.Asset) -> Bool {
let name = asset.name as NSString
if name.rangeOfString(CarthageProjectBinaryAssetPattern).location == NSNotFound {
return false
}
return contains(CarthageProjectBinaryAssetContentTypes, asset.contentType)
}
/// Returns the file URL at which the given project's repository will be
/// located.
private func repositoryFileURLForProject(project: ProjectIdentifier) -> NSURL {
return CarthageDependencyRepositoriesURL.URLByAppendingPathComponent(project.name, isDirectory: true)
}
/// Loads the Cartfile for the given dependency, at the given version.
private func cartfileForDependency(dependency: Dependency<PinnedVersion>) -> SignalProducer<Cartfile, CarthageError> {
let repositoryURL = repositoryFileURLForProject(dependency.project)
return contentsOfFileInRepository(repositoryURL, CarthageProjectCartfilePath, revision: dependency.version.commitish)
|> catch { _ in .empty }
|> tryMap { Cartfile.fromString($0) }
}
/// Returns the URL that the project's remote repository exists at.
private func repositoryURLForProject(project: ProjectIdentifier, #preferHTTPS: Bool) -> GitURL {
switch project {
case let .GitHub(repository):
if preferHTTPS {
return repository.HTTPSURL
} else {
return repository.SSHURL
}
case let .Git(URL):
return URL
}
}
/// Clones the given project to the global repositories folder, or fetches
/// inside it if it has already been cloned.
///
/// Returns a signal which will send the operation type once started, and
/// the URL to where the repository's folder will exist on disk, then complete
/// when the operation completes.
public func cloneOrFetchProject(project: ProjectIdentifier, #preferHTTPS: Bool) -> SignalProducer<(ProjectEvent, NSURL), CarthageError> {
let repositoryURL = repositoryFileURLForProject(project)
return SignalProducer.try { () -> Result<GitURL, CarthageError> in
var error: NSError?
if !NSFileManager.defaultManager().createDirectoryAtURL(CarthageDependencyRepositoriesURL, withIntermediateDirectories: true, attributes: nil, error: &error) {
return .failure(.WriteFailed(CarthageDependencyRepositoriesURL, error))
}
return .success(repositoryURLForProject(project, preferHTTPS: preferHTTPS))
}
|> flatMap(.Merge) { remoteURL in
if NSFileManager.defaultManager().createDirectoryAtURL(repositoryURL, withIntermediateDirectories: false, attributes: nil, error: nil) {
// If we created the directory, we're now responsible for
// cloning it.
let cloneSignal = cloneRepository(remoteURL, repositoryURL)
return SignalProducer(value: (ProjectEvent.Cloning(project), repositoryURL))
|> concat(cloneSignal |> then(.empty))
} else {
let fetchSignal = fetchRepository(repositoryURL, remoteURL: remoteURL, refspec: "+refs/heads/*:refs/heads/*") /* lol syntax highlighting */
return SignalProducer(value: (ProjectEvent.Fetching(project), repositoryURL))
|> concat(fetchSignal |> then(.empty))
}
}
}
| mit |
jkolb/midnightbacon | MidnightBacon/Reddit/OAuth/OAuthAuthorizeResponse.swift | 1 | 3906 | //
// OAuthAuthorizeResponse.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// 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 FranticApparatus
import ModestProposal
public class OAuthAuthorizeResponse : CustomStringConvertible {
let code: String
let state: String
public init(code: String, state: String) {
self.code = code
self.state = state
}
public var description: String {
return "code: \(code) state: \(state)"
}
public class func parseFromQuery(redirectURL: NSURL, expectedState: String) throws -> OAuthAuthorizeResponse {
if let components = NSURLComponents(URL: redirectURL, resolvingAgainstBaseURL: true) {
if let query = components.percentEncodedQuery {
return try parse(query, expectedState: expectedState)
} else {
throw OAuthError.MissingURLQuery
}
} else {
throw OAuthError.MalformedURL
}
}
public class func parseFromFragment(redirectURL: NSURL, expectedState: String) throws -> OAuthAuthorizeResponse {
if let components = NSURLComponents(URL: redirectURL, resolvingAgainstBaseURL: true) {
if let fragment = components.percentEncodedFragment {
return try parse(fragment, expectedState: expectedState)
} else {
throw OAuthError.MissingURLFragment
}
} else {
throw OAuthError.MalformedURL
}
}
public class func parse(formEncoded: String, expectedState: String) throws -> OAuthAuthorizeResponse {
let components = NSURLComponents()
components.percentEncodedQuery = formEncoded
let queryItems = components.parameters ?? [:]
if queryItems.count == 0 { throw OAuthError.EmptyURLQuery }
if let errorString = queryItems["error"] {
if "access_denied" == errorString {
throw OAuthError.AccessDenied
} else if "unsupported_response_type" == errorString {
throw OAuthError.UnsupportedResponseType
} else if "invalid_scope" == errorString {
throw OAuthError.InvalidScope
} else if "invalid_request" == errorString {
throw OAuthError.InvalidRequest
} else {
throw OAuthError.UnexpectedError(errorString)
}
}
let state = queryItems["state"] ?? ""
if expectedState != state {
throw OAuthError.UnexpectedState(state)
}
let code = queryItems["code"] ?? ""
if code == "" {
throw OAuthError.MissingCode
}
return OAuthAuthorizeResponse(code: code, state: state)
}
}
| mit |
arturjaworski/Colorizer | Sources/colorizer/Extensions/NSColor.swift | 1 | 914 | import AppKit.NSColor
enum NSColorError: Error {
case wrongString
}
extension NSColor {
convenience init(hex: UInt32) {
let red = (hex >> 24) & 0xff
let green = (hex >> 16) & 0xff
let blue = (hex >> 8) & 0xff
let alpha = hex & 0xff
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha) / 255.0)
}
convenience init(hexString hex: String) throws {
var hex = hex.withoutPrefix("#").withoutPrefix("0x").uppercased()
if hex.characters.count == 6 {
hex = hex + "FF" // if there is no alpha
}
if hex.characters.count != 8 {
throw NSColorError.wrongString
}
var rgbValue: UInt32 = 0
Scanner(string: hex).scanHexInt32(&rgbValue)
self.init(hex: rgbValue)
}
} | mit |
mkaply/firefox-ios | Client/Frontend/Intro/IntroViewModelV2.swift | 6 | 1733 | /* 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 ViewControllerConsts {
struct PreferredSize {
static let IntroViewController = CGSize(width: 375, height: 667)
static let UpdateViewController = CGSize(width: 375, height: 667)
}
}
protocol CardTheme {
var theme: BuiltinThemeName { get }
}
extension CardTheme {
var theme: BuiltinThemeName {
return BuiltinThemeName(rawValue: ThemeManager.instance.current.name) ?? .normal
}
}
// MARK: Requires Work (Currently part of A/B test)
// Intro View Model V2 - This is suppose to be the main view model for the
// IntroView V2 however since we are running an onboarding A/B test
// and there might be a chance that some of the work related to views
// might be throw away hence keeping it super simple for IntroViewControllerV2
// This is another reason why we don't have a proper model either.
class IntroViewModelV2 {
// Internal vars
var screenType: OnboardingScreenType?
// private vars
private var onboardingResearch: OnboardingUserResearch?
// Initializer
init() {
onboardingResearch = OnboardingUserResearch()
// Case: Older user who has updated to a newer version and is not a first time user
// When user updates from a version of app which didn't have the
// user research onboarding screen type and is trying to Always Show the screen
// from Show Tour, we default to our .version1 of the screen
screenType = onboardingResearch?.onboardingScreenType ?? .versionV1
}
}
| mpl-2.0 |
chrisdoc/hubber | hubber/Reusable.swift | 1 | 300 | protocol Reusable: class {
static var reuseIdentifier: String { get }
}
extension Reusable {
static var reuseIdentifier: String {
// I like to use the class's name as an identifier
// so this makes a decent default value.
return String(describing: Self.self)
}
}
| mit |
ahoppen/swift | test/decl/ext/protocol.swift | 2 | 25184 | // RUN: %target-typecheck-verify-swift -warn-redundant-requirements
// ----------------------------------------------------------------------------
// Using protocol requirements from inside protocol extensions
// ----------------------------------------------------------------------------
protocol P1 {
@discardableResult
func reqP1a() -> Bool
}
extension P1 {
func extP1a() -> Bool { return !reqP1a() }
var extP1b: Bool {
return self.reqP1a()
}
var extP1c: Bool {
return extP1b && self.extP1a()
}
}
protocol P2 {
associatedtype AssocP2 : P1
func reqP2a() -> AssocP2
}
extension P2 {
func extP2a() -> AssocP2? { return reqP2a() }
func extP2b() {
self.reqP2a().reqP1a()
}
func extP2c() -> Self.AssocP2 { return extP2a()! }
}
protocol P3 {
associatedtype AssocP3 : P2
func reqP3a() -> AssocP3
}
extension P3 {
func extP3a() -> AssocP3.AssocP2 {
return reqP3a().reqP2a()
}
}
protocol P4 {
associatedtype AssocP4
func reqP4a() -> AssocP4
}
// ----------------------------------------------------------------------------
// Using generics from inside protocol extensions
// ----------------------------------------------------------------------------
func acceptsP1<T : P1>(_ t: T) { }
extension P1 {
func extP1d() { acceptsP1(self) }
}
func acceptsP2<T : P2>(_ t: T) { }
extension P2 {
func extP2acceptsP1() { acceptsP1(reqP2a()) }
func extP2acceptsP2() { acceptsP2(self) }
}
// Use of 'Self' as a return type within a protocol extension.
protocol SelfP1 {
associatedtype AssocType
}
protocol SelfP2 {
}
func acceptSelfP1<T, U : SelfP1>(_ t: T, _ u: U) -> T where U.AssocType == T {
return t
}
extension SelfP1 {
func tryAcceptSelfP1<Z : SelfP1>(_ z: Z)-> Self where Z.AssocType == Self {
return acceptSelfP1(self, z)
}
}
// ----------------------------------------------------------------------------
// Initializers in protocol extensions
// ----------------------------------------------------------------------------
protocol InitP1 {
init(string: String)
}
extension InitP1 {
init(int: Int) { self.init(string: "integer") }
}
struct InitS1 : InitP1 {
init(string: String) { }
}
class InitC1 : InitP1 {
required init(string: String) { }
}
func testInitP1() {
var is1 = InitS1(int: 5)
is1 = InitS1(string: "blah") // check type
_ = is1
var ic1 = InitC1(int: 5)
ic1 = InitC1(string: "blah") // check type
_ = ic1
}
// ----------------------------------------------------------------------------
// Subscript in protocol extensions
// ----------------------------------------------------------------------------
protocol SubscriptP1 {
func readAt(_ i: Int) -> String
func writeAt(_ i: Int, string: String)
}
extension SubscriptP1 {
subscript(i: Int) -> String {
get { return readAt(i) }
set(newValue) { writeAt(i, string: newValue) }
}
}
struct SubscriptS1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
struct SubscriptC1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
func testSubscriptP1(_ ss1: SubscriptS1, sc1: SubscriptC1,
i: Int, s: String) {
var ss1 = ss1
var sc1 = sc1
_ = ss1[i]
ss1[i] = s
_ = sc1[i]
sc1[i] = s
}
// ----------------------------------------------------------------------------
// Using protocol extensions on types that conform to the protocols.
// ----------------------------------------------------------------------------
struct S1 : P1 {
@discardableResult
func reqP1a() -> Bool { return true }
func once() -> Bool {
return extP1a() && extP1b
}
}
func useS1(_ s1: S1) -> Bool {
s1.reqP1a()
return s1.extP1a() && s1.extP1b
}
extension S1 {
func twice() -> Bool {
return extP1a() && extP1b
}
}
// ----------------------------------------------------------------------------
// Protocol extensions with redundant requirements
// ----------------------------------------------------------------------------
protocol FooProtocol {}
extension FooProtocol where Self: FooProtocol {} // expected-warning {{redundant conformance constraint 'Self' : 'FooProtocol'}}
protocol AnotherFooProtocol {}
protocol BazProtocol {}
extension AnotherFooProtocol where Self: BazProtocol, Self: AnotherFooProtocol {} // expected-warning {{redundant conformance constraint 'Self' : 'AnotherFooProtocol'}}
protocol AnotherBazProtocol {
associatedtype BazValue
}
extension AnotherBazProtocol where BazValue: AnotherBazProtocol {} // ok, does not warn because BazValue is not Self
// ----------------------------------------------------------------------------
// Protocol extensions with additional requirements
// ----------------------------------------------------------------------------
extension P4 where Self.AssocP4 : P1 {
// expected-note@-1 {{candidate requires that 'Int' conform to 'P1' (requirement specified as 'Self.AssocP4' : 'P1')}}
// expected-note@-2 {{candidate requires that 'S4aHelper' conform to 'P1' (requirement specified as 'Self.AssocP4' : 'P1')}}
func extP4a() {
acceptsP1(reqP4a())
}
}
struct S4aHelper { }
struct S4bHelper : P1 {
func reqP1a() -> Bool { return true }
}
struct S4a : P4 {
func reqP4a() -> S4aHelper { return S4aHelper() }
}
struct S4b : P4 {
func reqP4a() -> S4bHelper { return S4bHelper() }
}
struct S4c : P4 {
func reqP4a() -> Int { return 0 }
}
struct S4d : P4 {
func reqP4a() -> Bool { return false }
}
extension P4 where Self.AssocP4 == Int { // expected-note {{where 'Self.AssocP4' = 'Bool'}}
func extP4Int() { }
}
extension P4 where Self.AssocP4 == Bool {
// expected-note@-1 {{candidate requires that the types 'Int' and 'Bool' be equivalent (requirement specified as 'Self.AssocP4' == 'Bool')}}
// expected-note@-2 {{candidate requires that the types 'S4aHelper' and 'Bool' be equivalent (requirement specified as 'Self.AssocP4' == 'Bool')}}
func extP4a() -> Bool { return reqP4a() }
}
func testP4(_ s4a: S4a, s4b: S4b, s4c: S4c, s4d: S4d) {
s4a.extP4a() // expected-error{{no exact matches in call to instance method 'extP4a'}}
s4b.extP4a() // ok
s4c.extP4a() // expected-error{{no exact matches in call to instance method 'extP4a'}}
s4c.extP4Int() // okay
var b1 = s4d.extP4a() // okay, "Bool" version
b1 = true // checks type above
s4d.extP4Int() // expected-error{{referencing instance method 'extP4Int()' on 'P4' requires the types 'Bool' and 'Int' be equivalent}}
_ = b1
}
// ----------------------------------------------------------------------------
// Protocol extensions with a superclass constraint on Self
// ----------------------------------------------------------------------------
protocol ConformedProtocol {
typealias ConcreteConformanceAlias = Self
}
class BaseWithAlias<T> : ConformedProtocol {
typealias ConcreteAlias = T
struct NestedNominal {}
func baseMethod(_: T) {}
}
class DerivedWithAlias : BaseWithAlias<Int> {}
protocol ExtendedProtocol {
typealias AbstractConformanceAlias = Self
}
extension ExtendedProtocol where Self : DerivedWithAlias {
func f0(x: T) {} // expected-error {{cannot find type 'T' in scope}}
func f1(x: ConcreteAlias) {
let _: Int = x
baseMethod(x)
}
func f2(x: ConcreteConformanceAlias) {
let _: DerivedWithAlias = x
}
func f3(x: AbstractConformanceAlias) {
let _: DerivedWithAlias = x
}
func f4(x: NestedNominal) {}
}
// rdar://problem/21991470 & https://bugs.swift.org/browse/SR-5022
class NonPolymorphicInit {
init() { } // expected-note {{selected non-required initializer 'init()'}}
}
protocol EmptyProtocol { }
// The diagnostic is not very accurate, but at least we reject this.
extension EmptyProtocol where Self : NonPolymorphicInit {
init(string: String) {
self.init()
// expected-error@-1 {{constructing an object of class type 'Self' with a metatype value must use a 'required' initializer}}
}
}
// ----------------------------------------------------------------------------
// Using protocol extensions to satisfy requirements
// ----------------------------------------------------------------------------
protocol P5 {
func reqP5a()
}
// extension of P5 provides a witness for P6
extension P5 {
func reqP6a() { reqP5a() }
}
protocol P6 {
func reqP6a()
}
// S6a uses P5.reqP6a
struct S6a : P5 {
func reqP5a() { }
}
extension S6a : P6 { }
// S6b uses P5.reqP6a
struct S6b : P5, P6 {
func reqP5a() { }
}
// S6c uses P5.reqP6a
struct S6c : P6 {
}
extension S6c : P5 {
func reqP5a() { }
}
// S6d does not use P5.reqP6a
struct S6d : P6 {
func reqP6a() { }
}
extension S6d : P5 {
func reqP5a() { }
}
protocol P7 {
associatedtype P7Assoc
func getP7Assoc() -> P7Assoc
}
struct P7FromP8<T> { }
protocol P8 {
associatedtype P8Assoc
func getP8Assoc() -> P8Assoc
}
// extension of P8 provides conformance to P7Assoc
extension P8 {
func getP7Assoc() -> P7FromP8<P8Assoc> { return P7FromP8() }
}
// Okay, P7 requirements satisfied by P8
struct P8a : P8, P7 {
func getP8Assoc() -> Bool { return true }
}
func testP8a(_ p8a: P8a) {
var p7 = p8a.getP7Assoc()
p7 = P7FromP8<Bool>() // okay, check type of above
_ = p7
}
// Okay, P7 requirements explicitly specified
struct P8b : P8, P7 {
func getP7Assoc() -> Int { return 5 }
func getP8Assoc() -> Bool { return true }
}
func testP8b(_ p8b: P8b) {
var p7 = p8b.getP7Assoc()
p7 = 17 // check type of above
_ = p7
}
protocol PConforms1 {
}
extension PConforms1 {
func pc2() { } // expected-note{{candidate exactly matches}}
}
protocol PConforms2 : PConforms1, MakePC2Ambiguous {
func pc2() // expected-note{{multiple matching functions named 'pc2()' with type '() -> ()'}}
}
protocol MakePC2Ambiguous {
}
extension MakePC2Ambiguous {
func pc2() { } // expected-note{{candidate exactly matches}}
}
struct SConforms2a : PConforms2 { } // expected-error{{type 'SConforms2a' does not conform to protocol 'PConforms2'}}
struct SConforms2b : PConforms2 {
func pc2() { }
}
// Satisfying requirements via protocol extensions for fun and profit
protocol _MySeq { }
protocol MySeq : _MySeq {
associatedtype Generator : IteratorProtocol
func myGenerate() -> Generator
}
protocol _MyCollection : _MySeq {
associatedtype Index : Strideable
var myStartIndex : Index { get }
var myEndIndex : Index { get }
associatedtype _Element
subscript (i: Index) -> _Element { get }
}
protocol MyCollection : _MyCollection {
}
struct MyIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
struct OtherIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
extension _MyCollection {
func myGenerate() -> MyIndexedIterator<Self> {
return MyIndexedIterator(container: self, index: self.myEndIndex)
}
}
struct SomeCollection1 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
}
struct SomeCollection2 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
func myGenerate() -> OtherIndexedIterator<SomeCollection2> {
return OtherIndexedIterator(container: self, index: self.myEndIndex)
}
}
func testSomeCollections(_ sc1: SomeCollection1, sc2: SomeCollection2) {
var mig = sc1.myGenerate()
mig = MyIndexedIterator(container: sc1, index: sc1.myStartIndex)
_ = mig
var ig = sc2.myGenerate()
ig = MyIndexedIterator(container: sc2, index: sc2.myStartIndex) // expected-error {{cannot assign value of type 'MyIndexedIterator<SomeCollection2>' to type 'OtherIndexedIterator<SomeCollection2>'}}
_ = ig
}
public protocol PConforms3 {}
extension PConforms3 {
public var z: Int {
return 0
}
}
public protocol PConforms4 : PConforms3 {
var z: Int { get }
}
struct PConforms4Impl : PConforms4 {}
let pc4z = PConforms4Impl().z
// rdar://problem/20608438
protocol PConforms5 {
func f() -> Int
}
protocol PConforms6 : PConforms5 {}
extension PConforms6 {
func f() -> Int { return 42 }
}
func test<T: PConforms6>(_ x: T) -> Int { return x.f() }
struct PConforms6Impl : PConforms6 { }
// Extensions of a protocol that directly satisfy requirements (i.e.,
// default implementations hack N+1).
protocol PConforms7 {
func method()
var property: Int { get }
subscript (i: Int) -> Int { get }
}
extension PConforms7 {
func method() { }
var property: Int { return 5 }
subscript (i: Int) -> Int { return i }
}
struct SConforms7a : PConforms7 { }
protocol PConforms8 {
associatedtype Assoc
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms8 {
func method() -> Int { return 5 }
var property: Int { return 5 }
subscript (i: Int) -> Int { return i }
}
struct SConforms8a : PConforms8 { }
struct SConforms8b : PConforms8 {
func method() -> String { return "" }
var property: String { return "" }
subscript (i: String) -> String { return i }
}
func testSConforms8b() {
let s: SConforms8b.Assoc = "hello"
_ = s
}
struct SConforms8c : PConforms8 {
func method() -> String { return "" } // no warning in type definition
}
func testSConforms8c() {
let s: SConforms8c.Assoc = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'SConforms8c.Assoc' (aka 'Int')}}
_ = s
let i: SConforms8c.Assoc = 5
_ = i
}
protocol DefaultInitializable {
init()
}
extension String : DefaultInitializable { }
extension Int : DefaultInitializable { }
protocol PConforms9 {
associatedtype Assoc : DefaultInitializable // expected-note{{protocol requires nested type 'Assoc'}}
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms9 {
func method() -> Self.Assoc { return Assoc() }
var property: Self.Assoc { return Assoc() }
subscript (i: Self.Assoc) -> Self.Assoc { return Assoc() }
}
struct SConforms9a : PConforms9 { // expected-error{{type 'SConforms9a' does not conform to protocol 'PConforms9'}}
}
struct SConforms9b : PConforms9 {
typealias Assoc = Int
}
func testSConforms9b(_ s9b: SConforms9b) {
var p = s9b.property
p = 5
_ = p
}
struct SConforms9c : PConforms9 {
typealias Assoc = String
}
func testSConforms9c(_ s9c: SConforms9c) {
var p = s9c.property
p = "hello"
_ = p
}
struct SConforms9d : PConforms9 {
func method() -> Int { return 5 }
}
func testSConforms9d(_ s9d: SConforms9d) {
var p = s9d.property
p = 6
_ = p
}
protocol PConforms10 {}
extension PConforms10 {
func f() {}
}
protocol PConforms11 {
func f()
}
struct SConforms11 : PConforms10, PConforms11 {}
// ----------------------------------------------------------------------------
// Typealiases in protocol extensions.
// ----------------------------------------------------------------------------
// Basic support
protocol PTypeAlias1 {
associatedtype AssocType1
}
extension PTypeAlias1 {
typealias ArrayOfAssocType1 = [AssocType1]
}
struct STypeAlias1a: PTypeAlias1 {
typealias AssocType1 = Int
}
struct STypeAlias1b<T>: PTypeAlias1 {
typealias AssocType1 = T
}
func testPTypeAlias1() {
var a: STypeAlias1a.ArrayOfAssocType1 = []
a.append(1)
var b: STypeAlias1b<String>.ArrayOfAssocType1 = []
b.append("hello")
}
// Defaulted implementations to satisfy a requirement.
struct TypeAliasHelper<T> { }
protocol PTypeAliasSuper2 {
}
extension PTypeAliasSuper2 {
func foo() -> TypeAliasHelper<Self> { return TypeAliasHelper() }
}
protocol PTypeAliasSub2 : PTypeAliasSuper2 {
associatedtype Helper
func foo() -> Helper
}
struct STypeAliasSub2a : PTypeAliasSub2 { }
struct STypeAliasSub2b<T, U> : PTypeAliasSub2 { }
// ----------------------------------------------------------------------------
// Partial ordering of protocol extension members
// ----------------------------------------------------------------------------
// Partial ordering between members of protocol extensions and members
// of concrete types.
struct S1b : P1 {
func reqP1a() -> Bool { return true }
func extP1a() -> Int { return 0 }
}
func useS1b(_ s1b: S1b) {
var x = s1b.extP1a() // uses S1b.extP1a due to partial ordering
x = 5 // checks that "x" deduced to "Int" above
_ = x
var _: Bool = s1b.extP1a() // still uses P1.ext1Pa due to type annotation
}
// Partial ordering between members of protocol extensions for
// different protocols.
protocol PInherit1 { }
protocol PInherit2 : PInherit1 { }
protocol PInherit3 : PInherit2 { }
protocol PInherit4 : PInherit2 { }
extension PInherit1 {
func order1() -> Int { return 0 }
}
extension PInherit2 {
func order1() -> Bool { return true }
}
extension PInherit3 {
func order1() -> Double { return 1.0 }
}
extension PInherit4 {
func order1() -> String { return "hello" }
}
struct SInherit1 : PInherit1 { }
struct SInherit2 : PInherit2 { }
struct SInherit3 : PInherit3 { }
struct SInherit4 : PInherit4 { }
func testPInherit(_ si2 : SInherit2, si3: SInherit3, si4: SInherit4) {
var b1 = si2.order1() // PInherit2.order1
b1 = true // check that the above returned Bool
_ = b1
var d1 = si3.order1() // PInherit3.order1
d1 = 3.14159 // check that the above returned Double
_ = d1
var s1 = si4.order1() // PInherit4.order1
s1 = "hello" // check that the above returned String
_ = s1
// Other versions are still visible, since they may have different
// types.
b1 = si3.order1() // PInherit2.order1
var _: Int = si3.order1() // PInherit1.order1
}
protocol PConstrained1 {
associatedtype AssocTypePC1
}
extension PConstrained1 {
func pc1() -> Int { return 0 }
}
extension PConstrained1 where AssocTypePC1 : PInherit2 {
func pc1() -> Bool { return true }
}
extension PConstrained1 where Self.AssocTypePC1 : PInherit3 {
func pc1() -> String { return "hello" }
}
struct SConstrained1 : PConstrained1 {
typealias AssocTypePC1 = SInherit1
}
struct SConstrained2 : PConstrained1 {
typealias AssocTypePC1 = SInherit2
}
struct SConstrained3 : PConstrained1 {
typealias AssocTypePC1 = SInherit3
}
func testPConstrained1(_ sc1: SConstrained1, sc2: SConstrained2,
sc3: SConstrained3) {
var i = sc1.pc1() // PConstrained1.pc1
i = 17 // checks type of above
_ = i
var b = sc2.pc1() // PConstrained1 (with PInherit2).pc1
b = true // checks type of above
_ = b
var s = sc3.pc1() // PConstrained1 (with PInherit3).pc1
s = "hello" // checks type of above
_ = s
}
protocol PConstrained2 {
associatedtype AssocTypePC2
}
protocol PConstrained3 : PConstrained2 {
}
extension PConstrained2 where Self.AssocTypePC2 : PInherit1 {
func pc2() -> Bool { return true }
}
extension PConstrained3 {
func pc2() -> String { return "hello" }
}
struct SConstrained3a : PConstrained3 {
typealias AssocTypePC2 = Int
}
struct SConstrained3b : PConstrained3 {
typealias AssocTypePC2 = SInherit3
}
func testSConstrained3(_ sc3a: SConstrained3a, sc3b: SConstrained3b) {
var s = sc3a.pc2() // PConstrained3.pc2
s = "hello"
_ = s
_ = sc3b.pc2()
s = sc3b.pc2()
var _: Bool = sc3b.pc2()
}
extension PConstrained3 where AssocTypePC2 : PInherit1 { }
// Extending via a superclass constraint.
class Superclass {
func foo() { }
static func bar() { }
typealias Foo = Int
}
protocol PConstrained4 { }
extension PConstrained4 where Self : Superclass {
func testFoo() -> Foo {
foo()
self.foo()
return Foo(5)
}
static func testBar() {
bar()
self.bar()
}
}
protocol PConstrained5 { }
protocol PConstrained6 {
associatedtype Assoc
func foo()
}
protocol PConstrained7 { }
extension PConstrained6 {
var prop1: Int { return 0 }
var prop2: Int { return 0 } // expected-note{{'prop2' previously declared here}}
subscript (key: Int) -> Int { return key }
subscript (key: Double) -> Double { return key } // expected-note{{'subscript(_:)' previously declared here}}
}
extension PConstrained6 {
var prop2: Int { return 0 } // expected-error{{invalid redeclaration of 'prop2'}}
subscript (key: Double) -> Double { return key } // expected-error{{invalid redeclaration of 'subscript(_:)'}}
}
extension PConstrained6 where Assoc : PConstrained5 {
var prop1: Int { return 0 } // okay
var prop3: Int { return 0 } // expected-note{{'prop3' previously declared here}}
subscript (key: Int) -> Int { return key } // ok
subscript (key: String) -> String { return key } // expected-note{{'subscript(_:)' previously declared here}}
func foo() { } // expected-note{{'foo()' previously declared here}}
}
extension PConstrained6 where Assoc : PConstrained5 {
var prop3: Int { return 0 } // expected-error{{invalid redeclaration of 'prop3'}}
subscript (key: String) -> String { return key } // expected-error{{invalid redeclaration of 'subscript(_:)'}}
func foo() { } // expected-error{{invalid redeclaration of 'foo()'}}
}
extension PConstrained6 where Assoc : PConstrained7 {
var prop1: Int { return 0 } // okay
subscript (key: Int) -> Int { return key } // okay
func foo() { } // okay
}
extension PConstrained6 where Assoc == Int {
var prop4: Int { return 0 }
subscript (key: Character) -> Character { return key }
func foo() { } // okay
}
extension PConstrained6 where Assoc == Double {
var prop4: Int { return 0 } // okay
subscript (key: Character) -> Character { return key } // okay
func foo() { } // okay
}
// Interaction between RawRepresentable and protocol extensions.
public protocol ReallyRaw : RawRepresentable {
}
public extension ReallyRaw where RawValue: SignedInteger {
// expected-warning@+1 {{'public' modifier is redundant for initializer declared in a public extension}}
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
}
enum Foo : Int, ReallyRaw {
case a = 0
}
// ----------------------------------------------------------------------------
// Semantic restrictions
// ----------------------------------------------------------------------------
// Extension cannot have an inheritance clause.
protocol BadProto1 { }
protocol BadProto2 { }
extension BadProto1 : BadProto2 { } // expected-error{{extension of protocol 'BadProto1' cannot have an inheritance clause}}
extension BadProto2 {
struct S { } // expected-error{{type 'S' cannot be nested in protocol extension of 'BadProto2'}}
class C { } // expected-error{{type 'C' cannot be nested in protocol extension of 'BadProto2'}}
enum E { } // expected-error{{type 'E' cannot be nested in protocol extension of 'BadProto2'}}
}
extension BadProto1 {
func foo() { }
var prop: Int { return 0 }
subscript (i: Int) -> String {
return "hello"
}
}
// rdar://problem/20756244
protocol BadProto3 { }
typealias BadProto4 = BadProto3
extension BadProto4 { } // okay
typealias RawRepresentableAlias = RawRepresentable
extension RawRepresentableAlias { } // okay
extension AnyObject { } // expected-error{{non-nominal type 'AnyObject' cannot be extended}}
// Members of protocol extensions cannot be overridden.
// rdar://problem/21075287
class BadClass1 : BadProto1 {
func foo() { }
override var prop: Int { return 5 } // expected-error{{property does not override any property from its superclass}}
}
protocol BadProto5 {
associatedtype T1 // expected-note{{protocol requires nested type 'T1'}}
associatedtype T2 // expected-note{{protocol requires nested type 'T2'}}
associatedtype T3 // expected-note{{protocol requires nested type 'T3'}}
}
class BadClass5 : BadProto5 {} // expected-error{{type 'BadClass5' does not conform to protocol 'BadProto5'}}
typealias A = BadProto1
typealias B = BadProto1
extension A & B {} // expected-warning {{extending a protocol composition is not supported; extending 'BadProto1' instead}}
// Suppress near-miss warning for unlabeled initializers.
protocol P9 {
init(_: Int)
init(_: Double)
}
extension P9 {
init(_ i: Int) {
self.init(Double(i))
}
}
struct X9 : P9 {
init(_: Float) { }
}
extension X9 {
init(_: Double) { }
}
// Suppress near-miss warning for unlabeled subscripts.
protocol P10 {
subscript (_: Int) -> Int { get }
subscript (_: Double) -> Double { get }
}
extension P10 {
subscript(i: Int) -> Int {
return Int(self[Double(i)])
}
}
struct X10 : P10 {
subscript(f: Float) -> Float { return f }
}
extension X10 {
subscript(d: Double) -> Double { return d }
}
protocol Empty1 {}
protocol Empty2 {}
struct Concrete1 {}
extension Concrete1 : Empty1 & Empty2 {}
typealias TA = Empty1 & Empty2
struct Concrete2 {}
extension Concrete2 : TA {}
func f<T : Empty1 & Empty2>(_: T) {}
func useF() {
f(Concrete1())
f(Concrete2())
}
| apache-2.0 |
dreamsxin/swift | validation-test/compiler_crashers_fixed/01311-swift-completegenerictyperesolver-resolvedependentmembertype.swift | 11 | 538 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func a<T> {
struct A {
case .init() -> {
}
class func i(a)) -> (T, f<T> String)
deinit {
let h> {
if c {
}
}
}
case C) {
}
func a() -> T -> T.h =
| apache-2.0 |
MyHammer/MHAppIndexing | Example/MHAppIndexing/ViewController.swift | 1 | 3860 | //
// ViewController.swift
// MHAppIndexing
//
// Created by Frank Lienkamp on 02/03/2016.
// Copyright (c) 2016 Frank Lienkamp. All rights reserved.
//
import UIKit
import MHAppIndexing
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func indexCoreSpotlightObjects(sender: AnyObject) {
let exampleOne = self.exampleObject1()
let exampleTwo = self.exampleObject2()
let exampleThree = self.exampleObject3()
MHCoreSpotlightManager.sharedInstance.addObjectToSearchIndex(exampleOne)
MHCoreSpotlightManager.sharedInstance.addObjectToSearchIndex(exampleTwo)
MHCoreSpotlightManager.sharedInstance.addObjectToSearchIndex(exampleThree)
}
@IBAction func indexUserActivityObjects(sender: AnyObject) {
let exampleOne = self.exampleObject1()
let exampleTwo = self.exampleObject2()
let exampleThree = self.exampleObject3()
MHUserActivityManager.sharedInstance.addObjectToSearchIndex(exampleOne)
MHUserActivityManager.sharedInstance.addObjectToSearchIndex(exampleTwo)
MHUserActivityManager.sharedInstance.addObjectToSearchIndex(exampleThree)
}
/*
// MARK: example creation methods
*/
func exampleObject1() -> ExampleObject {
let example = ExampleObject()
example.mhDomainIdentifier = "com.some.what.here"
example.mhUniqueIdentifier = "1234567891"
example.mhTitle = "Lisa"
example.mhContentDescription = "This is a content description for Lisa"
example.mhKeywords = ["apple", "cherry", "banana"]
example.mhImageInfo = MHImageInfo(imageURL: NSURL(string: "https://upload.wikimedia.org/wikipedia/en/e/ec/Lisa_Simpson.png")!)
//UserActivity stuff
example.mhUserInfo = ["objectId":example.mhUniqueIdentifier]
example.mhEligibleForSearch = true
example.mhEligibleForPublicIndexing = true
example.mhEligibleForHandoff = false
example.mhWebpageURL = NSURL(string: "https://en.wikipedia.org/wiki/Lisa_Simpson")
return example
}
func exampleObject2() -> ExampleObject {
let example = ExampleObject()
example.mhDomainIdentifier = "com.some.what.here"
example.mhUniqueIdentifier = "987654321"
example.mhTitle = "Homer"
example.mhContentDescription = "Here is a content description for Homer"
example.mhKeywords = ["orange", "melon", "pineapple"]
example.mhImageInfo = MHImageInfo(bundleImageName: "homer", bundleImageType: "png")
//UserActivity stuff
example.mhUserInfo = ["objectId":example.mhUniqueIdentifier]
example.mhEligibleForSearch = true
example.mhEligibleForPublicIndexing = true
example.mhEligibleForHandoff = false
example.mhWebpageURL = NSURL(string: "https://en.wikipedia.org/wiki/Homer_Simpson")
return example
}
func exampleObject3() -> ExampleObject {
let example = ExampleObject()
example.mhDomainIdentifier = "com.some.what.here"
example.mhUniqueIdentifier = "47110822"
example.mhTitle = "Carl"
example.mhContentDescription = "Content description here for Carl"
example.mhKeywords = ["strawberry", "kiwi", "lemon"]
example.mhImageInfo = MHImageInfo(assetImageName: "carl")
//UserActivity stuff
example.mhUserInfo = ["objectId":example.mhUniqueIdentifier]
example.mhEligibleForSearch = true
example.mhEligibleForPublicIndexing = true
example.mhEligibleForHandoff = false
example.mhWebpageURL = NSURL(string: "https://en.wikipedia.org/wiki/Lenny_and_Carl#Carl_Carlson")
return example
}
}
| apache-2.0 |
emilstahl/swift | validation-test/compiler_crashers/24440-swift-typechecker-coercepatterntotype.swift | 9 | 280 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{struct d<A{struct B{func a<g{func b<T where g.e:P{
| apache-2.0 |
incetro/NIO | Tests/DAOTests/Realm/Plains/DialogPlainObject.swift | 1 | 457 | //
// DialogPlainObject.swift
// SDAO
//
// Created by incetro on 07/10/2019.
//
import SDAO
// MARK: - DialogPlainObject
struct DialogPlainObject: Plain {
// MARK: - Properties
var uniqueId: UniqueID {
return UniqueID(value: id)
}
/// Unique id
let id: Int
/// True if the dialog has been pinned
let isPinned: Bool
/// All available (stored) the dialog's messages
let messages: [MessagePlainObject]
}
| mit |
rnystrom/GitHawk | Classes/Notifications/NoNewNotificationsCell.swift | 1 | 6098 | //
// NoNewNotificationsCell.swift
// Freetime
//
// Created by Ryan Nystrom on 6/30/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SnapKit
protocol NoNewNotificationsCellReviewAccessDelegate: class {
func didTapReviewAccess(cell: NoNewNotificationsCell)
}
final class NoNewNotificationsCell: UICollectionViewCell {
private let emojiLabel = UILabel()
private let messageLabel = UILabel()
private let shadow = CAShapeLayer()
private let reviewGitHubAccessButton = UIButton()
private weak var reviewGitHubAccessDelegate: NoNewNotificationsCellReviewAccessDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
emojiLabel.isAccessibilityElement = false
emojiLabel.textAlignment = .center
emojiLabel.backgroundColor = .clear
emojiLabel.font = .systemFont(ofSize: 60)
contentView.addSubview(emojiLabel)
emojiLabel.snp.makeConstraints { make in
make.centerX.equalTo(contentView)
make.centerY.equalTo(contentView).offset(-Styles.Sizes.tableSectionSpacing)
}
shadow.fillColor = UIColor(white: 0, alpha: 0.05).cgColor
contentView.layer.addSublayer(shadow)
messageLabel.isAccessibilityElement = false
messageLabel.textAlignment = .center
messageLabel.backgroundColor = .clear
messageLabel.font = Styles.Text.body.preferredFont
messageLabel.textColor = Styles.Colors.Gray.light.color
contentView.addSubview(messageLabel)
messageLabel.snp.makeConstraints { make in
make.centerX.equalTo(emojiLabel)
make.top.equalTo(emojiLabel.snp.bottom).offset(Styles.Sizes.tableSectionSpacing)
make.height.greaterThanOrEqualTo(messageLabel.font.pointSize)
}
resetAnimations()
// CAAnimations will be removed from layers on background. restore when foregrounding.
NotificationCenter.default
.addObserver(self,
selector: #selector(resetAnimations),
name: .UIApplicationWillEnterForeground,
object: nil
)
contentView.isAccessibilityElement = true
contentView.accessibilityLabel = NSLocalizedString("You have no new notifications!", comment: "Inbox Zero Accessibility Label")
//configure reviewGitHubAcess button
reviewGitHubAccessButton.setTitle(NSLocalizedString("Missing notifications?", comment: ""), for: .normal)
reviewGitHubAccessButton.isAccessibilityElement = false
reviewGitHubAccessButton.titleLabel?.textAlignment = .center
reviewGitHubAccessButton.backgroundColor = .clear
reviewGitHubAccessButton.titleLabel?.font = Styles.Text.finePrint.preferredFont
reviewGitHubAccessButton.setTitleColor(Styles.Colors.Gray.light.color, for: .normal)
reviewGitHubAccessButton.addTarget(self, action: #selector(reviewGitHubAccessButtonTapped),
for: .touchUpInside)
contentView.addSubview(reviewGitHubAccessButton)
let buttonWidth = (reviewGitHubAccessButton.titleLabel?.intrinsicContentSize.width ?? 0) + Styles.Sizes.gutter
let buttonHeight = (reviewGitHubAccessButton.titleLabel?.intrinsicContentSize.height ?? 0) + Styles.Sizes.gutter
reviewGitHubAccessButton.snp.makeConstraints { make in
make.centerX.equalTo(messageLabel)
make.width.equalTo(buttonWidth)
make.height.equalTo(buttonHeight)
make.top.greaterThanOrEqualTo(messageLabel.snp.bottom)
make.bottom.equalTo(contentView.snp.bottom).offset(-Styles.Sizes.tableSectionSpacing).priority(.low)
make.bottom.lessThanOrEqualTo(contentView.snp.bottom)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layoutContentView()
let width: CGFloat = 30
let height: CGFloat = 12
let rect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
shadow.path = UIBezierPath(ovalIn: rect).cgPath
let bounds = contentView.bounds
shadow.bounds = rect
shadow.position = CGPoint(
x: bounds.width/2,
y: bounds.height/2 + 15
)
}
override func prepareForReuse() {
super.prepareForReuse()
resetAnimations()
}
override func didMoveToWindow() {
super.didMoveToWindow()
resetAnimations()
}
// MARK: Public API
func configure(
emoji: String,
message: String,
reviewGitHubAccessDelegate: NoNewNotificationsCellReviewAccessDelegate?
) {
emojiLabel.text = emoji
messageLabel.text = message
self.reviewGitHubAccessDelegate = reviewGitHubAccessDelegate
}
// MARK: Private API
@objc private func resetAnimations() {
guard trueUnlessReduceMotionEnabled else { return }
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let duration: TimeInterval = 1
let emojiBounce = CABasicAnimation(keyPath: "transform.translation.y")
emojiBounce.toValue = -10
emojiBounce.repeatCount = .greatestFiniteMagnitude
emojiBounce.autoreverses = true
emojiBounce.duration = duration
emojiBounce.timingFunction = timingFunction
emojiLabel.layer.add(emojiBounce, forKey: "nonewnotificationscell.emoji")
let shadowScale = CABasicAnimation(keyPath: "transform.scale")
shadowScale.toValue = 0.9
shadowScale.repeatCount = .greatestFiniteMagnitude
shadowScale.autoreverses = true
shadowScale.duration = duration
shadowScale.timingFunction = timingFunction
shadow.add(shadowScale, forKey: "nonewnotificationscell.shadow")
}
@objc func reviewGitHubAccessButtonTapped() {
reviewGitHubAccessDelegate?.didTapReviewAccess(cell: self)
}
}
| mit |
fredrikcollden/LittleMaestro | Category.swift | 1 | 215 | //
// Category.swift
// MaestroLevel
//
// Created by Fredrik Colldén on 2015-12-05.
// Copyright © 2015 Marie. All rights reserved.
//
import Foundation
class Category {
var levels: [LevelData] = []
}
| lgpl-3.0 |
aapierce0/MatrixClient | MatrixClient/JoinRoomViewController.swift | 1 | 1288 | /*
Copyright 2017 Avery Pierce
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Cocoa
protocol JoinRoomViewControllerDelegate : class {
func joinRoomViewControllerDidCancel(_ sender: JoinRoomViewController)
func joinRoomViewControllerDidSubmit(_ sender: JoinRoomViewController)
}
class JoinRoomViewController: NSViewController {
weak var delegate: JoinRoomViewControllerDelegate?
@IBOutlet weak var nameTextField: NSTextField!
var roomIdOrAlias: String { return nameTextField.stringValue }
@IBAction func cancelButtonClicked(_ sender: NSButton) {
delegate?.joinRoomViewControllerDidCancel(self)
}
@IBAction func createButtonClicked(_ sender: NSButton) {
delegate?.joinRoomViewControllerDidSubmit(self)
}
}
| apache-2.0 |
frootloops/swift | test/Sema/fixed_ambiguities/rdar27198177.swift | 1 | 496 | // RUN: %target-swift-frontend -emit-sil -verify %s -swift-version 4 | %FileCheck %s
let arr = ["A", "B", "C"]
let lazy: LazyMapCollection = arr.lazy.map { $0 }
// CHECK: function_ref @_T0s22LazyCollectionProtocolPsE6filters0a6FilterB0Vy8ElementsQzGSb7ElementQzcF : $@convention(method) <τ_0_0 where τ_0_0 : LazyCollectionProtocol> (@owned @callee_guaranteed (@in τ_0_0.Element) -> Bool, @in_guaranteed τ_0_0) -> @out LazyFilterCollection<τ_0_0.Elements>
_ = lazy.filter { $0 > "A" }.count
| apache-2.0 |
gssdromen/CedFilterView | FilterTest/Extension/ArrayExtension.swift | 1 | 446 | //
// ArrayExtension.swift
// FilterTest
//
// Created by cedricwu on 3/10/17.
// Copyright © 2017 Cedric Wu. All rights reserved.
//
import Foundation
extension Array {
mutating func removeElementAtIndexes(indexes: [Int]) {
var temp = [Element]()
for i in 0 ..< count {
if indexes.contains(i) {
} else {
temp.append(self[i])
}
}
self = temp
}
}
| gpl-3.0 |
tmandry/Swindler | Sources/Application.swift | 1 | 27570 | import AXSwift
import Cocoa
import PromiseKit
// MARK: - Application
/// A running application.
public final class Application {
internal let delegate: ApplicationDelegate
// An Application holds a strong reference to the State (and therefore the StateDelegate).
// It should not be held internally by delegates, or it would create a reference cycle.
internal var state_: State!
internal init(delegate: ApplicationDelegate, stateDelegate: StateDelegate) {
self.delegate = delegate
state_ = State(delegate: stateDelegate)
}
/// This initializer only fails if the StateDelegate has been destroyed.
internal convenience init?(delegate: ApplicationDelegate) {
guard let stateDelegate = delegate.stateDelegate else {
log.debug("Application for delegate \(delegate) failed to initialize because of "
+ "unreachable StateDelegate")
return nil
}
self.init(delegate: delegate, stateDelegate: stateDelegate)
}
public var processIdentifier: pid_t { return delegate.processIdentifier }
public var bundleIdentifier: String? { return delegate.bundleIdentifier }
/// The global Swindler state.
public var swindlerState: State { return state_ }
/// The known windows of the application. Windows on spaces that we haven't seen yet aren't
/// included.
public var knownWindows: [Window] {
return delegate.knownWindows.compactMap({ Window(delegate: $0) })
}
/// The main window of the application.
/// -Note: Setting this will bring the window forward to just below the main window of the
/// frontmost application.
public var mainWindow: WriteableProperty<OfOptionalType<Window>> { return delegate.mainWindow }
/// The focused (or key) window of the application, the one currently accepting keyboard input.
/// Usually the same as the main window, or one of its helper windows such as a file open
/// dialog.
///
/// -Note: Sometimes the focused "window" is a sheet and not a window (i.e. it has no title bar
/// and cannot be moved by the user). In that case the value will be nil.
public var focusedWindow: Property<OfOptionalType<Window>> { return delegate.focusedWindow }
/// Whether the application is hidden.
public var isHidden: WriteableProperty<OfType<Bool>> { return delegate.isHidden }
}
public func ==(lhs: Application, rhs: Application) -> Bool {
return lhs.delegate.equalTo(rhs.delegate)
}
extension Application: Equatable {}
extension Application: CustomStringConvertible {
public var description: String {
return "Application(\(String(describing: delegate)))"
}
}
protocol ApplicationDelegate: AnyObject {
var processIdentifier: pid_t! { get }
var bundleIdentifier: String? { get }
var stateDelegate: StateDelegate? { get }
var knownWindows: [WindowDelegate] { get }
var mainWindow: WriteableProperty<OfOptionalType<Window>>! { get }
var focusedWindow: Property<OfOptionalType<Window>>! { get }
var isHidden: WriteableProperty<OfType<Bool>>! { get }
func equalTo(_ other: ApplicationDelegate) -> Bool
}
// MARK: - OSXApplicationDelegate
/// Implements ApplicationDelegate using the AXUIElement API.
final class OSXApplicationDelegate<
UIElement,
ApplicationElement: ApplicationElementType,
Observer: ObserverType
>: ApplicationDelegate
where Observer.UIElement == UIElement, ApplicationElement.UIElement == UIElement {
typealias Object = Application
typealias WinDelegate = OSXWindowDelegate<UIElement, ApplicationElement, Observer>
weak var stateDelegate: StateDelegate?
fileprivate weak var notifier: EventNotifier?
internal let axElement: UIElement // internal for testing only
internal var observer: Observer! // internal for testing only
fileprivate var windows: [WinDelegate] = []
// Used internally for deferring code until an OSXWindowDelegate has been initialized for a
// given UIElement.
fileprivate var newWindowHandler = NewWindowHandler<UIElement>()
fileprivate var initialized: Promise<Void>!
var mainWindow: WriteableProperty<OfOptionalType<Window>>!
var focusedWindow: Property<OfOptionalType<Window>>!
var isHidden: WriteableProperty<OfType<Bool>>!
var processIdentifier: pid_t!
lazy var runningApplication: NSRunningApplication =
NSRunningApplication(processIdentifier: self.processIdentifier)!
lazy var bundleIdentifier: String? =
self.runningApplication.bundleIdentifier
var knownWindows: [WindowDelegate] {
return windows.map({ $0 as WindowDelegate })
}
/// Initializes the object and returns it as a Promise that resolves once it's ready.
static func initialize(
axElement: ApplicationElement,
stateDelegate: StateDelegate,
notifier: EventNotifier
) -> Promise<OSXApplicationDelegate> {
return firstly { () -> Promise<OSXApplicationDelegate> in // capture thrown errors in promise chain
let appDelegate = try OSXApplicationDelegate(axElement, stateDelegate, notifier)
return appDelegate.initialized.map { appDelegate }
}
}
private init(_ axElement: ApplicationElement,
_ stateDelegate: StateDelegate,
_ notifier: EventNotifier) throws {
// TODO: filter out applications by activation policy
self.axElement = axElement.toElement
self.stateDelegate = stateDelegate
self.notifier = notifier
processIdentifier = try axElement.pid()
let notifications: [AXNotification] = [
.windowCreated,
.mainWindowChanged,
.focusedWindowChanged,
.applicationHidden,
.applicationShown
]
// Watch for notifications on app asynchronously.
let appWatched = watchApplicationElement(notifications)
// Get the list of windows asynchronously (after notifications are subscribed so we can't
// miss one).
let windowsFetched = fetchWindows(after: appWatched)
// Create a promise for the attribute dictionary we'll get from fetchAttributes.
let (attrsFetched, attrsSeal) = Promise<[AXSwift.Attribute: Any]>.pending()
// Some properties can't initialize until we fetch the windows. (WindowPropertyAdapter)
let initProperties =
PromiseKit.when(fulfilled: attrsFetched, windowsFetched)
.map { fetchedAttrs, _ in fetchedAttrs }
// Configure properties.
mainWindow = WriteableProperty(
MainWindowPropertyDelegate(axElement,
windowFinder: self,
windowDelegate: WinDelegate.self,
initProperties),
withEvent: ApplicationMainWindowChangedEvent.self,
receivingObject: Application.self,
notifier: self)
focusedWindow = Property(
WindowPropertyAdapter(AXPropertyDelegate(axElement, .focusedWindow, initProperties),
windowFinder: self,
windowDelegate: WinDelegate.self),
withEvent: ApplicationFocusedWindowChangedEvent.self,
receivingObject: Application.self,
notifier: self)
isHidden = WriteableProperty(
AXPropertyDelegate(axElement, .hidden, initProperties),
withEvent: ApplicationIsHiddenChangedEvent.self,
receivingObject: Application.self,
notifier: self)
let properties: [PropertyType] = [
mainWindow,
focusedWindow,
isHidden
]
let attributes: [Attribute] = [
.mainWindow,
.focusedWindow,
.hidden
]
// Fetch attribute values, after subscribing to notifications so there are no gaps.
fetchAttributes(attributes,
forElement: axElement,
after: appWatched,
seal: attrsSeal)
initialized = initializeProperties(properties).asVoid()
}
/// Called during initialization to set up an observer on the application element.
fileprivate func watchApplicationElement(_ notifications: [AXNotification]) -> Promise<Void> {
do {
weak var weakSelf = self
observer = try Observer(processID: processIdentifier, callback: { o, e, n in
weakSelf?.handleEvent(observer: o, element: e, notification: n)
})
} catch {
return Promise(error: error)
}
return Promise.value(()).done(on: .global()) {
for notification in notifications {
try traceRequest(self.axElement, "addNotification", notification) {
try self.observer.addNotification(notification, forElement: self.axElement)
}
}
}
}
func onSpaceChanged() -> Promise<Void> {
return fetchWindows(after: .value(())).then { _ in
return when(resolved: [
self.mainWindow.refresh().asVoid(),
self.focusedWindow.refresh().asVoid(),
]).asVoid()
}
}
/// Called during initialization to fetch a list of window elements and initialize window
/// delegates for them.
fileprivate func fetchWindows(after promise: Promise<Void>) -> Promise<Void> {
return promise.map(on: .global()) { () -> [UIElement]? in
// Fetch the list of window elements.
try traceRequest(self.axElement, "arrayAttribute", AXSwift.Attribute.windows) {
return try self.axElement.arrayAttribute(.windows)
}
}.then { maybeWindowElements -> Promise<Void> in
guard let windowElements = maybeWindowElements else {
throw OSXDriverError.missingAttribute(attribute: .windows,
onElement: self.axElement)
}
// Initialize OSXWindowDelegates from the window elements.
let windowPromises = windowElements.map({ windowElement in
self.createWindowForElementIfNotExists(windowElement)
})
return successes(windowPromises, onError: { index, error in
// Log any errors we encounter, but don't fail.
let windowElement = windowElements[index]
log.debug({
let description: String =
(try? windowElement.attribute(.description) ?? "") ?? ""
return "Couldn't initialize window for element \(windowElement) "
+ "(\(description)) of \(self): \(error)"
}())
}).asVoid()
}
}
var initializingWindows: [(UIElement, Promise<WinDelegate?>)] = []
/// Initializes an OSXWindowDelegate for the given axElement and adds it to `windows`, then
/// calls newWindowHandler handlers for that window, if any. If the window has already been
/// added, does nothing, and the returned promise resolves to nil.
fileprivate func createWindowForElementIfNotExists(_ axElement: UIElement)
-> Promise<WinDelegate?> {
guard let systemScreens = stateDelegate?.systemScreens else {
return .value(nil)
}
// Defer to the existing promise if the window is being initialized.
if let entry = initializingWindows.first(where: { $0.0 == axElement }) {
return entry.1.map({ _ in nil })
}
// Early return if the element already exists.
if self.windows.contains(where: { $0.axElement == axElement }) {
return .value(nil)
}
let promise = WinDelegate.initialize(
appDelegate: self, notifier: notifier, axElement: axElement, observer: observer,
systemScreens: systemScreens
).map { windowDelegate in
self.initializingWindows.removeAll(where: { $0.0 == axElement })
// This check needs to happen (again) here, because it's possible
// (though rare) to call this method from two different places
// (fetchWindows and onWindowCreated) before initialization of
// either one is complete.
if self.windows.contains(where: { $0.axElement == axElement }) {
return nil
}
self.windows.append(windowDelegate)
self.newWindowHandler.windowCreated(axElement)
return windowDelegate
}.recover { error -> Promise<WinDelegate?> in
// If this initialization of WinDelegate failed, the window is somehow invalid and we
// won't be seeing it again. Here we assume that if there were other initializations
// requested, they won't succeed either.
self.newWindowHandler.removeAllForUIElement(axElement)
throw error
}
initializingWindows.append((axElement, promise))
return promise
}
func equalTo(_ rhs: ApplicationDelegate) -> Bool {
if let other = rhs as? OSXApplicationDelegate {
return axElement == other.axElement
} else {
return false
}
}
}
/// Event handlers
extension OSXApplicationDelegate {
fileprivate func handleEvent(observer: Observer.Context,
element: UIElement,
notification: AXSwift.AXNotification) {
assert(Thread.current.isMainThread)
log.trace("Received \(notification) on \(element)")
switch notification {
case .windowCreated:
onWindowCreated(element)
case .mainWindowChanged:
onWindowTypePropertyChanged(mainWindow, element: element)
case .focusedWindowChanged:
onWindowTypePropertyChanged(focusedWindow, element: element)
case .applicationShown, .applicationHidden:
isHidden.refresh()
default:
onWindowLevelEvent(notification, windowElement: element)
}
}
fileprivate func onWindowCreated(_ windowElement: UIElement) {
addWindowElement(windowElement).catch { error in
log.trace("Could not watch window element on \(self): \(error)")
}
}
// Also used by FakeSwindler.
internal func addWindowElement(_ windowElement: UIElement) -> Promise<WinDelegate?> {
return firstly {
createWindowForElementIfNotExists(windowElement)
}.map { windowDelegate in
guard let windowDelegate = windowDelegate,
let window = Window(delegate: windowDelegate)
else { return nil }
self.notifier?.notify(WindowCreatedEvent(external: true, window: window))
return windowDelegate
}
}
/// Does special handling for updating of properties that hold windows (mainWindow,
/// focusedWindow).
fileprivate func onWindowTypePropertyChanged(_ property: Property<OfOptionalType<Window>>,
element: UIElement) {
if element == axElement {
// Was passed the application (this means there is no main/focused window); we can
// refresh immediately.
property.refresh()
} else if windows.contains(where: { $0.axElement == element }) {
// Was passed an already-initialized window; we can refresh immediately.
property.refresh()
} else {
// We don't know about the element that has been passed. Wait until the window is
// initialized.
addWindowElement(element)
.done { _ in property.refresh() }
.recover { err in
log.error("Error while updating window property: \(err)")
}
// In some cases, the element is actually IS the application element, but equality
// checks inexplicably return false. (This has been observed for Finder.) In this case
// we will never see a new window for this element. Asynchronously check the element
// role to handle this case.
checkIfWindowPropertyElementIsActuallyApplication(element, property: property)
}
}
fileprivate func checkIfWindowPropertyElementIsActuallyApplication(
_ element: UIElement,
property: Property<OfOptionalType<Window>>
) {
Promise.value(()).map(on: .global()) { () -> Role? in
guard let role: String = try element.attribute(.role) else { return nil }
return Role(rawValue: role)
}.done { role in
if role == .application {
// There is no main window; we can refresh immediately.
property.refresh()
// Remove the handler that will never be called.
self.newWindowHandler.removeAllForUIElement(element)
}
}.catch { error in
switch error {
case AXError.invalidUIElement:
// The window is already gone.
property.refresh()
self.newWindowHandler.removeAllForUIElement(element)
default:
// TODO: Retry on timeout
// Just refresh and hope for the best. Leave the handler in case the element does
// show up again.
property.refresh()
log.warn("Received MainWindowChanged on unknown element \(element), then \(error) "
+ "when trying to read its role")
}
}
// _______________________________
// < Now that's a long method name >
// -------------------------------
// \ . .
// \ / `. .' "
// \ .---. < > < > .---.
// \ | \ \ - ~ ~ - / / |
// _____ ..-~ ~-..-~
// | | \~~~\.' `./~~~/
// --------- \__/ \__/
// .' O \ / / \ "
// (_____, `._.' | } \/~~~/
// `----. / } | / \__/
// `-. | / | / `. ,~~|
// ~-.__| /_ - ~ ^| /- _ `..-'
// | / | / ~-. `-. _ _ _
// |_____| |_____| ~ - . _ _ _ _ _>
}
fileprivate func onWindowLevelEvent(_ notification: AXSwift.AXNotification,
windowElement: UIElement) {
func handleEvent(_ windowDelegate: WinDelegate) {
windowDelegate.handleEvent(notification, observer: observer)
if .uiElementDestroyed == notification {
// Remove window.
windows = windows.filter({ !$0.equalTo(windowDelegate) })
guard let window = Window(delegate: windowDelegate) else { return }
notifier?.notify(WindowDestroyedEvent(external: true, window: window))
}
}
if let windowDelegate = findWindowDelegateByElement(windowElement) {
handleEvent(windowDelegate)
} else {
log.debug("Notification \(notification) on unknown element \(windowElement), deferring")
newWindowHandler.performAfterWindowCreatedForElement(windowElement) {
if let windowDelegate = self.findWindowDelegateByElement(windowElement) {
handleEvent(windowDelegate)
} else {
// Window was already destroyed.
log.debug("Deferred notification \(notification) on window element "
+ "\(windowElement) never reached delegate")
}
}
}
}
fileprivate func findWindowDelegateByElement(_ axElement: UIElement) -> WinDelegate? {
return windows.filter({ $0.axElement == axElement }).first
}
}
extension OSXApplicationDelegate: PropertyNotifier {
func notify<Event: PropertyEventType>(_ event: Event.Type,
external: Bool,
oldValue: Event.PropertyType,
newValue: Event.PropertyType)
where Event.Object == Application {
guard let application = Application(delegate: self) else { return }
notifier?.notify(
Event(external: external, object: application, oldValue: oldValue, newValue: newValue)
)
}
func notifyInvalid() {
log.debug("Application invalidated: \(self)")
// TODO:
}
}
extension OSXApplicationDelegate: CustomStringConvertible {
var description: String {
do {
let pid = try self.axElement.pid()
if let app = NSRunningApplication(processIdentifier: pid),
let bundle = app.bundleIdentifier {
return bundle
}
return "pid=\(pid)"
} catch {
return "Invalid"
}
}
}
// MARK: Support
/// Stores internal new window handlers for OSXApplicationDelegate.
private struct NewWindowHandler<UIElement: Equatable> {
fileprivate var handlers: [HandlerType<UIElement>] = []
mutating func performAfterWindowCreatedForElement(_ windowElement: UIElement,
handler: @escaping () -> Void) {
assert(Thread.current.isMainThread)
handlers.append(HandlerType(windowElement: windowElement, handler: handler))
}
mutating func removeAllForUIElement(_ windowElement: UIElement) {
assert(Thread.current.isMainThread)
handlers = handlers.filter({ $0.windowElement != windowElement })
}
mutating func windowCreated(_ windowElement: UIElement) {
assert(Thread.current.isMainThread)
handlers.filter({ $0.windowElement == windowElement }).forEach { entry in
entry.handler()
}
removeAllForUIElement(windowElement)
}
}
private struct HandlerType<UIElement> {
let windowElement: UIElement
let handler: () -> Void
}
// MARK: PropertyDelegates
/// Used by WindowPropertyAdapter to match a UIElement to a Window object.
protocol WindowFinder: AnyObject {
// This would be more elegantly implemented by passing the list of delegates with every refresh
// request, but currently we don't have a way of piping that through.
associatedtype UIElement: UIElementType
func findWindowByElement(_ element: UIElement) -> Window?
}
extension OSXApplicationDelegate: WindowFinder {
func findWindowByElement(_ element: UIElement) -> Window? {
if let windowDelegate = findWindowDelegateByElement(element) {
return Window(delegate: windowDelegate)
} else {
return nil
}
}
}
protocol OSXDelegateType {
associatedtype UIElement: UIElementType
var axElement: UIElement { get }
var isValid: Bool { get }
}
extension OSXWindowDelegate: OSXDelegateType {}
/// Custom PropertyDelegate for the mainWindow property.
private final class MainWindowPropertyDelegate<
AppElement: ApplicationElementType,
WinFinder: WindowFinder,
WinDelegate: OSXDelegateType
>: PropertyDelegate
where WinFinder.UIElement == WinDelegate.UIElement {
typealias T = Window
typealias UIElement = WinFinder.UIElement
let readDelegate: WindowPropertyAdapter<AXPropertyDelegate<UIElement, AppElement>,
WinFinder, WinDelegate>
init(_ appElement: AppElement,
windowFinder: WinFinder,
windowDelegate: WinDelegate.Type,
_ initPromise: Promise<[Attribute: Any]>) {
readDelegate = WindowPropertyAdapter(
AXPropertyDelegate(appElement, .mainWindow, initPromise),
windowFinder: windowFinder,
windowDelegate: windowDelegate)
}
func initialize() -> Promise<Window?> {
return readDelegate.initialize()
}
func readValue() throws -> Window? {
return try readDelegate.readValue()
}
func writeValue(_ newValue: Window) throws {
// Extract the element from the window delegate.
guard let winDelegate = newValue.delegate as? WinDelegate else {
throw PropertyError.illegalValue
}
// Check early to see if the element is still valid. If it becomes invalid after this check,
// the same error will get thrown, it will just take longer.
guard winDelegate.isValid else {
throw PropertyError.illegalValue
}
// Note: This is happening on a background thread, so only properties that don't change
// should be accessed (the axElement).
// To set the main window, we have to access the .main attribute of the window element and
// set it to true.
let writeDelegate = AXPropertyDelegate<Bool, UIElement>(
winDelegate.axElement, .main, Promise.value([:])
)
try writeDelegate.writeValue(true)
}
}
/// Converts a UIElement attribute into a readable Window property.
private final class WindowPropertyAdapter<
Delegate: PropertyDelegate,
WinFinder: WindowFinder,
WinDelegate: OSXDelegateType
>: PropertyDelegate
where Delegate.T == WinFinder.UIElement, WinFinder.UIElement == WinDelegate.UIElement {
typealias T = Window
let delegate: Delegate
weak var windowFinder: WinFinder?
init(_ delegate: Delegate, windowFinder: WinFinder, windowDelegate: WinDelegate.Type) {
self.delegate = delegate
self.windowFinder = windowFinder
}
func readValue() throws -> Window? {
guard let element = try delegate.readValue() else {
return nil
}
let window = findWindowByElement(element)
if window == nil {
// This can happen if, for instance, the window was destroyed since the refresh was
// requested.
log.debug("While updating property value, could not find window matching element: "
+ String(describing: element))
}
return window
}
func writeValue(_ newValue: Window) throws {
// If we got here, a property is wrongly configured.
fatalError("Writing directly to an \"object\" property is not supported by the AXUIElement "
+ "API")
}
func initialize() -> Promise<Window?> {
return delegate.initialize().map { maybeElement in
guard let element = maybeElement else {
return nil
}
return self.findWindowByElement(element)
}
}
fileprivate func findWindowByElement(_ element: Delegate.T) -> Window? {
// Avoid using locks by forcing calls out to `windowFinder` to happen on the main thead.
var window: Window?
if Thread.current.isMainThread {
window = windowFinder?.findWindowByElement(element)
} else {
DispatchQueue.main.sync {
window = self.windowFinder?.findWindowByElement(element)
}
}
return window
}
}
| mit |
geeven/EveryWeekSwiftDemo | PictureCarousel/PictureCarousel/LoopView/GDLoopViewCell.swift | 1 | 851 | //
// GDLoopViewCell.swift
// PictureCarousel
//
// Created by Geeven on 16/3/6.
// Copyright © 2016年 Geeven. All rights reserved.
//
import UIKit
class GDLoopViewCell: UICollectionViewCell {
//MARK: - 生命周期方法
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - 懒加载
/// 图像视图
private lazy var imageView:UIImageView = UIImageView(frame:self.bounds)
//MARK: - 私有属性
/// url
var url:NSURL? {
didSet {
let data = NSData(contentsOfURL: url!)
imageView.image = UIImage(data: data!)
}
}
}
| mit |
iZhang/travel-architect | main/Focus Square/FocusSquare.swift | 1 | 18872 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
SceneKit node giving the user hints about the status of ARKit world tracking.
*/
import Foundation
import ARKit
/**
An `SCNNode` which is used to provide uses with visual cues about the status of ARKit world tracking.
- Tag: FocusSquare
*/
class FocusSquare: SCNNode {
// MARK: - Types
enum State: Equatable {
case initializing
case detecting(hitTestResult: ARHitTestResult, camera: ARCamera?)
}
// MARK: - Configuration Properties
// Original size of the focus square in meters.
static let size: Float = 0.17
// Thickness of the focus square lines in meters.
static let thickness: Float = 0.018
// Scale factor for the focus square when it is closed, w.r.t. the original size.
static let scaleForClosedSquare: Float = 0.97
// Side length of the focus square segments when it is open (w.r.t. to a 1x1 square).
static let sideLengthForOpenSegments: CGFloat = 0.2
// Duration of the open/close animation
static let animationDuration = 0.7
static let primaryColor = #colorLiteral(red: 1, green: 0.8, blue: 0, alpha: 1)
// Color of the focus square fill.
static let fillColor = #colorLiteral(red: 1, green: 0.9254901961, blue: 0.4117647059, alpha: 1)
// MARK: - Properties
/// The most recent position of the focus square based on the current state.
var lastPosition: float3? {
switch state {
case .initializing: return nil
case .detecting(let hitTestResult, _): return hitTestResult.worldTransform.translation
}
}
var state: State = .initializing {
didSet {
guard state != oldValue else { return }
switch state {
case .initializing:
displayAsBillboard()
case let .detecting(hitTestResult, camera):
if let planeAnchor = hitTestResult.anchor as? ARPlaneAnchor {
displayAsClosed(for: hitTestResult, planeAnchor: planeAnchor, camera: camera)
currentPlaneAnchor = planeAnchor
} else {
displayAsOpen(for: hitTestResult, camera: camera)
currentPlaneAnchor = nil
}
}
}
}
/// Indicates whether the segments of the focus square are disconnected.
private var isOpen = false
/// Indicates if the square is currently being animated.
private var isAnimating = false
/// Indicates if the square is currently changing its alignment.
private var isChangingAlignment = false
/// The focus square's current alignment.
private var currentAlignment: ARPlaneAnchor.Alignment?
/// The current plane anchor if the focus square is on a plane.
private(set) var currentPlaneAnchor: ARPlaneAnchor?
/// The focus square's most recent positions.
private var recentFocusSquarePositions: [float3] = []
/// The focus square's most recent alignments.
private(set) var recentFocusSquareAlignments: [ARPlaneAnchor.Alignment] = []
/// Previously visited plane anchors.
private var anchorsOfVisitedPlanes: Set<ARAnchor> = []
/// List of the segments in the focus square.
private var segments: [FocusSquare.Segment] = []
/// The primary node that controls the position of other `FocusSquare` nodes.
private let positioningNode = SCNNode()
// MARK: - Initialization
override init() {
super.init()
opacity = 0.0
/*
The focus square consists of eight segments as follows, which can be individually animated.
s1 s2
_ _
s3 | | s4
s5 | | s6
- -
s7 s8
*/
let s1 = Segment(name: "s1", corner: .topLeft, alignment: .horizontal)
let s2 = Segment(name: "s2", corner: .topRight, alignment: .horizontal)
let s3 = Segment(name: "s3", corner: .topLeft, alignment: .vertical)
let s4 = Segment(name: "s4", corner: .topRight, alignment: .vertical)
let s5 = Segment(name: "s5", corner: .bottomLeft, alignment: .vertical)
let s6 = Segment(name: "s6", corner: .bottomRight, alignment: .vertical)
let s7 = Segment(name: "s7", corner: .bottomLeft, alignment: .horizontal)
let s8 = Segment(name: "s8", corner: .bottomRight, alignment: .horizontal)
segments = [s1, s2, s3, s4, s5, s6, s7, s8]
let sl: Float = 0.5 // segment length
let c: Float = FocusSquare.thickness / 2 // correction to align lines perfectly
s1.simdPosition += float3(-(sl / 2 - c), -(sl - c), 0)
s2.simdPosition += float3(sl / 2 - c, -(sl - c), 0)
s3.simdPosition += float3(-sl, -sl / 2, 0)
s4.simdPosition += float3(sl, -sl / 2, 0)
s5.simdPosition += float3(-sl, sl / 2, 0)
s6.simdPosition += float3(sl, sl / 2, 0)
s7.simdPosition += float3(-(sl / 2 - c), sl - c, 0)
s8.simdPosition += float3(sl / 2 - c, sl - c, 0)
positioningNode.eulerAngles.x = .pi / 2 // Horizontal
positioningNode.simdScale = float3(FocusSquare.size * FocusSquare.scaleForClosedSquare)
for segment in segments {
positioningNode.addChildNode(segment)
}
positioningNode.addChildNode(fillPlane)
// Always render focus square on top of other content.
displayNodeHierarchyOnTop(true)
addChildNode(positioningNode)
// Start the focus square as a billboard.
displayAsBillboard()
}
required init?(coder aDecoder: NSCoder) {
fatalError("\(#function) has not been implemented")
}
// MARK: - Appearance
/// Hides the focus square.
func hide() {
guard action(forKey: "hide") == nil else { return }
displayNodeHierarchyOnTop(false)
runAction(.fadeOut(duration: 0.5), forKey: "hide")
}
/// Unhides the focus square.
func unhide() {
guard action(forKey: "unhide") == nil else { return }
displayNodeHierarchyOnTop(true)
runAction(.fadeIn(duration: 0.5), forKey: "unhide")
}
/// Displays the focus square parallel to the camera plane.
private func displayAsBillboard() {
simdTransform = matrix_identity_float4x4
eulerAngles.x = .pi / 2
simdPosition = float3(0, 0, -0.8)
unhide()
performOpenAnimation()
}
/// Called when a surface has been detected.
private func displayAsOpen(for hitTestResult: ARHitTestResult, camera: ARCamera?) {
performOpenAnimation()
let position = hitTestResult.worldTransform.translation
recentFocusSquarePositions.append(position)
updateTransform(for: position, hitTestResult: hitTestResult, camera: camera)
}
/// Called when a plane has been detected.
private func displayAsClosed(for hitTestResult: ARHitTestResult, planeAnchor: ARPlaneAnchor, camera: ARCamera?) {
performCloseAnimation(flash: !anchorsOfVisitedPlanes.contains(planeAnchor))
anchorsOfVisitedPlanes.insert(planeAnchor)
let position = hitTestResult.worldTransform.translation
recentFocusSquarePositions.append(position)
updateTransform(for: position, hitTestResult: hitTestResult, camera: camera)
}
// MARK: Helper Methods
/// Update the transform of the focus square to be aligned with the camera.
private func updateTransform(for position: float3, hitTestResult: ARHitTestResult, camera: ARCamera?) {
// Average using several most recent positions.
recentFocusSquarePositions = Array(recentFocusSquarePositions.suffix(10))
// Move to average of recent positions to avoid jitter.
let average = recentFocusSquarePositions.reduce(float3(0), { $0 + $1 }) / Float(recentFocusSquarePositions.count)
self.simdPosition = average
self.simdScale = float3(scaleBasedOnDistance(camera: camera))
// Correct y rotation of camera square.
guard let camera = camera else { return }
let tilt = abs(camera.eulerAngles.x)
let threshold1: Float = .pi / 2 * 0.65
let threshold2: Float = .pi / 2 * 0.75
let yaw = atan2f(camera.transform.columns.0.x, camera.transform.columns.1.x)
var angle: Float = 0
switch tilt {
case 0..<threshold1:
angle = camera.eulerAngles.y
case threshold1..<threshold2:
let relativeInRange = abs((tilt - threshold1) / (threshold2 - threshold1))
let normalizedY = normalize(camera.eulerAngles.y, forMinimalRotationTo: yaw)
angle = normalizedY * (1 - relativeInRange) + yaw * relativeInRange
default:
angle = yaw
}
if state != .initializing {
updateAlignment(for: hitTestResult, yRotationAngle: angle)
}
}
private func updateAlignment(for hitTestResult: ARHitTestResult, yRotationAngle angle: Float) {
// Abort if an animation is currently in progress.
if isChangingAlignment {
return
}
var shouldAnimateAlignmentChange = false
let tempNode = SCNNode()
tempNode.simdRotation = float4(0, 1, 0, angle)
// Determine current alignment
var alignment: ARPlaneAnchor.Alignment?
if let planeAnchor = hitTestResult.anchor as? ARPlaneAnchor {
alignment = planeAnchor.alignment
} else if hitTestResult.type == .estimatedHorizontalPlane {
alignment = .horizontal
} else if hitTestResult.type == .estimatedVerticalPlane {
alignment = .vertical
}
// add to list of recent alignments
if alignment != nil {
recentFocusSquareAlignments.append(alignment!)
}
// Average using several most recent alignments.
recentFocusSquareAlignments = Array(recentFocusSquareAlignments.suffix(20))
let horizontalHistory = recentFocusSquareAlignments.filter({ $0 == .horizontal }).count
let verticalHistory = recentFocusSquareAlignments.filter({ $0 == .vertical }).count
// Alignment is same as most of the history - change it
if alignment == .horizontal && horizontalHistory > 15 ||
alignment == .vertical && verticalHistory > 10 ||
hitTestResult.anchor is ARPlaneAnchor {
if alignment != currentAlignment {
shouldAnimateAlignmentChange = true
currentAlignment = alignment
recentFocusSquareAlignments.removeAll()
}
} else {
// Alignment is different than most of the history - ignore it
alignment = currentAlignment
return
}
if alignment == .vertical {
tempNode.simdOrientation = hitTestResult.worldTransform.orientation
shouldAnimateAlignmentChange = true
}
// Change the focus square's alignment
if shouldAnimateAlignmentChange {
performAlignmentAnimation(to: tempNode.simdOrientation)
} else {
simdOrientation = tempNode.simdOrientation
}
}
private func normalize(_ angle: Float, forMinimalRotationTo ref: Float) -> Float {
// Normalize angle in steps of 90 degrees such that the rotation to the other angle is minimal
var normalized = angle
while abs(normalized - ref) > .pi / 4 {
if angle > ref {
normalized -= .pi / 2
} else {
normalized += .pi / 2
}
}
return normalized
}
/**
Reduce visual size change with distance by scaling up when close and down when far away.
These adjustments result in a scale of 1.0x for a distance of 0.7 m or less
(estimated distance when looking at a table), and a scale of 1.2x
for a distance 1.5 m distance (estimated distance when looking at the floor).
*/
private func scaleBasedOnDistance(camera: ARCamera?) -> Float {
guard let camera = camera else { return 1.0 }
let distanceFromCamera = simd_length(simdWorldPosition - camera.transform.translation)
if distanceFromCamera < 0.7 {
return distanceFromCamera / 0.7
} else {
return 0.25 * distanceFromCamera + 0.825
}
}
// MARK: Animations
private func performOpenAnimation() {
guard !isOpen, !isAnimating else { return }
isOpen = true
isAnimating = true
// Open animation
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
positioningNode.opacity = 1.0
for segment in segments {
segment.open()
}
SCNTransaction.completionBlock = {
self.positioningNode.runAction(pulseAction(), forKey: "pulse")
// This is a safe operation because `SCNTransaction`'s completion block is called back on the main thread.
self.isAnimating = false
}
SCNTransaction.commit()
// Add a scale/bounce animation.
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
positioningNode.simdScale = float3(FocusSquare.size)
SCNTransaction.commit()
}
private func performCloseAnimation(flash: Bool = false) {
guard isOpen, !isAnimating else { return }
isOpen = false
isAnimating = true
positioningNode.removeAction(forKey: "pulse")
positioningNode.opacity = 1.0
// Close animation
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 2
positioningNode.opacity = 0.99
SCNTransaction.completionBlock = {
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
for segment in self.segments {
segment.close()
}
SCNTransaction.completionBlock = { self.isAnimating = false }
SCNTransaction.commit()
}
SCNTransaction.commit()
// Scale/bounce animation
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.x"), forKey: "transform.scale.x")
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.y"), forKey: "transform.scale.y")
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.z"), forKey: "transform.scale.z")
if flash {
let waitAction = SCNAction.wait(duration: FocusSquare.animationDuration * 0.75)
let fadeInAction = SCNAction.fadeOpacity(to: 0.25, duration: FocusSquare.animationDuration * 0.125)
let fadeOutAction = SCNAction.fadeOpacity(to: 0.0, duration: FocusSquare.animationDuration * 0.125)
fillPlane.runAction(SCNAction.sequence([waitAction, fadeInAction, fadeOutAction]))
let flashSquareAction = flashAnimation(duration: FocusSquare.animationDuration * 0.25)
for segment in segments {
segment.runAction(.sequence([waitAction, flashSquareAction]))
}
}
}
private func performAlignmentAnimation(to newOrientation: simd_quatf) {
isChangingAlignment = true
SCNTransaction.begin()
SCNTransaction.completionBlock = {
self.isChangingAlignment = false
}
SCNTransaction.animationDuration = 0.5
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
simdOrientation = newOrientation
SCNTransaction.commit()
}
// MARK: Convenience Methods
private func scaleAnimation(for keyPath: String) -> CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: keyPath)
let easeOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
let easeInOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let linear = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
let size = FocusSquare.size
let ts = FocusSquare.size * FocusSquare.scaleForClosedSquare
let values = [size, size * 1.15, size * 1.15, ts * 0.97, ts]
let keyTimes: [NSNumber] = [0.00, 0.25, 0.50, 0.75, 1.00]
let timingFunctions = [easeOut, linear, easeOut, easeInOut]
scaleAnimation.values = values
scaleAnimation.keyTimes = keyTimes
scaleAnimation.timingFunctions = timingFunctions
scaleAnimation.duration = FocusSquare.animationDuration
return scaleAnimation
}
/// Sets the rendering order of the `positioningNode` to show on top or under other scene content.
func displayNodeHierarchyOnTop(_ isOnTop: Bool) {
// Recursivley traverses the node's children to update the rendering order depending on the `isOnTop` parameter.
func updateRenderOrder(for node: SCNNode) {
node.renderingOrder = isOnTop ? 2 : 0
for material in node.geometry?.materials ?? [] {
material.readsFromDepthBuffer = !isOnTop
}
for child in node.childNodes {
updateRenderOrder(for: child)
}
}
updateRenderOrder(for: positioningNode)
}
private lazy var fillPlane: SCNNode = {
let correctionFactor = FocusSquare.thickness / 2 // correction to align lines perfectly
let length = CGFloat(1.0 - FocusSquare.thickness * 2 + correctionFactor)
let plane = SCNPlane(width: length, height: length)
let node = SCNNode(geometry: plane)
node.name = "fillPlane"
node.opacity = 0.0
let material = plane.firstMaterial!
material.diffuse.contents = FocusSquare.fillColor
material.isDoubleSided = true
material.ambient.contents = UIColor.black
material.lightingModel = .constant
material.emission.contents = FocusSquare.fillColor
return node
}()
}
// MARK: - Animations and Actions
private func pulseAction() -> SCNAction {
let pulseOutAction = SCNAction.fadeOpacity(to: 0.4, duration: 0.5)
let pulseInAction = SCNAction.fadeOpacity(to: 1.0, duration: 0.5)
pulseOutAction.timingMode = .easeInEaseOut
pulseInAction.timingMode = .easeInEaseOut
return SCNAction.repeatForever(SCNAction.sequence([pulseOutAction, pulseInAction]))
}
private func flashAnimation(duration: TimeInterval) -> SCNAction {
let action = SCNAction.customAction(duration: duration) { (node, elapsedTime) -> Void in
// animate color from HSB 48/100/100 to 48/30/100 and back
let elapsedTimePercentage = elapsedTime / CGFloat(duration)
let saturation = 2.8 * (elapsedTimePercentage - 0.5) * (elapsedTimePercentage - 0.5) + 0.3
if let material = node.geometry?.firstMaterial {
material.diffuse.contents = UIColor(hue: 0.1333, saturation: saturation, brightness: 1.0, alpha: 1.0)
}
}
return action
}
| mit |
Swinject/SwinjectMVVMExample | ExampleModel/ImageSearching.swift | 2 | 361 | //
// ImageSearching.swift
// SwinjectMVVMExample
//
// Created by Yoichi Tagaya on 8/22/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import ReactiveSwift
import Result
public protocol ImageSearching {
func searchImages(nextPageTrigger trigger: SignalProducer<(), NoError>) -> SignalProducer<ResponseEntity, NetworkError>
}
| mit |
AzenXu/Memo | Memo/Common/Helpers/SmartTask.swift | 1 | 1313 | //
// SmartTask.swift
// Base
//
// Created by kenneth wang on 16/5/8.
// Copyright © 2016年 st. All rights reserved.
//
import Foundation
import UIKit
public typealias CancelableTask = (cancel: Bool) -> Void
/**
延迟执行任务
- parameter time: 延迟时间
- parameter work: 任务闭包
- returns:
*/
public func delay(time: NSTimeInterval, work: dispatch_block_t) -> CancelableTask? {
var finalTask: CancelableTask?
let cancelableTask: CancelableTask = { cancel in
if cancel {
finalTask = nil // key
} else {
dispatch_async(dispatch_get_main_queue(), work)
}
}
finalTask = cancelableTask
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
if let task = finalTask {
task(cancel: false)
}
}
return finalTask
}
/**
取消执行任务
- parameter cancelableTask:
*/
public func cancel(cancelableTask: CancelableTask?) {
cancelableTask?(cancel: true)
}
/**
测量函数的执行时间
- parameter f: 函数
*/
public func measure(f: () -> ()) {
let start = CACurrentMediaTime()
f()
let end = CACurrentMediaTime()
print("测量时间:\(end - start)")
}
| mit |
CombineCommunity/CombineExt | Tests/FilterManyTests.swift | 1 | 2044 | //
// FilterManyTests.swift
// CombineExtTests
//
// Created by Hugo Saynac on 30/09/2020.
// Copyright © 2020 Combine Community. All rights reserved.
//
#if !os(watchOS)
import XCTest
import Combine
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
class FilterManyTests: XCTestCase {
var subscription: AnyCancellable!
func testFilterManyWithModelAndFinishedCompletion() {
let source = PassthroughSubject<[Int], Never>()
var expectedOutput = [Int]()
var completion: Subscribers.Completion<Never>?
subscription = source
.filterMany(isPair)
.sink(
receiveCompletion: { completion = $0 },
receiveValue: { $0.forEach { expectedOutput.append($0) } }
)
source.send([10, 1, 2, 4, 3, 8])
source.send(completion: .finished)
XCTAssertEqual(
expectedOutput,
[10, 2, 4, 8]
)
XCTAssertEqual(completion, .finished)
}
func testFilterManyWithModelAndFailureCompletion() {
let source = PassthroughSubject<[Int], FilterManyError>()
var expectedOutput = [Int]()
var completion: Subscribers.Completion<FilterManyError>?
subscription = source
.filterMany(isPair)
.sink(
receiveCompletion: { completion = $0 },
receiveValue: { $0.forEach { expectedOutput.append($0) } }
)
source.send([10, 1, 2, 4, 3, 8])
source.send(completion: .failure(.anErrorCase))
XCTAssertEqual(
expectedOutput,
[10, 2, 4, 8]
)
XCTAssertEqual(completion, .failure(.anErrorCase))
}
}
private func isPair(_ value: Int) -> Bool {
value.isMultiple(of: 2)
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
private extension FilterManyTests {
enum FilterManyError: Error {
case anErrorCase
}
}
#endif
| mit |
coderZsq/coderZsq.target.swift | StudyNotes/Swift Note/LiveBroadcast/Client/LiveBroadcast/Classes/Main/View/PageView/ContentView.swift | 1 | 4770 | //
// ContentView.swift
// LiveBroadcast
//
// Created by 朱双泉 on 2018/12/10.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
private let kContentCellID = "kContentCellID"
protocol ContentViewDelegate: class {
func contentView(_ contentView: ContentView, targetIndex: Int)
func contentView(_ contentView: ContentView, targetIndex: Int, progress: CGFloat)
}
class ContentView: UIView {
weak var delegate: ContentViewDelegate?
fileprivate var childVcs: [UIViewController]
fileprivate var parentVc: UIViewController
fileprivate var startOffsetX: CGFloat = 0
fileprivate var isForbidScroll = false
fileprivate lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = self.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kContentCellID)
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.scrollsToTop = false
collectionView.showsHorizontalScrollIndicator = false
return collectionView
}()
init(frame: CGRect, childVcs: [UIViewController], parentVc: UIViewController) {
self.childVcs = childVcs
self.parentVc = parentVc
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ContentView {
fileprivate func setupUI() {
for childVc in childVcs {
parentVc.addChild(childVc)
}
addSubview(collectionView)
}
}
extension ContentView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kContentCellID, for: indexPath)
for subView in cell.contentView.subviews {
subView.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
extension ContentView: UICollectionViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
contentEndScroll()
scrollView.isScrollEnabled = true
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
contentEndScroll()
} else {
scrollView.isScrollEnabled = false
}
}
private func contentEndScroll() {
guard !isForbidScroll else { return }
let currentIndex = Int(collectionView.contentOffset.x / collectionView.bounds.width)
delegate?.contentView(self, targetIndex: currentIndex)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScroll = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard startOffsetX != scrollView.contentOffset.x, !isForbidScroll else {
return
}
var targetIndex = 0
var progress: CGFloat = 0.0
let currentIndex = Int(startOffsetX / scrollView.bounds.width)
if startOffsetX < scrollView.contentOffset.x {
targetIndex = currentIndex + 1
if targetIndex > childVcs.count - 1 {
targetIndex = childVcs.count - 1
}
progress = (scrollView.contentOffset.x - startOffsetX) / scrollView.bounds.width
} else {
targetIndex = currentIndex - 1
if targetIndex < 0 {
targetIndex = 0
}
progress = (startOffsetX - scrollView.contentOffset.x) / scrollView.bounds.width
}
delegate?.contentView(self, targetIndex: targetIndex, progress: progress)
}
}
extension ContentView: TitleViewDelegate {
func titleView(_ titleView: TitleView, targetIndex: Int) {
isForbidScroll = true
let indexPath = IndexPath(item: targetIndex, section: 0)
collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
}
}
| mit |
pnhechim/Fiestapp-iOS | Fiestapp/Fiestapp/ViewControllers/Home/HomeViewController.swift | 1 | 2134 | //
// HomeViewController.swift
// Fiestapp
//
// Created by Nicolás Hechim on 2/7/17.
// Copyright © 2017 Mint. All rights reserved.
//
import UIKit
class HomeViewController: UITabBarController, UITabBarControllerDelegate {
// UITabBarDelegate
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
if item.title == "Cerrar sesión" {
let alertController = UIAlertController(title: "Cerrar sesión", message: "¿Seguro que querés cerrar sesión? Necesitás estar logueado para utilizar Fiestapp!", preferredStyle: UIAlertControllerStyle.actionSheet)
alertController.addAction(UIAlertAction(title: "Cancelar", style: UIAlertActionStyle.cancel) {
(result : UIAlertAction) -> Void in
})
alertController.addAction(UIAlertAction(title: "Sí", style: UIAlertActionStyle.destructive)
{
(result : UIAlertAction) -> Void in
FirebaseService.shared.cerrarSesion()
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") {
UIApplication.shared.keyWindow?.rootViewController = viewController
self.dismiss(animated: true, completion: nil)
}
})
self.present(alertController, animated: true, completion: nil)
}
else if item.title == "Mis fiestas" {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.currentSelectedIndex = 0
}
else if item.title == "Nueva fiesta" {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.currentSelectedIndex = 1
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
youprofit/firefox-ios | Client/Frontend/Settings/SearchSettingsTableViewController.swift | 14 | 10348 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class SearchSettingsTableViewController: UITableViewController {
private let SectionDefault = 0
private let ItemDefaultEngine = 0
private let ItemDefaultSuggestions = 1
private let NumberOfItemsInSectionDefault = 2
private let SectionOrder = 1
private let NumberOfSections = 2
private let IconSize = CGSize(width: OpenSearchEngine.PreferredIconSize, height: OpenSearchEngine.PreferredIconSize)
private let SectionHeaderIdentifier = "SectionHeaderIdentifier"
var model: SearchEngines!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Search", comment: "Navigation title for search settings.")
// To allow re-ordering the list of search engines at all times.
tableView.editing = true
// So that we push the default search engine controller on selection.
tableView.allowsSelectionDuringEditing = true
tableView.registerClass(SettingsTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
// Insert Done button if being presented outside of the Settings Nav stack
if !(self.navigationController is SettingsNavigationController) {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Done", comment: "Done button label for search settings table"), style: .Done, target: self, action: "SELDismiss")
}
tableView.tableFooterView = UIView()
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell!
var engine: OpenSearchEngine!
if indexPath.section == SectionDefault {
switch indexPath.item {
case ItemDefaultEngine:
engine = model.defaultEngine
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.editingAccessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.accessibilityLabel = NSLocalizedString("Default Search Engine", comment: "Accessibility label for default search engine setting.")
cell.accessibilityValue = engine.shortName
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image?.createScaled(IconSize)
case ItemDefaultSuggestions:
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.textLabel?.text = NSLocalizedString("Show Search Suggestions", comment: "Label for show search suggestions setting.")
let toggle = UISwitch()
toggle.onTintColor = UIConstants.ControlTintColor
toggle.addTarget(self, action: "SELdidToggleSearchSuggestions:", forControlEvents: UIControlEvents.ValueChanged)
toggle.on = model.shouldShowSearchSuggestions
cell.editingAccessoryView = toggle
cell.selectionStyle = .None
default:
// Should not happen.
break
}
} else {
// The default engine is not a quick search engine.
let index = indexPath.item + 1
engine = model.orderedEngines[index]
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.showsReorderControl = true
let toggle = UISwitch()
toggle.onTintColor = UIConstants.ControlTintColor
// This is an easy way to get from the toggle control to the corresponding index.
toggle.tag = index
toggle.addTarget(self, action: "SELdidToggleEngine:", forControlEvents: UIControlEvents.ValueChanged)
toggle.on = model.isEngineEnabled(engine)
cell.editingAccessoryView = toggle
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image?.createScaled(IconSize)
cell.selectionStyle = .None
}
// So that the seperator line goes all the way to the left edge.
cell.separatorInset = UIEdgeInsetsZero
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return NumberOfSections
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == SectionDefault {
return NumberOfItemsInSectionDefault
} else {
// The first engine -- the default engine -- is not shown in the quick search engine list.
return model.orderedEngines.count - 1
}
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if indexPath.section == SectionDefault && indexPath.item == ItemDefaultEngine {
let searchEnginePicker = SearchEnginePicker()
// Order alphabetically, so that picker is always consistently ordered.
// Every engine is a valid choice for the default engine, even the current default engine.
searchEnginePicker.engines = model.orderedEngines.sort { e, f in e.shortName < f.shortName }
searchEnginePicker.delegate = self
searchEnginePicker.selectedSearchEngineName = model.defaultEngine.shortName
navigationController?.pushViewController(searchEnginePicker, animated: true)
}
return nil
}
// Don't show delete button on the left.
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.None
}
// Don't reserve space for the delete button on the left.
override func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// Hide a thin vertical line that iOS renders between the accessoryView and the reordering control.
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.editing {
for v in cell.subviews {
if v.frame.width == 1.0 {
v.backgroundColor = UIColor.clearColor()
}
}
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderView
var sectionTitle: String
if section == SectionDefault {
sectionTitle = NSLocalizedString("Default Search Engine", comment: "Title for default search engine settings section.")
} else {
sectionTitle = NSLocalizedString("Quick-search Engines", comment: "Title for quick-search engines settings section.")
}
headerView.titleLabel.text = sectionTitle
return headerView
}
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if indexPath.section == SectionDefault {
return false
} else {
return true
}
}
override func tableView(tableView: UITableView, moveRowAtIndexPath indexPath: NSIndexPath, toIndexPath newIndexPath: NSIndexPath) {
// The first engine (default engine) is not shown in the list, so the indices are off-by-1.
let index = indexPath.item + 1
let newIndex = newIndexPath.item + 1
let engine = model.orderedEngines.removeAtIndex(index)
model.orderedEngines.insert(engine, atIndex: newIndex)
tableView.reloadData()
}
// Snap to first or last row of the list of engines.
override func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
// You can't drag or drop on the default engine.
if sourceIndexPath.section == SectionDefault || proposedDestinationIndexPath.section == SectionDefault {
return sourceIndexPath
}
if (sourceIndexPath.section != proposedDestinationIndexPath.section) {
var row = 0
if (sourceIndexPath.section < proposedDestinationIndexPath.section) {
row = tableView.numberOfRowsInSection(sourceIndexPath.section) - 1
}
return NSIndexPath(forRow: row, inSection: sourceIndexPath.section)
}
return proposedDestinationIndexPath
}
func SELdidToggleEngine(toggle: UISwitch) {
let engine = model.orderedEngines[toggle.tag] // The tag is 1-based.
if toggle.on {
model.enableEngine(engine)
} else {
model.disableEngine(engine)
}
}
func SELdidToggleSearchSuggestions(toggle: UISwitch) {
// Setting the value in settings dismisses any opt-in.
model.shouldShowSearchSuggestionsOptIn = false
model.shouldShowSearchSuggestions = toggle.on
}
func SELcancel() {
navigationController?.popViewControllerAnimated(true)
}
func SELDismiss() {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
extension SearchSettingsTableViewController: SearchEnginePickerDelegate {
func searchEnginePicker(searchEnginePicker: SearchEnginePicker, didSelectSearchEngine searchEngine: OpenSearchEngine?) {
if let engine = searchEngine {
model.defaultEngine = engine
self.tableView.reloadData()
}
navigationController?.popViewControllerAnimated(true)
}
}
| mpl-2.0 |
jianzhi2010/NVProgressHUD | NVProgressHUDDemo/AppDelegate.swift | 1 | 2143 | //
// AppDelegate.swift
// NVProgressHUDDemo
//
// Created by liang on 15/12/5.
// Copyright © 2015年 liang. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
ReactiveKit/ReactiveGitter | ReactiveGitter/Extensions.swift | 1 | 815 | //
// Extensions.swift
// ReactiveGitter
//
// Created by Srdan Rasic on 15/01/2017.
// Copyright © 2017 ReactiveKit. All rights reserved.
//
import UIKit
import Networking
import ReactiveKit
import Bond
extension ReactiveExtensions where Base: UIViewController {
public var userErrors: Bond<UserFriendlyError> {
return bond { vc, error in
let alert = UIAlertController(title: "Error occurred", message: error.message, preferredStyle: .actionSheet)
if let retry = error.retry {
let action = UIAlertAction(title: "Retry", style: .default) { _ in
retry.next()
}
alert.addAction(action)
}
let dismissAction = UIAlertAction(title: "Dismiss", style: .cancel)
alert.addAction(dismissAction)
vc.present(alert, animated: true)
}
}
}
| mit |
TalkingBibles/Talking-Bible-iOS | TalkingBible/Player.swift | 1 | 12297 | //
// Copyright 2015 Talking Bibles International
//
// 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 Swift
import Foundation
import AVFoundation
import TMReachability
final class Player: NSObject {
class var sharedManager: Player {
struct Singleton {
static let player = Player()
}
return Singleton.player
}
let reach: TMReachability
var machine: StateMachine<Player>!
enum PlayerState: Int {
case Unknown = 0
case NoConnection = 1
case Unplayable = 2
case NotReady = 3
case AlmostReady = 4
case Ready = 5
case Playing = 6
case Paused = 7
func description() -> String {
let descriptions = [
"Unknown",
"NoConnection",
"Unplayable",
"NotReady",
"AlmostReady",
"Ready",
"Playing",
"Paused"
]
return descriptions[self.hashValue]
}
}
var onReady: (() -> ())?
typealias PlayerItemQueue = [AVPlayerItem]
struct Constants {
struct KeyPaths {
static let currentItem = "currentItem"
static let status = "status"
static let rate = "rate"
static let duration = "duration"
}
static let interval = CMTimeMakeWithSeconds(1.0, Int32(NSEC_PER_SEC))
}
private var player: AVPlayer! {
willSet {
if let player = player {
log.info("Removing player observers")
player.removeObserver(self, forKeyPath: Constants.KeyPaths.currentItem)
player.removeObserver(self, forKeyPath: Constants.KeyPaths.status)
player.removeObserver(self, forKeyPath: Constants.KeyPaths.rate)
for timeObserver in timeObservers {
player.removeTimeObserver(timeObserver)
}
timeObservers = []
}
}
didSet {
log.info("Adding player observers")
player.addObserver(self, forKeyPath: Constants.KeyPaths.currentItem, options: .New, context: nil)
player.addObserver(self, forKeyPath: Constants.KeyPaths.status, options: .New, context: nil)
player.addObserver(self, forKeyPath: Constants.KeyPaths.rate, options: [.Initial, .New], context: nil)
timeObservers.append(player.addPeriodicTimeObserverForInterval(Constants.interval, queue: nil) { time in
if time.flags == CMTimeFlags.Valid {
postNotification(playerTimeUpdatedNotification, value: time)
}
})
}
}
private var mp3Queue: [String]!
private var playerItemQueue: PlayerItemQueue! {
willSet {
if let queue = playerItemQueue {
log.info("Removing \(queue.count) observers from playerItemQueue")
for playerItem in queue {
playerItem.removeObserver(self, forKeyPath: Constants.KeyPaths.status, context: nil)
}
}
}
didSet {
log.info("Adding \(playerItemQueue.count) observers to playerItemQueue")
for playerItem in playerItemQueue {
playerItem.addObserver(self, forKeyPath: Constants.KeyPaths.status, options: .New, context: nil)
}
}
}
var currentTime: CMTime {
return player.currentTime()
}
var duration: CMTime {
return player.currentItem?.duration ?? CMTimeMake(0, 16)
}
private var _currentPlayerItemIndex: Int = 0
var currentPlayerItemIndex: Int {
get {
return _currentPlayerItemIndex
}
}
/// Strong Links
private var timeObservers = [AnyObject]()
/// Time Tracking
private var _currentPercentComplete: Float {
let currentTime = player.currentTime()
if let currentDuration = player.currentItem?.duration {
return Float(CMTimeGetSeconds(currentTime)) / Float(CMTimeGetSeconds(currentDuration))
}
return Float(0)
}
override init() {
reach = TMReachability.reachabilityForInternetConnection()
super.init()
machine = StateMachine(initialState: .NotReady, delegate: self)
replacePlayer()
}
// MARK: Setup
private func replaceQueue() {
var tempPlayerItemQueue = [AVPlayerItem]()
for mp3 in mp3Queue {
guard let url = NSURL(string: mp3) else {
return
}
let playerItem = AVPlayerItem(URL: url)
tempPlayerItemQueue.append(playerItem)
}
playerItemQueue = tempPlayerItemQueue
}
private func replacePlayer() {
log.info("Replacing player")
machine.state = .NotReady
player = AVPlayer()
}
private func recoverFromFailure() {
dispatch_async(dispatch_get_main_queue()) {
self.replaceQueue()
self.replacePlayer()
self.selectPlayerItem(self._currentPlayerItemIndex, timeInterval: 0.0)
}
}
// MARK: Public methods
func playItem() {
player.play()
}
func pauseItem() {
onReady = nil
player.pause()
}
func toggleItem() {
switch machine.state {
case .Playing:
onReady = nil
player.pause()
case .Ready, .Paused:
player.play()
default:
break
}
}
func nextPlayerItem() {
let nextPlayerItemIndex = _currentPlayerItemIndex + 1
if nextPlayerItemIndex < playerItemQueue.count {
selectPlayerItem(nextPlayerItemIndex, timeInterval: 0.0)
}
}
func previousPlayerItem() {
if player.rate > 0.0 && player.error == nil {
if _currentPercentComplete > 0.1 || _currentPlayerItemIndex == 0 {
seekToTime(Float(0)) { _ in }
return
}
}
let previousPlayerItemIndex = _currentPlayerItemIndex - 1
if previousPlayerItemIndex >= 0 {
selectPlayerItem(previousPlayerItemIndex, timeInterval: 0.0)
}
}
func seekToTime(time: Float, completionHandler: (Bool) -> ()) {
guard let currentItem = player.currentItem else {
return
}
let status = currentItem.status as AVPlayerItemStatus
if status == .ReadyToPlay {
currentItem.seekToTime(CMTimeMakeWithSeconds(Float64(time), currentItem.duration.timescale), completionHandler: completionHandler)
} else {
completionHandler(false)
}
}
func seekIncrementally() {
let currentTime = player.currentTime()
if let currentDuration = player.currentItem?.duration {
let playerItem = playerItemQueue[_currentPlayerItemIndex]
let fifteenSecondsLater = CMTimeMakeWithSeconds(CMTimeGetSeconds(currentTime) + 15, currentTime.timescale)
if CMTimeCompare(fifteenSecondsLater, currentDuration) <= 0 {
playerItem.seekToTime(fifteenSecondsLater)
} else {
playerItem.seekToTime(currentDuration)
}
}
}
func seekDecrementally() {
let currentTime = player.currentTime()
if let currentDuration = player.currentItem?.duration {
let playerItem = playerItemQueue[_currentPlayerItemIndex]
let fifteenSecondsEarlier = CMTimeMakeWithSeconds(CMTimeGetSeconds(currentTime) - 15, currentTime.timescale)
if CMTimeCompare(fifteenSecondsEarlier, currentDuration) >= 0 {
playerItem.seekToTime(fifteenSecondsEarlier)
} else {
playerItem.seekToTime(CMTimeMakeWithSeconds(0, currentTime.timescale))
}
}
}
func replaceQueue(queue: [String]) {
mp3Queue = queue
_currentPlayerItemIndex = 0
replaceQueue()
replacePlayer()
}
func selectPlayerItem(index: Int, timeInterval: NSTimeInterval) {
if playerItemQueue.count <= index {
return
}
_currentPlayerItemIndex = index
postNotification(playerItemInQueueChangedNotification, value: _currentPlayerItemIndex)
self.player.replaceCurrentItemWithPlayerItem(playerItemQueue[index])
onReady = {
self.onReady = nil
self.seekToTime(Float(timeInterval), completionHandler: { success in
if success {
self.playItem()
}
})
return
}
}
// MARK: Observers
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard let keyPath = keyPath else { return }
switch (object, keyPath) {
case (let player as AVPlayer, Constants.KeyPaths.status):
switch player.status {
case .Failed:
handleFailure(player: player)
default:
log.info("AVPlayer is \(player.status.rawValue)")
}
case (let player as AVPlayer, Constants.KeyPaths.rate):
if player.rate > 0.0 && player.error == nil {
machine.state = .Playing
} else {
machine.state = .Paused
}
case (_, Constants.KeyPaths.currentItem):
machine.state = .AlmostReady
case (let currentItem as AVPlayerItem, Constants.KeyPaths.status):
switch currentItem.status {
case .ReadyToPlay:
machine.state = .Ready
case .Failed:
handleFailure(playerItem: currentItem)
default:
log.warning("AVPlayerItem status is unknown")
}
default:
log.warning("\(keyPath) happened with \(object), which is unimplemented")
}
}
// MARK: Error Handling
private func handleFailure(player player: AVPlayer) {
guard let error = player.error else {
return recoverFromFailure()
}
log.error("AVPlayer failed because: [\(error.code)] \(error.localizedDescription)")
machine.state = .Unplayable
recoverFromFailure()
}
private func handleFailure(playerItem item: AVPlayerItem) {
guard let error = item.error else {
return recoverFromFailure()
}
log.error("AVPlayerItem [\(item.asset)] failed because: [\(error.code)] \(error.localizedDescription)")
switch error.code {
case -1003:
fallthrough
case -1100:
log.warning("AVPlayerItem is unplayable")
machine.state = .Unplayable
case -1005, -1009:
log.warning("AVPlayer has no connection")
machine.state = .NoConnection
default:
recoverFromFailure()
}
}
private func doWhenReachable(completionHandler: () -> ()) {
reach.reachableBlock = { (reach: TMReachability!) in
reach.stopNotifier()
completionHandler()
}
reach.startNotifier()
}
}
extension Player: StateMachineDelegateProtocol{
typealias StateType = PlayerState
func shouldTransitionFrom(from:StateType, to:StateType)->Bool{
// log.debug("should? from: \(from.description()), to: \(to.description())")
switch (from, to){
case (.NoConnection, .NoConnection), (.NotReady, .NotReady), (.AlmostReady, .AlmostReady):
return false
case (_, .NoConnection):
doWhenReachable { [unowned self] in
self.recoverFromFailure()
}
return true
case (.NoConnection, _):
return reach.isReachable()
case (_, .Unplayable):
if !reach.isReachable() {
machine.state = .NoConnection
return false
}
return true
case (_, .Ready):
if !reach.isReachable() {
machine.state = .NoConnection
return false
}
if let currentItem = self.player.currentItem {
postNotification(playerDurationUpdatedNotification, value: currentItem.duration)
}
onReady?()
return true
case (.NotReady, .Paused), (.AlmostReady, .Paused), (.Ready, .Paused):
return false
case (_, .AlmostReady), (_, .NotReady), (_, .Unknown), (_, .Paused), (_, .Playing):
return true
default:
return false
}
}
func didTransitionFrom(from:StateType, to:StateType){
postNotification(playerStateChangedNotification, value: to)
// log.debug("did. from: \(from.description()), to: \(to.description())")
}
} | apache-2.0 |
Molbie/Outlaw-SpriteKit | Tests/OutlawSpriteKitTests/Enums/SKUniformTypeTests.swift | 1 | 4277 | //
// SKUniformTypeTests.swift
// OutlawSpriteKit
//
// Created by Brian Mullen on 12/18/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import XCTest
import Outlaw
import OutlawCoreGraphics
import OutlawSimd
import SpriteKit
@testable import OutlawSpriteKit
@available(OSX 10.10, *)
class SKUniformTypeTests: XCTestCase {
fileprivate typealias strings = SKUniformType.StringValues
func testStringInit() {
let none = SKUniformType(stringValue: strings.none)
XCTAssertEqual(none, SKUniformType.none)
let float = SKUniformType(stringValue: strings.float)
XCTAssertEqual(float, .float)
let floatVector2 = SKUniformType(stringValue: strings.floatVector2)
XCTAssertEqual(floatVector2, .floatVector2)
let floatVector3 = SKUniformType(stringValue: strings.floatVector3)
XCTAssertEqual(floatVector3, .floatVector3)
let floatVector4 = SKUniformType(stringValue: strings.floatVector4)
XCTAssertEqual(floatVector4, .floatVector4)
let floatMatrix2 = SKUniformType(stringValue: strings.floatMatrix2)
XCTAssertEqual(floatMatrix2, .floatMatrix2)
let floatMatrix3 = SKUniformType(stringValue: strings.floatMatrix3)
XCTAssertEqual(floatMatrix3, .floatMatrix3)
let floatMatrix4 = SKUniformType(stringValue: strings.floatMatrix4)
XCTAssertEqual(floatMatrix4, .floatMatrix4)
let texture = SKUniformType(stringValue: strings.texture)
XCTAssertEqual(texture, .texture)
let invalid = SKUniformType(stringValue: "invalid")
XCTAssertNil(invalid)
}
func testUpperStringInit() {
let none = SKUniformType(stringValue: strings.none.uppercased())
XCTAssertEqual(none, SKUniformType.none)
let float = SKUniformType(stringValue: strings.float.uppercased())
XCTAssertEqual(float, .float)
let floatVector2 = SKUniformType(stringValue: strings.floatVector2.uppercased())
XCTAssertEqual(floatVector2, .floatVector2)
let floatVector3 = SKUniformType(stringValue: strings.floatVector3.uppercased())
XCTAssertEqual(floatVector3, .floatVector3)
let floatVector4 = SKUniformType(stringValue: strings.floatVector4.uppercased())
XCTAssertEqual(floatVector4, .floatVector4)
let floatMatrix2 = SKUniformType(stringValue: strings.floatMatrix2.uppercased())
XCTAssertEqual(floatMatrix2, .floatMatrix2)
let floatMatrix3 = SKUniformType(stringValue: strings.floatMatrix3.uppercased())
XCTAssertEqual(floatMatrix3, .floatMatrix3)
let floatMatrix4 = SKUniformType(stringValue: strings.floatMatrix4.uppercased())
XCTAssertEqual(floatMatrix4, .floatMatrix4)
let texture = SKUniformType(stringValue: strings.texture.uppercased())
XCTAssertEqual(texture, .texture)
let invalid = SKUniformType(stringValue: "INVALID")
XCTAssertNil(invalid)
}
func testStringValue() {
let none = SKUniformType.none
XCTAssertEqual(none.stringValue, strings.none)
let float = SKUniformType.float
XCTAssertEqual(float.stringValue, strings.float)
let floatVector2 = SKUniformType.floatVector2
XCTAssertEqual(floatVector2.stringValue, strings.floatVector2)
let floatVector3 = SKUniformType.floatVector3
XCTAssertEqual(floatVector3.stringValue, strings.floatVector3)
let floatVector4 = SKUniformType.floatVector4
XCTAssertEqual(floatVector4.stringValue, strings.floatVector4)
let floatMatrix2 = SKUniformType.floatMatrix2
XCTAssertEqual(floatMatrix2.stringValue, strings.floatMatrix2)
let floatMatrix3 = SKUniformType.floatMatrix3
XCTAssertEqual(floatMatrix3.stringValue, strings.floatMatrix3)
let floatMatrix4 = SKUniformType.floatMatrix4
XCTAssertEqual(floatMatrix4.stringValue, strings.floatMatrix4)
let texture = SKUniformType.texture
XCTAssertEqual(texture.stringValue, strings.texture)
}
}
| mit |
jspahrsummers/RxSwift | RxSwift/ObservableProperty.swift | 1 | 920 | //
// ObservableProperty.swift
// RxSwift
//
// Created by Justin Spahr-Summers on 2014-06-26.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
/// Represents a mutable property of type T along with the changes to its value.
@final class ObservableProperty<T>: Observable<T>, Sink {
typealias Element = T
var _sink = SinkOf<T> { _ in () }
/// The current value of the property.
///
/// Setting this will notify all observers of the change.
override var current: T {
get {
return super.current
}
set(newValue) {
_sink.put(newValue)
}
}
/// Initializes the property with the given default value.
init(_ value: T) {
super.init(generator: { sink in
sink.put(value)
self._sink = sink
})
}
/// Treats the property as its current value in expressions.
@conversion func __conversion() -> T {
return current
}
func put(value: T) {
current = value
}
}
| mit |
WCByrne/CBToolkit | CBToolkit/CBToolkit/CBSliderCollectionViewLayout.swift | 1 | 6000 | // CBSliderCell.swift
//
// Created by Wes Byrne on 2/11/15.
// Copyright (c) 2015 WCBMedia. All rights reserved.
//
import Foundation
import UIKit
/// A very simple full size 'slider' CollectionViewLayout for horizontal sliding
public class CBSliderCollectionViewLayout : UICollectionViewFlowLayout {
/// The currently displayed row in the collectionView. This must be set to handle autoscrolling.
public var currentIndex: Int = 0
/// Start and stop the collection view autoscroll.
public var autoScroll: Bool = false {
didSet {
if autoScroll {
startAutoScroll()
}
else {
cancelAutoScroll()
}
}
}
/// The delay between scroll animations
public var autoScrollDelay: TimeInterval = 5
private var autoScrollTimer: Timer?
public override init() {
super.init()
self.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
self.minimumInteritemSpacing = 0
self.minimumLineSpacing = 0
self.scrollDirection = UICollectionViewScrollDirection.horizontal
}
/**
Initialize the layout with a collectionView
- parameter collectionView: The collectionView to apply the layout to
- returns: The intialized layout
*/
public convenience init(collectionView: UICollectionView) {
self.init()
collectionView.collectionViewLayout = self;
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
Start the autoscroll timer to begin animated slides through the cells. Repeats until cancel is called.
*/
public func startAutoScroll() {
if autoScrollTimer != nil { return }
if autoScroll {
autoScrollTimer = Timer.scheduledTimer(timeInterval: autoScrollDelay, target: self, selector: #selector(CBSliderCollectionViewLayout.animateScroll), userInfo: nil, repeats: true)
}
}
/**
Cancel the autoscroll animations if they were previously started
*/
public func cancelAutoScroll() {
autoScrollTimer?.invalidate()
autoScrollTimer = nil
}
@objc internal func animateScroll() {
guard let cv = self.collectionView,
cv.numberOfSections > 0,
cv.numberOfItems(inSection: 0) > 0
else { return }
currentIndex += 1
if currentIndex >= cv.numberOfItems(inSection: 0) {
currentIndex = 0
}
self.collectionView?.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: UICollectionViewScrollPosition.left, animated: true)
}
override public var collectionViewContentSize : CGSize {
if collectionView?.numberOfSections == 0 {
return CGSize.zero
}
var contentWidth: CGFloat = 0
for section in 0...collectionView!.numberOfSections-1 {
let numItems = collectionView!.numberOfItems(inSection: section)
contentWidth = contentWidth + (CGFloat(numItems) * minimumLineSpacing) + (CGFloat(numItems) * collectionView!.frame.size.width)
}
return CGSize(width: CGFloat(contentWidth), height: collectionView!.bounds.size.height)
}
override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
if !collectionView!.bounds.size.equalTo(newBounds.size) {
return true;
}
return false;
}
var attributes : [UICollectionViewLayoutAttributes] = []
var contentSize : CGSize = CGSize.zero
override public func prepare() {
super.prepare()
let slideCount = self.collectionView?.dataSource?.collectionView(self.collectionView!, numberOfItemsInSection: 0) ?? 0
attributes.removeAll(keepingCapacity: false)
var x: CGFloat = 0
for idx in 0..<slideCount {
let height: CGFloat = collectionView!.frame.size.height
let width: CGFloat = collectionView!.frame.size.width
let y: CGFloat = 0
let attrs = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: idx, section: 0))
attrs.frame = CGRect(x: x, y: y, width: width, height: height)
x += width
attributes.append(attrs)
}
self.contentSize = CGSize(width: x, height: self.collectionView!.bounds.height)
}
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributes : [UICollectionViewLayoutAttributes] = []
if let numSections = collectionView?.numberOfSections {
if numSections > 0 {
for section in 0...numSections-1 {
let numItems = collectionView!.numberOfItems(inSection: section)
if numItems > 0 {
for row in 0...numItems-1 {
let indexPath = IndexPath(item: row, section: section)
attributes.append(layoutAttributesForItem(at: indexPath)!)
}
}
}
}
}
return attributes
}
public override func prepare(forAnimatedBoundsChange oldBounds: CGRect) {
super.prepare(forAnimatedBoundsChange: oldBounds)
collectionView!.contentOffset = CGPoint(x: CGFloat(currentIndex) * collectionView!.frame.size.width, y: 0)
}
override public func finalizeAnimatedBoundsChange() {
super.finalizeAnimatedBoundsChange()
collectionView!.contentOffset = CGPoint(x: CGFloat(currentIndex) * collectionView!.frame.size.width, y: 0)
}
override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return attributes[indexPath.item]
}
}
| mit |
vinivendra/jokr | jokr/main.swift | 1 | 570 | import Foundation
import Antlr4
// Branch - declarations
// TODO: Add class declarations
// TODO: Integrate class declarations to output file structure
// TODO: Add missing tests for declaration files, function declarations and
// returns
private let filePath = CommandLine.arguments[1] + "/tests/"
do {
let driver = JKRDriver(folderPath: filePath,
parser: JKRAntlrParser(),
language: .java)
try driver.transpile()
let result = driver.run()
}
catch (let error) {
log("Failed :(")
log(String(describing: error))
}
| apache-2.0 |
richeterre/jumu-nordost-ios | JumuNordost/Application/PerformanceFilterView.swift | 1 | 2307 | //
// PerformanceFilterView.swift
// JumuNordost
//
// Created by Martin Richter on 20/02/16.
// Copyright © 2016 Martin Richter. All rights reserved.
//
import Cartography
import ReactiveCocoa
class PerformanceFilterView: UIView {
let selectedDateIndex = MutableProperty<Int?>(nil)
let selectedVenueIndex = MutableProperty<Int?>(nil)
private let dateSwitcher: UISegmentedControl
private let venueSwitcher: UISegmentedControl
// MARK: - Lifecycle
init(dateStrings: [String], venueNames: [String]) {
dateSwitcher = UISegmentedControl(items: dateStrings)
venueSwitcher = UISegmentedControl(items: venueNames)
super.init(frame: CGRectZero)
selectedDateIndex.producer.startWithNext { [weak self] index in
self?.dateSwitcher.selectedSegmentIndex = index ?? -1
}
selectedVenueIndex.producer.startWithNext { [weak self] index in
self?.venueSwitcher.selectedSegmentIndex = index ?? -1
}
dateSwitcher.addTarget(self, action: #selector(dateSwitcherChanged(_:)), forControlEvents: .ValueChanged)
venueSwitcher.addTarget(self, action: #selector(venueSwitcherChanged(_:)), forControlEvents: .ValueChanged)
addSubview(dateSwitcher)
addSubview(venueSwitcher)
makeConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
private func makeConstraints() {
constrain(self, dateSwitcher, venueSwitcher) { superview, dateSwitcher, venueSwitcher in
dateSwitcher.top == superview.topMargin
dateSwitcher.left == superview.leftMargin
dateSwitcher.right == superview.rightMargin
venueSwitcher.top == dateSwitcher.bottom + 8
venueSwitcher.left == superview.leftMargin
venueSwitcher.right == superview.rightMargin
venueSwitcher.bottom == superview.bottomMargin
}
}
// MARK: - User Interaction
func dateSwitcherChanged(switcher: UISegmentedControl) {
selectedDateIndex.value = switcher.selectedSegmentIndex
}
func venueSwitcherChanged(switcher: UISegmentedControl) {
selectedVenueIndex.value = switcher.selectedSegmentIndex
}
}
| mit |
bugsnag/bugsnag-cocoa | features/fixtures/shared/scenarios/ThermalStateBreadcrumbScenario.swift | 1 | 776 | //
// ThermalStateBreadcrumbScenario.swift
// iOSTestApp
//
// Created by Nick Dowell on 18/08/2021.
// Copyright © 2021 Bugsnag Inc. All rights reserved.
//
@available(iOS 11.0, tvOS 11.0, *)
class ThermalStateBreadcrumbScenario: Scenario {
override func startBugsnag() {
config.autoTrackSessions = false
config.enabledBreadcrumbTypes = [.state]
super.startBugsnag()
}
override func run() {
NotificationCenter.default.post(name: ProcessInfo.thermalStateDidChangeNotification, object: ProcessInfoStub())
Bugsnag.notifyError(NSError(domain: "DummyError", code: 0))
}
class ProcessInfoStub: NSObject {
@objc let thermalState: ProcessInfo.ThermalState = .critical
}
}
| mit |
AlbanPerli/HandWriting-Recognition-iOS | HandWriting-Learner/UIImage+Processing.swift | 1 | 2290 | import UIKit
extension UIImage {
// Retreive intensity (alpha) of each pixel from this image
func pixelsArray()->(pixelValues: [Float], width: Int, height: Int){
let width = Int(self.size.width)
let height = Int(self.size.height)
var pixelsArray = [Float]()
let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage))
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let bytesPerRow = CGImageGetBytesPerRow(self.CGImage)
let bytesPerPixel = (CGImageGetBitsPerPixel(self.CGImage) / 8)
var position = 0
for _ in 0..<height {
for _ in 0..<width {
let alpha = Float(data[position + 3])
pixelsArray.append(alpha / 255)
position += bytesPerPixel
}
if position % bytesPerRow != 0 {
position += (bytesPerRow - (position % bytesPerRow))
}
}
return (pixelsArray,width,height)
}
// Resize UIImage to the given size
// No ratio check - no scale check
func toSize(newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContext(newSize)
self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
// Extract sub image based on the given frame
// x,y top left | x,y bottom right | pixels margin above this frame
func extractFrame(var topLeft: CGPoint, var bottomRight: CGPoint, pixelMargin: CGFloat) ->UIImage {
topLeft.x = topLeft.x - pixelMargin
topLeft.y = topLeft.y - pixelMargin
bottomRight.x = bottomRight.x + pixelMargin
bottomRight.y = bottomRight.y + pixelMargin
let size:CGSize = CGSizeMake(bottomRight.x-topLeft.x, bottomRight.y-topLeft.y)
let rect = CGRectMake(-topLeft.x, -topLeft.y, self.size.width, self.size.height)
UIGraphicsBeginImageContext(size)
self.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
} | mit |
LesCoureurs/Courir | Courir/Courir/SettingsManager.swift | 1 | 575 | //
// SettingsManager.swift
// Courir
//
// Created by Karen on 6/4/16.
// Copyright © 2016 NUS CS3217. All rights reserved.
//
import Foundation
class SettingsManager {
static let _instance = SettingsManager()
static let nameKey = "myName"
private static let defaults = NSUserDefaults.standardUserDefaults()
private init() {}
func get(key: String) -> AnyObject? {
return SettingsManager.defaults.objectForKey(key)
}
func put(key: String, value: AnyObject) {
SettingsManager.defaults.setObject(value, forKey: key)
}
} | mit |
eminemoholic/SoruVA | soru/AppDelegate.swift | 1 | 2241 | //
// AppDelegate.swift
// soru
//
import UIKit
import BMSCore
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let myBMSClient = BMSClient.sharedInstance
myBMSClient.initialize(bluemixRegion: BMSClient.Region.usSouth)
myBMSClient.requestTimeout = 10.0 // seconds
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
RamonGilabert/Prodam | Prodam/Prodam/LaunchStarter.swift | 1 | 2236 | import Cocoa
class LaunchStarter: NSObject {
class func toggleLaunchAtStartup() {
let itemReferences = itemReferencesInLoginItems()
let shouldBeToggled = (itemReferences.existingReference == nil)
if let loginItemsRef = LSSharedFileListCreate( nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue() as LSSharedFileListRef? {
if shouldBeToggled {
if let appUrl : CFURLRef = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath) {
LSSharedFileListInsertItemURL(loginItemsRef, itemReferences.lastReference, nil, nil, appUrl, nil, nil)
}
} else {
if let itemRef = itemReferences.existingReference {
LSSharedFileListItemRemove(loginItemsRef,itemRef);
}
}
}
}
class func applicationIsInStartUpItems() -> Bool {
return (itemReferencesInLoginItems().existingReference != nil)
}
class func itemReferencesInLoginItems() -> (existingReference: LSSharedFileListItemRef?, lastReference: LSSharedFileListItemRef?) {
if let appURL : NSURL = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath) {
if let loginItemsRef = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue() as LSSharedFileListRef? {
let loginItems: NSArray = LSSharedFileListCopySnapshot(loginItemsRef, nil).takeRetainedValue() as NSArray
let lastItemRef: LSSharedFileListItemRef = loginItems.lastObject as! LSSharedFileListItemRef
for var i = 0; i < loginItems.count; ++i {
let currentItemRef: LSSharedFileListItemRef = loginItems.objectAtIndex(i) as! LSSharedFileListItemRef
if let itemURL = LSSharedFileListItemCopyResolvedURL(currentItemRef, 0, nil) {
if (itemURL.takeRetainedValue() as NSURL).isEqual(appURL) {
return (currentItemRef, lastItemRef)
}
}
}
return (nil, lastItemRef)
}
}
return (nil, nil)
}
}
| mit |
grandima/DMUtilities | DMUtilities/Classes/Protocols/DataProvider.swift | 1 | 914 | //
// DataProvider.swift
// Series
//
// Created by Dima Medynsky on 2/26/16.
// Copyright © 2016 Dima Medynsky. All rights reserved.
//
import Foundation
protocol DataProvider: class {
associatedtype Item
func object(at indexPath: IndexPath) -> Item
func numberOfItems(in section: Int) -> Int
}
protocol AugmentedDataProvider: DataProvider {
var numberOfSections: Int { get }
func titleForHeader(in section: Int) -> String?
}
extension AugmentedDataProvider {
var numberOfSections: Int { return 1 }
func titleForHeader(in section: Int) -> String? { return nil }
}
protocol DataProviderDelegate: class {
associatedtype Item: Any
func dataProviderDidUpdate(updates: [DataProviderUpdate<Item>]?)
}
enum DataProviderUpdate<Object> {
case Insert(IndexPath)
case Update(IndexPath, Object)
case Move(IndexPath, IndexPath)
case Delete(IndexPath)
}
| mit |
jovito-royeca/CardMagusKit | CardMagusKit/Classes/CMBorder+CoreDataClass.swift | 1 | 192 | //
// CMBorder+CoreDataClass.swift
// Pods
//
// Created by Jovito Royeca on 15/04/2017.
//
//
import Foundation
import CoreData
@objc(CMBorder)
open class CMBorder: NSManagedObject {
}
| mit |
lemberg/connfa-ios | Pods/SwiftDate/Sources/SwiftDate/Formatters/RelativeFormatter/languages/lang_zh_Hant.swift | 1 | 3659 | import Foundation
// swiftlint:disable type_name
public class lang_zhHant: RelativeFormatterLang {
/// Chinese (Traditional)
public static let identifier: String = "zh_Hant"
public required init() {}
public func quantifyKey(forValue value: Double) -> RelativeFormatter.PluralForm? {
return .other
}
public var flavours: [String: Any] {
return [
RelativeFormatter.Flavour.long.rawValue: self._long,
RelativeFormatter.Flavour.narrow.rawValue: self._narrow,
RelativeFormatter.Flavour.short.rawValue: self._short
]
}
private var _short: [String: Any] {
return [
"year": [
"previous": "去年",
"current": "今年",
"next": "明年",
"past": "{0} 年前",
"future": "{0} 年後"
],
"quarter": [
"previous": "上一季",
"current": "這一季",
"next": "下一季",
"past": "{0} 季前",
"future": "{0} 季後"
],
"month": [
"previous": "上個月",
"current": "本月",
"next": "下個月",
"past": "{0} 個月前",
"future": "{0} 個月後"
],
"week": [
"previous": "上週",
"current": "本週",
"next": "下週",
"past": "{0} 週前",
"future": "{0} 週後"
],
"day": [
"previous": "昨天",
"current": "今天",
"next": "明天",
"past": "{0} 天前",
"future": "{0} 天後"
],
"hour": [
"current": "這一小時",
"past": "{0} 小時前",
"future": "{0} 小時後"
],
"minute": [
"current": "這一分鐘",
"past": "{0} 分鐘前",
"future": "{0} 分鐘後"
],
"second": [
"current": "現在",
"past": "{0} 秒前",
"future": "{0} 秒後"
],
"now": "現在"
]
}
private var _narrow: [String: Any] {
return [
"year": [
"previous": "去年",
"current": "今年",
"next": "明年",
"past": "{0} 年前",
"future": "{0} 年後"
],
"quarter": [
"previous": "上一季",
"current": "這一季",
"next": "下一季",
"past": "{0} 季前",
"future": "{0} 季後"
],
"month": [
"previous": "上個月",
"current": "本月",
"next": "下個月",
"past": "{0} 個月前",
"future": "{0} 個月後"
],
"week": [
"previous": "上週",
"current": "本週",
"next": "下週",
"past": "{0} 週前",
"future": "{0} 週後"
],
"day": [
"previous": "昨天",
"current": "今天",
"next": "明天",
"past": "{0} 天前",
"future": "{0} 天後"
],
"hour": [
"current": "這一小時",
"past": "{0} 小時前",
"future": "{0} 小時後"
],
"minute": [
"current": "這一分鐘",
"past": "{0} 分鐘前",
"future": "{0} 分鐘後"
],
"second": [
"current": "現在",
"past": "{0} 秒前",
"future": "{0} 秒後"
],
"now": "現在"
]
}
private var _long: [String: Any] {
return [
"year": [
"previous": "去年",
"current": "今年",
"next": "明年",
"past": "{0} 年前",
"future": "{0} 年後"
],
"quarter": [
"previous": "上一季",
"current": "這一季",
"next": "下一季",
"past": "{0} 季前",
"future": "{0} 季後"
],
"month": [
"previous": "上個月",
"current": "本月",
"next": "下個月",
"past": "{0} 個月前",
"future": "{0} 個月後"
],
"week": [
"previous": "上週",
"current": "本週",
"next": "下週",
"past": "{0} 週前",
"future": "{0} 週後"
],
"day": [
"previous": "昨天",
"current": "今天",
"next": "明天",
"past": "{0} 天前",
"future": "{0} 天後"
],
"hour": [
"current": "這一小時",
"past": "{0} 小時前",
"future": "{0} 小時後"
],
"minute": [
"current": "這一分鐘",
"past": "{0} 分鐘前",
"future": "{0} 分鐘後"
],
"second": [
"current": "現在",
"past": "{0} 秒前",
"future": "{0} 秒後"
],
"now": "現在"
]
}
}
| apache-2.0 |
John-Connolly/SwiftQ | Sources/SwiftQ/Worker/Worker.swift | 1 | 3773 | //
// Worker.swift
// SwiftQ
//
// Created by John Connolly on 2017-05-07.
// Copyright © 2017 John Connolly. All rights reserved.
//
import Foundation
import Dispatch
final class Worker {
private let concurrentQueue = DispatchQueue(label: "com.swiftq.concurrent", attributes: .concurrent)
private let queue: ReliableQueue
private let decoder: Decoder
private let semaphore: DispatchSemaphore
private let middlewares: MiddlewareCollection
init(decoder: Decoder,
config: RedisConfig,
concurrency: Int,
queue: String,
consumerName: String?,
middleware: [Middleware]) throws {
self.semaphore = DispatchSemaphore(value: concurrency)
self.decoder = decoder
self.middlewares = MiddlewareCollection(middleware)
self.queue = try ReliableQueue(queue: queue,
config: config,
consumer: consumerName,
concurrency: concurrency)
try self.queue.prepare()
}
/// Atomically transfers a task from the work queue into the
/// processing queue then enqueues it to the worker.
func run() {
repeat {
semaphore.wait()
AsyncWorker(queue: concurrentQueue) {
defer {
self.semaphore.signal()
}
do {
let task = try self.queue.bdequeue { data in
return try self.decoder.decode(data: data)
}
task.map(self.execute)
} catch {
Logger.log(error)
}
}.run()
} while true
}
private func execute(_ task: Task) {
do {
middlewares.before(task: task)
try task.execute()
middlewares.after(task: task)
complete(task: task)
} catch {
middlewares.after(task: task, with: error)
failure(task, error: error)
}
}
/// Called when a task is successfully completed. If the task is
/// periodic it is re-queued into the zset.
private func complete(task: Task) {
do {
if let task = task as? PeriodicTask {
let box = try PeriodicBox(task)
try queue.requeue(item: box, success: true)
} else {
try queue.complete(item: try EnqueueingBox(task), success: true)
}
} catch {
Logger.log(error)
}
}
/// Called when the tasks fails. Note: If the tasks recovery
/// stategy is none it will never be ran again.
private func failure(_ task: Task, error: Error) {
do {
switch task.recoveryStrategy {
case .none:
try queue.complete(item: EnqueueingBox(task), success: false)
case .retry(let retries):
if task.shouldRetry(retries) {
task.retry()
try queue.requeue(item: EnqueueingBox(task), success: false)
} else {
try queue.complete(item: EnqueueingBox(task), success: false)
}
case .log:
try queue.log(task: task, error: error)
}
} catch {
Logger.log(error)
}
}
}
enum Result<T> {
case success(T)
case failure(Error)
}
| mit |
castial/Quick-Start-iOS | Quick-Start-iOS/Vendors/HYKeychainHelper/HYKeychainHelper.swift | 1 | 2655 | //
// HYKeychainHelper.swift
// Quick-Start-iOS
//
// Created by hyyy on 2017/1/18.
// Copyright © 2017年 hyyy. All rights reserved.
//
import Foundation
struct HYKeychainHelper {
static func password(service: String, account: String, accessGroup: String? = nil) -> String? {
var item = HYKeychainItem (service: service, account: account)
item.accessGroup = accessGroup
do {
try item.queryPassword()
}catch {
fatalError("Error fetching password item - \(error)")
}
return item.password
}
static func passwordData(service: String, account: String, accessGroup: String? = nil) -> Data? {
var item = HYKeychainItem (service: service, account: account)
item.accessGroup = accessGroup
do {
try item.queryPassword()
}catch {
fatalError("Error fetching passwordData item - \(error)")
}
return item.passwordData
}
static func deletePassword(service: String, account: String, accessGroup: String? = nil) {
var item = HYKeychainItem (service: service, account: account)
item.accessGroup = accessGroup
do {
try item.delete()
} catch {
fatalError("Error deleting password item - \(error)")
}
}
static func set(password: String, service: String, account: String, accessGroup: String? = nil) {
var item = HYKeychainItem (service: service, account: account)
item.accessGroup = accessGroup
item.password = password
do {
try item.save()
} catch {
fatalError("Error setting password item - \(error)")
}
}
static func set(passwordData: Data, service: String, account: String, accessGroup: String? = nil) {
var item = HYKeychainItem (service: service, account: account)
item.accessGroup = accessGroup
item.passwordData = passwordData
do {
try item.save()
}catch {
fatalError("Error setting password item - \(error)")
}
}
static func allAccount() -> Array<[String : AnyObject]> {
return allAccounts(forService: nil)
}
static func allAccounts(forService service: String?) -> Array<[String : AnyObject]> {
var item = HYKeychainItem ()
item.service = service
var allAccountsArr: Array<[String : AnyObject]>
do {
try allAccountsArr = item.queryAll()
} catch {
fatalError("Error setting password item - \(error)")
}
return allAccountsArr
}
}
| mit |
an23lm/Player | Player/PauseView.swift | 1 | 1095 | //
// PauseView.swift
// Player
//
// Created by Ansèlm Joseph on 11/07/2017.
// Copyright © 2017 Ansèlm Joseph. All rights reserved.
//
import Cocoa
@IBDesignable
class PauseView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
let width = self.frame.width
let height = self.frame.height
let center = CGPoint(x: width/2, y: height/2)
let lineWidth = width / 4
let lineHeight = height - 4
let rect1 = NSRect(x: center.x - lineWidth - lineWidth/3, y: center.y - lineHeight/2, width: lineWidth, height: lineHeight)
let path1 = NSBezierPath(roundedRect: rect1, xRadius: 2, yRadius: 2)
NSColor.black.setFill()
let rect2 = NSRect(x: center.x + lineWidth/3, y: center.y - lineHeight/2, width: lineWidth, height: lineHeight)
let path2 = NSBezierPath(roundedRect: rect2, xRadius: 2, yRadius: 2)
NSColor.black.setFill()
path1.fill()
path2.fill()
}
}
| apache-2.0 |
adrian-kubala/MyPlaces | MyPlaces/CreatorViewControllerDelegate.swift | 1 | 280 | //
// CreatorViewControllerDelegate.swift
// MyPlaces
//
// Created by Adrian Kubała on 07.04.2017.
// Copyright © 2017 Adrian Kubała. All rights reserved.
//
import Foundation
protocol CreatorViewControllerDelegate: class {
func didCreatePlace(_ place: Place)
}
| mit |
Rochester-Ting/DouyuTVDemo | RRDouyuTV/RRDouyuTV/Classes/Home(首页)/ViewController/FunnyVC.swift | 1 | 2895 | //
// FunnyVC.swift
// RRDouyuTV
//
// Created by 丁瑞瑞 on 18/10/16.
// Copyright © 2016年 Rochester. All rights reserved.
//
import UIKit
fileprivate let kItemMargin : CGFloat = 10
fileprivate let kItemWidth : CGFloat = (kScreenW - 3 * kItemMargin) / 2
fileprivate let kItemHeight : CGFloat = kItemWidth * 3 / 4
fileprivate let kNormalCellId = "kNormalCellId"
class FunnyVC: BaseViewController {
let funnyVM : FunnyViewModel = FunnyViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemWidth, height: kItemHeight)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.scrollDirection = .vertical
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.register(UINib(nibName: "RecommandNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellId)
collectionView.contentInset = UIEdgeInsets(top: kItemMargin, left: 0, bottom: kStatusBarH + kNavigationH + kTabBarH + kTitleViewH, right: 0)
collectionView.delegate = self
collectionView.dataSource = self
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = UIColor.white
setUpUI()
}
}
extension FunnyVC{
override func setUpUI() {
// super.setUpUI()
view.addSubview(collectionView)
contentView = collectionView
super.setUpUI()
funnyVM.requestFunnyData {
self.collectionView.reloadData()
self.stopAnimation()
}
}
}
extension FunnyVC : UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let isVertical = funnyVM.funnyModels[indexPath.item].isVertical
isVertical == 0 ? pushVC() : presentVC()
}
func pushVC() {
navigationController?.pushViewController(RoomNormalVC(), animated: true)
}
func presentVC(){
present(RoomBeatifulVC(), animated: true, completion: nil)
}
}
extension FunnyVC : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return funnyVM.funnyModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellId, for: indexPath) as! RecommandNormalCell
cell.achor = funnyVM.funnyModels[indexPath.row]
return cell
}
}
| mit |
k-o-d-e-n/CGLayout | Sources/Classes/rtl.cglayout.swift | 1 | 235 | //
// rtl.cglayout.swift
// Pods
//
// Created by Denis Koryttsev on 13/10/2019.
//
import Foundation
public struct CGLConfiguration {
public var isRTLMode: Bool = false
public static var `default` = CGLConfiguration()
}
| mit |
rajeejones/SavingPennies | Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationBallGridBeat.swift | 5 | 2015 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallGridBeat: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
let circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let durations = [0.96, 0.93, 1.19, 1.13, 1.34, 0.94, 1.2, 0.82, 1.19]
let beginTime = CACurrentMediaTime()
let beginTimes = [0.36, 0.4, 0.68, 0.41, 0.71, -0.15, -0.12, 0.01, 0.32]
let animation = self.animation
// Draw circles
for i in 0 ..< 3 {
for j in 0 ..< 3 {
let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(j) + circleSpacing * CGFloat(j),
y: y + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
width: circleSize,
height: circleSize)
animation.duration = durations[3 * i + j]
animation.beginTime = beginTime + beginTimes[3 * i + j]
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallGridBeat {
var animation: CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "opacity")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.7, 1]
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
}
| gpl-3.0 |
BeauNouvelle/ChatParser | ChatParser/Example/ViewController.swift | 1 | 883 | //
// ViewController.swift
// Example
//
// Created by Beau Young on 19/01/2016.
// Copyright © 2016 Beau Nouvelle. All rights reserved.
//
import UIKit
import ChatParser
class ViewController: UIViewController {
@IBOutlet weak var inputTextField: UITextField!
@IBOutlet weak var outputTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
ChatParser().extractContent(.Any, .Mentions, fromString: textField.text!) { (prettyJSON) -> () in
if let prettyJSON = prettyJSON {
self.outputTextView.text = prettyJSON
}
}
return true
}
} | mit |
angelsteger/week3 | week3/week3/AppDelegate.swift | 1 | 2142 | //
// AppDelegate.swift
// week3
//
// Created by Angel Steger on 9/29/15.
// Copyright © 2015 Angel Steger. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
iOS-Swift-Developers/Swift | 基础语法/Switch/main.swift | 1 | 3527 | //
// main.swift
// Switch
//
// Created by 韩俊强 on 2017/6/8.
// Copyright © 2017年 HaRi. All rights reserved.
//
import Foundation
/*
Swith
格式: switch(需要匹配的值) case 匹配的值: 需要执行的语句 break;
OC:
char rank = 'A';
switch (rank) {
case 'A':
NSLog(@"优");
break;
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
default:
NSLog(@"没有评级");
break;
}
可以穿透
char rank = 'A';
switch (rank) {
case 'A':
NSLog(@"优");
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
default:
NSLog(@"没有评级");
break;
}
可以不写default
char rank = 'A';
switch (rank) {
case 'A':
NSLog(@"优");
break;
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
}
default位置可以随便放
char rank = 'E';
switch (rank) {
default:
NSLog(@"没有评级");
break;
case 'A':
{
int score = 100;
NSLog(@"优");
break;
}
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
}
在case中定义变量需要加大括号, 否则作用域混乱
char rank = 'A';
switch (rank) {
case 'A':
{
int score = 100;
NSLog(@"优");
break;
}
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
}
不能判断对象类型
NSNumber *num = @100;
switch (num) {
case @100:
NSLog(@"优");
break;
default:
NSLog(@"没有评级");
break;
}
*/
/** Swift:可以判断对象类型, OC必须是整数 **/
//不可以穿透
//可以不写break
var rank = "A"
switch rank{
case "A": // 相当于if
print("A")
case "B": // 相当于 else if
print("B")
case "C": // 相当于 else if
print("C")
default: // 相当于 else
print("其他")
}
/*
因为不能穿透所以不能这么写
var rank1 = "A"
switch rank1{
case "A":
case "B":
print("B")
case "C":
print("C")
default:
print("其他")
}
*/
//只能这么写
var rank1 = "A"
switch rank1{
case "A", "B": // 注意OC不能这样写
print("A&&B")
case "C":
print("C")
default:
print("其他")
}
/*
//不能不写default
var rank2 = "A"
switch rank2{
case "A":
print("A")
case "B":
print("B")
case "C":
print("C")
}
*/
/*
//default位置只能在最后
var rank3 = "A"
switch rank3{
default:
print("其他")
case "A":
print("A")
case "B":
print("B")
case "C":
print("C")
}
*/
//在case中定义变量不用加大括号
var rank4 = "A"
switch rank4{
case "A":
var num = 10
print("A")
case "B":
print("B")
case "C":
print("C")
default:
print("其他")
}
/*
区间和元组匹配
var num = 10
switch num{
case 1...9:
print("个位数")
case 10...99:
print("十位数")
default:
print("其他数")
}
var point = (10, 15)
switch point{
case (0, 0):
print("坐标原点")
case (1...10, 10...20):
print("坐标的X和Y在1~10之间") // 可以在元组中再加上区间
default:
print("Other")
}
*/
/*
//值绑定
var point = (1, 10)
switch point{
case (var x, 10): // 会将point中的x赋值给
print("x = \(x)")
case (var x, var y): // 会将point中xy的值赋值给xy
print("x = \(x) y = \(y)")
case var(x,y):
print("x = \(x) y =\(y)")
default:
print("Other")
}
//根据条件绑定
var point = (101, 100)
switch point{
// 只有where后面的条件表达式为真才赋值并执行case后的语句
case var(x, y) where x > y:
print("x = \(x) y = \(y)")
default:
print("Other")
}
*/
| mit |
Romdeau4/16POOPS | Helps_Kitchen_iOS/Help's Kitchen/Reservation.swift | 1 | 270 | //
// User.swift
// Help's Kitchen
//
// Created by Stephen Ulmer on 2/17/17.
// Copyright © 2017 Stephen Ulmer. All rights reserved.
//
import Foundation
class Reservation: NSObject{
var partySize: Int?
var name: String?
var dateTime: String?
}
| mit |
AboutObjectsTraining/swift-comp-reston-2017-02 | examples/swift-tool/ARC.playground/Contents.swift | 1 | 488 | import Foundation
class Human
{
var cats: [Cat] = []
func addCat(cat: Cat) {
cats.append(cat)
cat.owner = self
}
deinit {
print("Deinitializing \(self)")
}
}
class Cat
{
var owner: Human!
deinit {
print("Deinitializing \(self)")
}
}
func createCatAndOwner()
{
autoreleasepool {
let owner = Human()
owner.addCat(Cat())
print("Created \(owner) with \(owner.cats)")
}
}
createCatAndOwner()
| mit |
anotheren/TrafficPolice | Source/Ex+UInt64.swift | 1 | 262 | //
// Ex+UInt64.swift
// TrafficPolice
//
// Created by 刘栋 on 2016/11/18.
// Copyright © 2016年 anotheren.com. All rights reserved.
//
import Foundation
extension UInt64 {
public var double: Double {
return Double(self)
}
}
| mit |
doronkatz/firefox-ios | XCUITests/ToolbarTest.swift | 2 | 4168 | /* 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 XCTest
let website1: [String: String] = ["url": "www.mozilla.org", "label": "Internet for people, not profit — Mozilla", "value": "mozilla.org"]
let website2 = "yahoo.com"
class ToolbarTests: BaseTestCase {
var navigator: Navigator!
var app: XCUIApplication!
override func setUp() {
super.setUp()
app = XCUIApplication()
navigator = createScreenGraph(app).navigator(self)
}
override func tearDown() {
super.tearDown()
}
/**
* Tests landscape page navigation enablement with the URL bar with tab switching.
*/
func testLandscapeNavigationWithTabSwitch() {
XCUIDevice.shared().orientation = .landscapeLeft
// Check that url field is empty and it shows a placeholder
navigator.goto(NewTabScreen)
let urlPlaceholder = "Search or enter address"
XCTAssert(app.textFields["url"].exists)
let defaultValuePlaceholder = app.textFields["url"].placeholderValue!
// Check the url placeholder text and that the back and forward buttons are disabled
XCTAssertTrue(urlPlaceholder == defaultValuePlaceholder, "The placeholder does not show the correct value")
XCTAssertFalse(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
XCTAssertFalse(app.buttons["Reload"].isEnabled)
// Navigate to two pages and press back once so that all buttons are enabled in landscape mode.
navigator.openURL(urlString: website1["url"]!)
waitForValueContains(app.textFields["url"], value: website1["value"]!)
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
XCTAssertTrue(app.buttons["Reload"].isEnabled)
navigator.openURL(urlString: website2)
waitForValueContains(app.textFields["url"], value: website2)
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
app.buttons["URLBarView.backButton"].tap()
waitForValueContains(app.textFields["url"], value: website1["value"]!)
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertTrue(app.buttons["Forward"].isEnabled)
// Open new tab and then go back to previous tab to test navigation buttons.
navigator.goto(NewTabScreen)
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[website1["label"]!])
app.collectionViews.cells[website1["label"]!].tap()
waitForValueContains(app.textFields["url"], value: website1["value"]!)
// Test to see if all the buttons are enabled then close tab.
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertTrue(app.buttons["Forward"].isEnabled)
navigator.nowAt(BrowserTab)
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[website1["label"]!])
app.collectionViews.cells[website1["label"]!].swipeRight()
// Go Back to other tab to see if all buttons are disabled.
waitforExistence(app.collectionViews.cells["home"])
app.collectionViews.cells["home"].tap()
XCTAssertFalse(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
// Go back to portrait mode
XCUIDevice.shared().orientation = .portrait
}
func testClearURLTextUsingBackspace() {
navigator.openURL(urlString: website1["url"]!)
waitForValueContains(app.textFields["url"], value: website1["value"]!)
// Simulate pressing on backspace key should remove the text
app.textFields["url"].tap()
app.textFields["address"].typeText("\u{8}")
let value = app.textFields["address"].value
XCTAssertEqual(value as? String, "", "The url has not been removed correctly")
}
}
| mpl-2.0 |
HabitRPG/habitrpg-ios | Habitica Database/Habitica Database/Models/Content/RealmSpecialItem.swift | 1 | 643 | //
// RealmSpecialItem.swift
// Habitica Database
//
// Created by Phillip Thelen on 08.06.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import RealmSwift
class RealmSpecialItem: RealmItem, SpecialItemProtocol {
var target: String?
var immediateUse: Bool = false
var silent: Bool = false
convenience init(_ specialItem: SpecialItemProtocol) {
self.init(item: specialItem)
target = specialItem.target
immediateUse = specialItem.immediateUse
silent = specialItem.silent
itemType = ItemType.special.rawValue
}
}
| gpl-3.0 |
andrea-prearo/SwiftExamples | ParallaxAndScale/ParallaxAndScale/MainViewController.swift | 1 | 5334 | //
// MainViewController.swift
// ParallaxAndScale
//
// Created by Andrea Prearo on 8/31/18.
// Copyright © 2018 Andrea Prearo. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
// MARK: - Constants
struct Constants {
static fileprivate let headerHeight: CGFloat = 210
}
// MARK: - Properties
private var scrollView: UIScrollView!
private var label: UILabel!
private var headerContainerView: UIView!
private var headerImageView: UIImageView!
private var headerTopConstraint: NSLayoutConstraint!
private var headerHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
scrollView = createScrollView()
headerContainerView = createHeaderContainerView()
headerImageView = createHeaderImageView()
label = createLabel()
headerContainerView.addSubview(headerImageView)
scrollView.addSubview(headerContainerView)
scrollView.addSubview(label)
view.addSubview(scrollView)
arrangeConstraints()
}
}
private extension MainViewController {
func createScrollView() -> UIScrollView {
let scrollView = UIScrollView()
scrollView.delegate = self
scrollView.alwaysBounceVertical = true
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}
func createHeaderContainerView() -> UIView {
let view = UIView()
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}
func createHeaderImageView() -> UIImageView {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
if let image = UIImage(named: "Coffee") {
imageView.image = image
}
imageView.clipsToBounds = true
return imageView
}
func createLabel() -> UILabel {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = .white
let titleFont = UIFont.preferredFont(forTextStyle: .title1)
if let boldDescriptor = titleFont.fontDescriptor.withSymbolicTraits(.traitBold) {
label.font = UIFont(descriptor: boldDescriptor, size: 0)
} else {
label.font = titleFont
}
label.textAlignment = .center
label.adjustsFontForContentSizeCategory = true
label.text = "Your content here"
return label
}
func arrangeConstraints() {
let scrollViewConstraints: [NSLayoutConstraint] = [
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
]
NSLayoutConstraint.activate(scrollViewConstraints)
headerTopConstraint = headerContainerView.topAnchor.constraint(equalTo: view.topAnchor)
headerHeightConstraint = headerContainerView.heightAnchor.constraint(equalToConstant: 210)
let headerContainerViewConstraints: [NSLayoutConstraint] = [
headerTopConstraint,
headerContainerView.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 1.0),
headerHeightConstraint
]
NSLayoutConstraint.activate(headerContainerViewConstraints)
let headerImageViewConstraints: [NSLayoutConstraint] = [
headerImageView.topAnchor.constraint(equalTo: headerContainerView.topAnchor),
headerImageView.leadingAnchor.constraint(equalTo: headerContainerView.leadingAnchor),
headerImageView.trailingAnchor.constraint(equalTo: headerContainerView.trailingAnchor),
headerImageView.bottomAnchor.constraint(equalTo: headerContainerView.bottomAnchor)
]
NSLayoutConstraint.activate(headerImageViewConstraints)
let labelConstraints: [NSLayoutConstraint] = [
label.topAnchor.constraint(equalTo: headerContainerView.bottomAnchor),
label.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 1.0),
label.heightAnchor.constraint(equalToConstant: 800)
]
NSLayoutConstraint.activate(labelConstraints)
}
}
extension MainViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y < 0.0 {
headerHeightConstraint?.constant = Constants.headerHeight - scrollView.contentOffset.y
} else {
let parallaxFactor: CGFloat = 0.25
let offsetY = scrollView.contentOffset.y * parallaxFactor
let minOffsetY: CGFloat = 8.0
let availableOffset = min(offsetY, minOffsetY)
let contentRectOffsetY = availableOffset / Constants.headerHeight
headerTopConstraint?.constant = view.frame.origin.y
headerHeightConstraint?.constant = Constants.headerHeight - scrollView.contentOffset.y
headerImageView.layer.contentsRect = CGRect(x: 0, y: -contentRectOffsetY, width: 1, height: 1)
}
}
}
| mit |
OHeroJ/twicebook | Sources/App/Controllers/UserController.swift | 1 | 7737 | //
// UserController.swift
// seesometop
//
// Created by laijihua on 29/08/2017.
//
//
import Foundation
import Vapor
final class UserController: ControllerRoutable {
init(builder: RouteBuilder) {
/// 用户修改 /user/update
builder.put("update",Int.parameter, handler: update)
/// 绑定微信信息
builder.post("bindwx", handler: bindWx)
/// 用户登出
builder.get("logout", Int.parameter, handler: logout)
/// 获取用户信息
builder.get("/", Int.parameter, handler: show)
/// 获取用户列表
builder.get("list", handler: getNewerUserList)
/// 朋友关系
builder.post("friend", handler: friendAdd)
builder.delete("friend", handler: friendRemove)
builder.get("friend", Int.parameter, handler:haveFriend)
builder.get("friends", handler: userFriends)
/// 举报
builder.post("report", handler: report)
}
// 绑定微信
func bindWx(req: Request) throws -> ResponseRepresentable {
guard let sign = req.data[User.Key.wxSign]?.string,
let number = req.data[User.Key.wxNumber]?.string,
let userId = req.data[User.Key.id] else {
return try ApiRes.error(code: 1, msg: "参数错误")
}
guard let user = try User.find(userId) else {
return try ApiRes.error(code: 2, msg: "未找到该用户")
}
if user.wxSign.count > 0 && user.wxSign != sign {
return try ApiRes.error(code: 3, msg: "该账号已绑定")
}
user.wxSign = sign
user.wxNumber = number
try user.save()
return try ApiRes.success(data:["user": user])
}
/// 获取最新的用户信息
func getNewerUserList(req: Request) throws -> ResponseRepresentable {
let isNewer = req.data["isNew"]?.int ?? 0 // 0 not | 1 newer
var query = try User.makeQuery()
if isNewer == 1 {
query = try query.sort(User.Key.createTime, .descending)
}
var friendIds = [Identifier]()
if let userId = req.data["userId"]?.int {
friendIds = try Friend.makeQuery()
.filter(Friend.Key.masterId, userId)
.all()
.map({ $0.friendId })
}
return try User.page(request: req, query: query, resultJSONHook: { (user) -> User in
if let thisId = user.id {
if friendIds.contains(thisId) {
user.isFriend = true
}
}
return user
})
}
func report(request: Request) throws -> ResponseRepresentable {
guard let userId = request.data["userId"]?.int else {
return try ApiRes.error(code: 1, msg: "MISS USERID")
}
guard let reportId = request.data["reportId"]?.int else {
return try ApiRes.error(code: 2, msg: "miss report ID")
}
if userId == reportId {return try ApiRes.error(code: 3, msg: "miss UserId")}
guard let reportUser = try User.find(reportId) else {
return try ApiRes.error(code: 3, msg: "miss user")
}
reportUser.reportCount += 1
try reportUser.save()
return try ApiRes.success(data:["success": true])
}
func userFriends(request: Request) throws -> ResponseRepresentable {
guard let masterId = request.data[Friend.Key.masterId]?.int else {
return try ApiRes.error(code: 1, msg: "miss masterId")
}
let friends = try Friend.makeQuery().filter(Friend.Key.masterId, masterId).all()
var users = [User]()
for friend in friends {
if let user = try User.find(friend.friendId) {
users.append(user)
}
}
return try ApiRes.success(data:["friends": users])
}
func haveFriend(request: Request) throws -> ResponseRepresentable {
let friendId = try request.parameters.next(Int.self)
guard let userId = request.data[Friend.Key.masterId]?.int else {
return try ApiRes.error(code: 1, msg: "misss master_id")
}
let friends = try Friend.makeQuery().and { (andGroup) in
try andGroup.filter(Friend.Key.masterId, userId)
try andGroup.filter(Friend.Key.friendId, friendId)
}
if let _ = try friends.first(){
return try ApiRes.success(data:["isFriend": true])
} else {
return try ApiRes.success(data:["isFriend": false])
}
}
func friendRemove(request: Request) throws -> ResponseRepresentable {
guard let userId = request.data[Friend.Key.masterId]?.int else {
return try ApiRes.error(code: 1, msg: "misss master_id")
}
guard let friendId = request.data[Friend.Key.friendId]?.int else {
return try ApiRes.error(code: 2, msg: "miss friend_id")
}
let friends = try Friend.makeQuery().and { (andGroup) in
try andGroup.filter(Friend.Key.masterId, userId)
try andGroup.filter(Friend.Key.friendId, friendId)
}
guard let friend = try friends.first() else {
return try ApiRes.error(code: 3, msg: "not found friend ship")
}
try friend.delete()
return try ApiRes.success(data:["ret": true])
}
func friendAdd(request: Request) throws -> ResponseRepresentable {
guard let userId = request.data[Friend.Key.masterId]?.int else {
return try ApiRes.error(code: 1, msg: "misss master_id")
}
guard let friendId = request.data[Friend.Key.friendId]?.int else {
return try ApiRes.error(code: 2, msg: "miss friend_id")
}
let friends = try Friend.makeQuery().and { (andGroup) in
try andGroup.filter(Friend.Key.masterId, userId)
try andGroup.filter(Friend.Key.friendId, friendId)
}
if let _ = try friends.first() {
// 已收藏
} else {
let frindship = Friend(masterId: Identifier(userId), friendId: Identifier(friendId))
try frindship.save()
}
return try ApiRes.success(data:["ret": true])
}
func show(request: Request) throws -> ResponseRepresentable {
let userId = try request.parameters.next(Int.self)
guard let user = try User.find(userId) else {
return try ApiRes.error(code: 1, msg:"user not found")
}
return try ApiRes.success(data:["user": user])
}
func logout(request: Request) throws -> ResponseRepresentable {
let userId = try request.parameters.next(Int.self)
if let token = try UserToken.makeQuery().filter(UserToken.Key.userId, userId).first() {
try token.delete()
}
return try ApiRes.success(data:"success")
}
func update(request: Request) throws -> ResponseRepresentable {
let userId = try request.parameters.next(Int.self)
guard let user = try User.find(userId) else {
return try ApiRes.error(code: 1, msg: "user not found")
}
// 修改昵称
if let name = request.data[User.Key.name]?.string {
user.name = name
}
// 修改密码
if let pwd = request.data[User.Key.password]?.string {
user.password = pwd
}
// 修改昵称
if let avator = request.data[User.Key.avator]?.string {
user.avator = avator
}
// 修改用户简洁
if let info = request.data[User.Key.info]?.string {
user.info = info
}
try user.save()
return try ApiRes.success(data:["user": user])
}
}
| mit |
kmalkic/LazyKit | LazyKit/Classes/Theming/Sets/Models/LazyParagraph.swift | 1 | 2007 | //
// LazyParagraph.swift
// LazyKit
//
// Created by Kevin Malkic on 28/04/2015.
// Copyright (c) 2015 Malkic Kevin. All rights reserved.
//
import UIKit
internal class LazyParagraph {
var lineSpacing: LazyMeasure?
var paragraphSpacing: LazyMeasure?
var headIndent: LazyMeasure?
var alignment: LazyTextAlignment?
var lineBreakMode: LazyLineBreakMode?
func convertWordWrap(_ wordWrap: String) -> NSLineBreakMode {
switch wordWrap {
case "word-wrapping":
return .byWordWrapping
case "char-wrapping":
return .byCharWrapping
case "clipping":
return .byClipping
case "truncating-head":
return .byTruncatingHead
case "truncating-tail":
return .byTruncatingTail
case "truncating-middle":
return .byTruncatingMiddle
default:
break
}
return .byTruncatingTail
}
func paragraphStyle() -> NSParagraphStyle! {
let paragraphStyle = NSMutableParagraphStyle()
if let value = lineSpacing?.value {
paragraphStyle.lineSpacing = value
}
if let value = paragraphSpacing?.value {
paragraphStyle.paragraphSpacing = value
}
if let value = headIndent?.value {
paragraphStyle.firstLineHeadIndent = value
}
if let value = alignment {
paragraphStyle.alignment = value.alignment!
} else {
paragraphStyle.alignment = .left
}
if let value = lineBreakMode {
paragraphStyle.lineBreakMode = value
} else {
paragraphStyle.lineBreakMode = .byTruncatingTail
}
return paragraphStyle
}
}
| mit |
roambotics/swift | test/SILGen/default_arguments.swift | 2 | 26292 |
// RUN: %target-swift-emit-silgen -module-name default_arguments -Xllvm -sil-full-demangle -swift-version 4 %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -module-name default_arguments -Xllvm -sil-full-demangle -swift-version 4 %s | %FileCheck %s --check-prefix=NEGATIVE
// __FUNCTION__ used as top-level parameter produces the module name.
// CHECK-LABEL: sil [ossa] @main
// CHECK: string_literal utf8 "default_arguments"
// Default argument for first parameter.
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments7defarg11i1d1sySi_SdSStFfA_ : $@convention(thin) () -> Int
// CHECK: [[LIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 17
// CHECK: [[INT:%[0-9]+]] = metatype $@thin Int.Type
// CHECK: [[CVT:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC
// CHECK: [[RESULT:%[0-9]+]] = apply [[CVT]]([[LIT]], [[INT]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: return [[RESULT]] : $Int
// Default argument for third parameter.
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments7defarg11i1d1sySi_SdSStFfA1_ : $@convention(thin) () -> @owned String
// CHECK: [[LIT:%[0-9]+]] = string_literal utf8 "Hello"
// CHECK: [[LEN:%[0-9]+]] = integer_literal $Builtin.Word, 5
// CHECK: [[STRING:%[0-9]+]] = metatype $@thin String.Type
// CHECK: [[CVT:%[0-9]+]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC
// CHECK: [[RESULT:%[0-9]+]] = apply [[CVT]]([[LIT]], [[LEN]], {{[^,]+}}, [[STRING]]) : $@convention(method)
// CHECK: return [[RESULT]] : $String
func defarg1(i: Int = 17, d: Double, s: String = "Hello") { }
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments15testDefaultArg1yyF
func testDefaultArg1() {
// CHECK: [[FLOATLIT:%[0-9]+]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x4009000000000000|0x4000C800000000000000}}
// CHECK: [[FLOAT64:%[0-9]+]] = metatype $@thin Double.Type
// CHECK: [[LITFN:%[0-9]+]] = function_ref @$sSd20_builtinFloatLiteralSdBf{{[_0-9]*}}__tcfC
// CHECK: [[FLOATVAL:%[0-9]+]] = apply [[LITFN]]([[FLOATLIT]], [[FLOAT64]])
// CHECK: [[DEF0FN:%[0-9]+]] = function_ref @$s17default_arguments7defarg1{{.*}}A_
// CHECK: [[DEF0:%[0-9]+]] = apply [[DEF0FN]]()
// CHECK: [[DEF2FN:%[0-9]+]] = function_ref @$s17default_arguments7defarg1{{.*}}A1_
// CHECK: [[DEF2:%[0-9]+]] = apply [[DEF2FN]]()
// CHECK: [[FNREF:%[0-9]+]] = function_ref @$s17default_arguments7defarg1{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FNREF]]([[DEF0]], [[FLOATVAL]], [[DEF2]])
defarg1(d:3.125)
}
func defarg2(_ i: Int, d: Double = 3.125, s: String = "Hello") { }
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments15testDefaultArg2{{[_0-9a-zA-Z]*}}F
func testDefaultArg2() {
// CHECK: [[INTLIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 5
// CHECK: [[INT64:%[0-9]+]] = metatype $@thin Int.Type
// CHECK: [[LITFN:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC
// CHECK: [[I:%[0-9]+]] = apply [[LITFN]]([[INTLIT]], [[INT64]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [[DFN:%[0-9]+]] = function_ref @$s17default_arguments7defarg2{{.*}}A0_ : $@convention(thin) () -> Double
// CHECK: [[D:%[0-9]+]] = apply [[DFN]]() : $@convention(thin) () -> Double
// CHECK: [[SFN:%[0-9]+]] = function_ref @$s17default_arguments7defarg2{{.*}}A1_ : $@convention(thin) () -> @owned String
// CHECK: [[S:%[0-9]+]] = apply [[SFN]]() : $@convention(thin) () -> @owned String
// CHECK: [[FNREF:%[0-9]+]] = function_ref @$s17default_arguments7defarg2{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Int, Double, @guaranteed String) -> ()
// CHECK: apply [[FNREF]]([[I]], [[D]], [[S]]) : $@convention(thin) (Int, Double, @guaranteed String) -> ()
defarg2(5)
}
func autocloseFile(x: @autoclosure () -> String = #file,
y: @autoclosure () -> Int = #line) { }
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments17testAutocloseFileyyF
func testAutocloseFile() {
// CHECK-LABEL: sil private [transparent] [ossa] @$s17default_arguments17testAutocloseFileyyFSSyXEfu_ : $@convention(thin) () -> @owned String
// CHECK: string_literal utf8{{.*}}default_arguments.swift
// CHECK-LABEL: sil private [transparent] [ossa] @$s17default_arguments17testAutocloseFileyyFSiyXEfu0_ : $@convention(thin) () -> Int
// CHECK: integer_literal $Builtin.IntLiteral, [[@LINE+1]]
autocloseFile()
}
func testMagicLiterals(file: String = #file,
function: String = #function,
line: Int = #line,
column: Int = #column) {}
// Check that default argument generator functions don't leak information about
// user's source.
//
// NEGATIVE-NOT: sil hidden [ossa] @$s17default_arguments17testMagicLiteralsySS4file_SS8functionSi4lineSi6columntFfA_
//
// NEGATIVE-NOT: sil hidden [ossa] @$s17default_arguments17testMagicLiteralsySS4file_SS8functionSi4lineSi6columntFfA0_
//
// NEGATIVE-NOT: sil hidden [ossa] @$s17default_arguments17testMagicLiteralsySS4file_SS8functionSi4lineSi6columntFfA1_
//
// NEGATIVE-NOT: sil hidden [ossa] @$s17default_arguments17testMagicLiteralsySS4file_SS8functionSi4lineSi6columntFfA2_
// https://github.com/apple/swift/issues/54034
func genericMagicLiteral<T : ExpressibleByIntegerLiteral>(_ x: T = #column) -> T { x }
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments23testGenericMagicLiteralyyF
func testGenericMagicLiteral() {
// CHECK: [[RET:%[0-9]+]] = alloc_stack $Int
// CHECK-NEXT: [[RAWLIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 35
// CHECK-NEXT: [[INTTY:%[0-9]+]] = metatype $@thin Int.Type
// CHECK-NEXT: // function_ref Swift.Int.init(_builtinIntegerLiteral: Builtin.IntLiteral) -> Swift.Int
// CHECK-NEXT: [[LITFN:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC
// CHECK-NEXT: [[LIT:%[0-9]+]] = apply [[LITFN]]([[RAWLIT]], [[INTTY]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK-NEXT: [[LITARG:%[0-9]+]] = alloc_stack $Int
// CHECK-NEXT: store [[LIT]] to [trivial] [[LITARG]] : $*Int
// CHECK-NEXT: // function_ref default_arguments.genericMagicLiteral<A where A: Swift.ExpressibleByIntegerLiteral>(A) -> A
// CHECK-NEXT: [[FN:%[0-9]+]] = function_ref @$s17default_arguments19genericMagicLiteralyxxs020ExpressibleByIntegerE0RzlF : $@convention(thin) <τ_0_0 where τ_0_0 : ExpressibleByIntegerLiteral> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK-NEXT: apply [[FN]]<Int>([[RET]], [[LITARG]]) : $@convention(thin) <τ_0_0 where τ_0_0 : ExpressibleByIntegerLiteral> (@in_guaranteed τ_0_0) -> @out τ_0_0
let _: Int = genericMagicLiteral()
}
func closure(_: () -> ()) {}
func autoclosure(_: @autoclosure () -> ()) {}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments25testCallWithMagicLiteralsyyF
// CHECK: string_literal utf8 "testCallWithMagicLiterals()"
// CHECK: string_literal utf8 "testCallWithMagicLiterals()"
// CHECK-LABEL: sil private [ossa] @$s17default_arguments25testCallWithMagicLiteralsyyFyyXEfU_
// CHECK: string_literal utf8 "testCallWithMagicLiterals()"
// CHECK-LABEL: sil private [transparent] [ossa] @$s17default_arguments25testCallWithMagicLiteralsyyFyyXEfu_
// CHECK: string_literal utf8 "testCallWithMagicLiterals()"
func testCallWithMagicLiterals() {
testMagicLiterals()
testMagicLiterals()
closure { testMagicLiterals() }
autoclosure(testMagicLiterals())
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments25testPropWithMagicLiteralsSivg
// CHECK: string_literal utf8 "testPropWithMagicLiterals"
var testPropWithMagicLiterals: Int {
testMagicLiterals()
closure { testMagicLiterals() }
autoclosure(testMagicLiterals())
return 0
}
class Foo {
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments3FooC3int6stringACSi_SStcfc : $@convention(method) (Int, @owned String, @owned Foo) -> @owned Foo
// CHECK: string_literal utf8 "init(int:string:)"
init(int: Int, string: String = #function) {
testMagicLiterals()
closure { testMagicLiterals() }
autoclosure(testMagicLiterals())
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments3FooCfd
// CHECK: string_literal utf8 "deinit"
deinit {
testMagicLiterals()
closure { testMagicLiterals() }
autoclosure(testMagicLiterals())
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments3FooCyS2icig
// CHECK: string_literal utf8 "subscript(_:)"
subscript(x: Int) -> Int {
testMagicLiterals()
closure { testMagicLiterals() }
autoclosure(testMagicLiterals())
return x
}
// CHECK-LABEL: sil private [global_init_once_fn] [ossa] @{{.*}}WZ
// CHECK: string_literal utf8 "Foo"
static let x = Foo(int:0)
}
// Test at top level.
testMagicLiterals()
closure { testMagicLiterals() }
autoclosure(testMagicLiterals())
// CHECK: string_literal utf8 "default_arguments"
let y : String = #function
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments16testSelectorCall_17withMagicLiteralsySi_SitF
// CHECK: string_literal utf8 "testSelectorCall(_:withMagicLiterals:)"
func testSelectorCall(_ x: Int, withMagicLiterals y: Int) {
testMagicLiterals()
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments32testSelectorCallWithUnnamedPieceyySi_SitF
// CHECK: string_literal utf8 "testSelectorCallWithUnnamedPiece(_:_:)"
func testSelectorCallWithUnnamedPiece(_ x: Int, _ y: Int) {
testMagicLiterals()
}
// Test default arguments in an inherited subobject initializer
class SuperDefArg {
init(int i: Int = 10) { }
}
// CHECK: sil hidden [ossa] @$s17default_arguments11SuperDefArgC3intACSi_tcfcfA_ : $@convention(thin) () -> Int
// CHECK-NOT: sil hidden [ossa] @$s17default_arguments9SubDefArgCAC3intSi_tcfcfA_ : $@convention(thin) () -> Int
class SubDefArg : SuperDefArg { }
// CHECK: sil hidden [ossa] @$s17default_arguments13testSubDefArgAA0deF0CyF : $@convention(thin) () -> @owned SubDefArg
func testSubDefArg() -> SubDefArg {
// CHECK: function_ref @$s17default_arguments11SuperDefArgC3intACSi_tcfcfA_
// CHECK: function_ref @$s17default_arguments9SubDefArgC{{[_0-9a-zA-Z]*}}fC
// CHECK: return
return SubDefArg()
}
// CHECK-NOT: sil hidden [ossa] @$s17default_arguments9SubDefArgCACSi3int_tcfcfA_ : $@convention(thin) () -> Int
// <rdar://problem/17379550>
func takeDefaultArgUnnamed(_ x: Int = 5) { }
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments25testTakeDefaultArgUnnamed{{[_0-9a-zA-Z]*}}F
func testTakeDefaultArgUnnamed(_ i: Int) {
// CHECK: bb0([[I:%[0-9]+]] : $Int):
// CHECK: [[FN:%[0-9]+]] = function_ref @$s17default_arguments21takeDefaultArgUnnamedyySiF : $@convention(thin) (Int) -> ()
// CHECK: apply [[FN]]([[I]]) : $@convention(thin) (Int) -> ()
takeDefaultArgUnnamed(i)
}
func takeDSOHandle(_ handle: UnsafeRawPointer = #dsohandle) { }
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments13testDSOHandleyyF
func testDSOHandle() {
// CHECK: [[DSO_HANDLE:%[0-9]+]] = global_addr {{@__dso_handle|@__ImageBase}} : $*Builtin.RawPointer
takeDSOHandle()
}
// Test __FUNCTION__ in an extension initializer. rdar://problem/19792181
extension SuperDefArg {
static let extensionInitializerWithClosure: Int = { return 22 }()
}
// <rdar://problem/19086357> SILGen crashes reabstracting default argument closure in members
class ReabstractDefaultArgument<T> {
init(a: (T, T) -> Bool = { _, _ in true }) {
}
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments32testDefaultArgumentReabstractionyyF
// function_ref default_arguments.ReabstractDefaultArgument.__allocating_init <A>(default_arguments.ReabstractDefaultArgument<A>.Type)(a : (A, A) -> Swift.Bool) -> default_arguments.ReabstractDefaultArgument<A>
// CHECK: [[FN:%.*]] = function_ref @$s17default_arguments25ReabstractDefaultArgument{{.*}} : $@convention(thin) <τ_0_0> () -> @owned @callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> Bool for <τ_0_0, τ_0_0>
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Int>() : $@convention(thin) <τ_0_0> () -> @owned @callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> Bool for <τ_0_0, τ_0_0>
// CHECK-NEXT: [[RESULT_CONV:%.*]] = convert_function [[RESULT]]
// CHECK-NEXT: function_ref reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Swift.Int, @in_guaranteed Swift.Int) -> (@unowned Swift.Bool) to @escaping @callee_guaranteed (@unowned Swift.Int, @unowned Swift.Int) -> (@unowned Swift.Bool)
// CHECK-NEXT: [[THUNK:%.*]] = function_ref @$sS2iSbIegnnd_S2iSbIegyyd_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Int, @in_guaranteed Int) -> Bool) -> Bool
// CHECK-NEXT: [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[RESULT_CONV]]) : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Int, @in_guaranteed Int) -> Bool) -> Bool
// CHECK-NEXT: [[CONV_FN:%.*]] = convert_escape_to_noescape [not_guaranteed] [[FN]]
// function_ref reabstraction thunk helper from @callee_guaranteed (@unowned Swift.Int, @unowned Swift.Int) -> (@unowned Swift.Bool) to @callee_guaranteed (@in_guaranteed Swift.Int, @in_guaranteed Swift.Int) -> (@unowned Swift.Bool)
// CHECK: [[THUNK:%.*]] = function_ref @$sS2iSbIgyyd_S2iSbIegnnd_TR : $@convention(thin) (@in_guaranteed Int, @in_guaranteed Int, @noescape @callee_guaranteed (Int, Int) -> Bool) -> Bool
// CHECK-NEXT: [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CONV_FN]]) : $@convention(thin) (@in_guaranteed Int, @in_guaranteed Int, @noescape @callee_guaranteed (Int, Int) -> Bool) -> Bool
// CHECK-NEXT: [[CONV_FN_0:%.*]] = convert_function [[FN]]
// CHECK-NEXT: [[CONV_FN:%.*]] = convert_escape_to_noescape [not_guaranteed] [[CONV_FN_0]]
// CHECK: [[INITFN:%[0-9]+]] = function_ref @$s17default_arguments25ReabstractDefaultArgumentC{{[_0-9a-zA-Z]*}}fC
// CHECK-NEXT: apply [[INITFN]]<Int>([[CONV_FN]],
func testDefaultArgumentReabstraction() {
_ = ReabstractDefaultArgument<Int>()
}
// <rdar://problem/20494437> SILGen crash handling default arguments
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments18r20494437onSuccessyyAA25r20494437ExecutionContext_pF
// CHECK: function_ref @$s17default_arguments19r20494437onCompleteyyAA25r20494437ExecutionContext_pF
// <rdar://problem/20494437> SILGen crash handling default arguments
protocol r20494437ExecutionContext {}
let r20494437Default: r20494437ExecutionContext
func r20494437onComplete(_ executionContext: r20494437ExecutionContext = r20494437Default) {}
func r20494437onSuccess(_ a: r20494437ExecutionContext) {
r20494437onComplete(a)
}
// <rdar://problem/18400194> Parenthesized function expression crashes the compiler
func r18400194(_ a: Int, x: Int = 97) {}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments9r18400194_1xySi_SitFfA0_
// CHECK: integer_literal $Builtin.IntLiteral, 97
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments14test_r18400194yyF
// CHECK: integer_literal $Builtin.IntLiteral, 1
// CHECK: function_ref @$s17default_arguments9r18400194_1xySi_SitFfA0_ : $@convention(thin) () -> Int
// CHECK: function_ref @$s17default_arguments9r18400194_1xySi_SitF : $@convention(thin) (Int, Int) -> (){{.*}}
func test_r18400194() {
(r18400194)(1)
}
// rdar://24242783
// Don't add capture arguments to local default argument generators.
func localFunctionWithDefaultArg() {
var z = 5
func bar(_ x: Int? = (nil)) {
z += 1
}
bar()
}
// CHECK-LABEL: sil private [ossa] @$s17default_arguments27localFunctionWithDefaultArgyyF3barL_yySiSgFfA_
// CHECK-SAME: $@convention(thin) () -> Optional<Int>
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments15throwingDefault7closureySbyKXE_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
func throwingDefault(closure: () throws -> Bool = { return true }) throws {
try _ = closure()
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments26throwingAutoclosureDefault7closureySbyKXK_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
func throwingAutoclosureDefault(closure: @autoclosure () throws -> Bool = true ) throws {
try _ = closure()
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments0A3Arg7closureySbyXE_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool
func defaultArg(closure: () -> Bool = { return true }) {
_ = closure()
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments21autoclosureDefaultArg7closureySbyXK_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool
func autoclosureDefaultArg(closure: @autoclosure () -> Bool = true ) {
_ = closure()
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments23throwingDefaultEscaping7closureySbyKc_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
func throwingDefaultEscaping(closure: @escaping () throws -> Bool = { return true }) throws {
try _ = closure()
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments34throwingAutoclosureDefaultEscaping7closureySbyKXA_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
func throwingAutoclosureDefaultEscaping(closure: @escaping @autoclosure () throws -> Bool = true ) throws {
try _ = closure()
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments0A8Escaping7closureySbyc_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool
func defaultEscaping(closure: @escaping () -> Bool = { return true }) {
_ = closure()
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments26autoclosureDefaultEscaping7closureySbyXA_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool {
func autoclosureDefaultEscaping(closure: @escaping @autoclosure () -> Bool = true ) {
_ = closure()
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}callThem{{.*}} : $@convention(thin) () -> @error any Error
// CHECK: [[F:%.*]] = function_ref @$s17default_arguments15throwingDefault7closureySbyKXE_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
// CHECK: [[C:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
// CHECK: [[E:%.*]] = convert_escape_to_noescape [not_guaranteed] [[C]]
// CHECK: [[R:%.*]] = function_ref @$s17default_arguments15throwingDefault7closureySbyKXE_tKF : $@convention(thin) (@noescape @callee_guaranteed () -> (Bool, @error any Error)) -> @error any Error
// CHECK: try_apply [[R]]([[E]])
// CHECK: [[F:%.*]] = function_ref @$s17default_arguments26throwingAutoclosureDefault7closureySbyKXK_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
// CHECK: [[C:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
// CHECK: [[E:%.*]] = convert_escape_to_noescape [not_guaranteed] [[C]]
// CHECK: [[R:%.*]] = function_ref @$s17default_arguments26throwingAutoclosureDefault7closureySbyKXK_tKF : $@convention(thin) (@noescape @callee_guaranteed () -> (Bool, @error any Error)) -> @error any Error
// CHECK: try_apply [[R]]([[E]])
// CHECK: [[F:%.*]] = function_ref @$s17default_arguments0A3Arg7closureySbyXE_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool
// CHECK: [[C:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool
// CHECK: [[E:%.*]] = convert_escape_to_noescape [not_guaranteed] [[C]]
// CHECK: [[R:%.*]] = function_ref @$s17default_arguments0A3Arg7closureySbyXE_tF : $@convention(thin) (@noescape @callee_guaranteed () -> Bool) -> ()
// CHECK: apply [[R]]([[E]])
// CHECK: [[F:%.*]] = function_ref @$s17default_arguments21autoclosureDefaultArg7closureySbyXK_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Boo
// CHECK: [[C:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool
// CHECK: [[E:%.*]] = convert_escape_to_noescape [not_guaranteed] [[C]]
// CHECK: [[R:%.*]] = function_ref @$s17default_arguments21autoclosureDefaultArg7closureySbyXK_tF : $@convention(thin) (@noescape @callee_guaranteed () -> Bool) -> ()
// CHECK: apply [[R]]([[E]])
// CHECK: [[F:%.*]] = function_ref @$s17default_arguments23throwingDefaultEscaping7closureySbyKc_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
// CHECK: [[E:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
// CHECK: [[R:%.*]] = function_ref @$s17default_arguments23throwingDefaultEscaping7closureySbyKc_tKF : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Bool, @error any Error)) -> @error any Error
// CHECK: try_apply [[R]]([[E]])
// CHECK: [[F:%.*]] = function_ref @$s17default_arguments34throwingAutoclosureDefaultEscaping7closureySbyKXA_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
// CHECK: [[E:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error any Error)
// CHECK: [[R:%.*]] = function_ref @$s17default_arguments34throwingAutoclosureDefaultEscaping7closureySbyKXA_tKF : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Bool, @error any Error)) -> @error any Error
// CHECK: try_apply [[R]]([[E]])
// CHECK: [[F:%.*]] = function_ref @$s17default_arguments0A8Escaping7closureySbyc_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool
// CHECK: [[E:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool
// CHECK: [[R:%.*]] = function_ref @$s17default_arguments0A8Escaping7closureySbyc_tF : $@convention(thin) (@guaranteed @callee_guaranteed () -> Bool) -> ()
// CHECK: apply [[R]]([[E]])
// CHECK: [[F:%.*]] = function_ref @$s17default_arguments26autoclosureDefaultEscaping7closureySbyXA_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool
// CHECK: [[E:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool
// CHECK: [[R:%.*]] = function_ref @$s17default_arguments26autoclosureDefaultEscaping7closureySbyXA_tF : $@convention(thin) (@guaranteed @callee_guaranteed () -> Bool) -> ()
// CHECK: apply [[R]]([[E]])
func callThem() throws {
try throwingDefault()
try throwingAutoclosureDefault()
defaultArg()
autoclosureDefaultArg()
try throwingDefaultEscaping()
try throwingAutoclosureDefaultEscaping()
defaultEscaping()
autoclosureDefaultEscaping()
}
func tupleDefaultArg(x: (Int, Int) = (1, 2)) {}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments19callTupleDefaultArgyyF : $@convention(thin) () -> ()
// CHECK: function_ref @$s17default_arguments15tupleDefaultArg1xySi_Sit_tFfA_ : $@convention(thin) () -> (Int, Int)
// CHECK: function_ref @$s17default_arguments15tupleDefaultArg1xySi_Sit_tF : $@convention(thin) (Int, Int) -> ()
// CHECK: return
func callTupleDefaultArg() {
tupleDefaultArg()
}
// FIXME: Should this be banned?
func stupidGames(x: Int = 3) -> Int {
return x
}
stupidGames(x:)()
func genericMagic<T : ExpressibleByStringLiteral>(x: T = #file) -> T {
return x
}
let _: String = genericMagic()
// https://github.com/apple/swift/issues/54185
struct CallableWithDefault {
func callAsFunction(x: Int = 4) {}
func callAsFunction(y: Int, z: String = #function) {}
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments23testCallableWithDefaultyyAA0deF0VF : $@convention(thin) (CallableWithDefault) -> ()
func testCallableWithDefault(_ x: CallableWithDefault) {
// CHECK: [[DEF_FN:%[0-9]+]] = function_ref @$s17default_arguments19CallableWithDefaultV14callAsFunction1xySi_tFfA_ : $@convention(thin) () -> Int
// CHECK: [[DEF:%[0-9]+]] = apply [[DEF_FN]]() : $@convention(thin) () -> Int
// CHECK: [[CALL_AS_FN:%[0-9]+]] = function_ref @$s17default_arguments19CallableWithDefaultV14callAsFunction1xySi_tF : $@convention(method) (Int, CallableWithDefault) -> ()
// CHECK: apply [[CALL_AS_FN]]([[DEF]], {{%[0-9]+}})
x()
// CHECK: [[RAW_I:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 5
// CHECK: [[I:%[0-9]+]] = apply {{%[0-9]+}}([[RAW_I]], {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [[RAW_STR:%[0-9]+]] = string_literal utf8 "testCallableWithDefault(_:)"
// CHECK: [[STR:%[0-9]+]] = apply {{%[0-9]+}}([[RAW_STR]], {{%[0-9]+}}, {{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
// CHECK: [[CALL_AS_FN:%[0-9]+]] = function_ref @$s17default_arguments19CallableWithDefaultV14callAsFunction1y1zySi_SStF : $@convention(method) (Int, @guaranteed String, CallableWithDefault) -> ()
// CHECK: apply [[CALL_AS_FN]]([[I]], [[STR]], {{%[0-9]+}})
x(y: 5)
}
enum E {
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments1EO6ResultV4name9platformsAESS_SaySiGtcfcfA0_ : $@convention(thin) () -> @owned Array<Int>
struct Result {
var name: String
var platforms: [Int] = []
}
// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments1EO4testyyFZ : $@convention(method) (@thin E.Type) -> ()
static func test() {
// CHECK: function_ref @$s17default_arguments1EO6ResultV4name9platformsAESS_SaySiGtcfcfA0_ : $@convention(thin) () -> @owned Array<Int>
// CHECK: function_ref @$s17default_arguments1EO4testyyFZAC6ResultVSS_SaySiGtcfu_ : $@convention(thin) (@guaranteed String, @guaranteed Array<Int>) -> @owned E.Result
// CHECK-LABEL: sil private [ossa] @$s17default_arguments1EO4testyyFZAC6ResultVSS_SaySiGtcfu_ : $@convention(thin) (@guaranteed String, @guaranteed Array<Int>) -> @owned E.Result
var result = Self.Result(name: "")
}
}
// FIXME: Arguably we shouldn't allow calling a constructor like this, as
// we usually require the user write an explicit '.init'.
struct WeirdUMEInitCase {
static let ty = WeirdUMEInitCase.self
init(_ x: Int = 0) {}
}
let _: WeirdUMEInitCase = .ty()
let _: WeirdUMEInitCase = .ty(5)
struct KeyPathLiteralAsFunctionDefaultArg {
var x: Int
func doStuff(with prop: (KeyPathLiteralAsFunctionDefaultArg) -> Int = \.x) {}
}
KeyPathLiteralAsFunctionDefaultArg(x: 1738).doStuff()
| apache-2.0 |
actframework/FrameworkBenchmarks | frameworks/Swift/swift-nio/Sources/swift-nio-tfb-default/main.swift | 2 | 4681 |
import Foundation
import NIO
import NIOHTTP1
struct JSONTestResponse: Encodable {
let message = "Hello, World!"
}
enum Constants {
static let httpVersion = HTTPVersion(major: 1, minor: 1)
static let serverName = "SwiftNIO"
static let plainTextResponse: StaticString = "Hello, World!"
static let plainTextResponseLength = plainTextResponse.count
static let plainTextResponseLengthString = String(plainTextResponseLength)
static let jsonResponseLength = try! JSONEncoder().encode(JSONTestResponse()).count
static let jsonResponseLengthString = String(jsonResponseLength)
}
private final class HTTPHandler: ChannelInboundHandler {
public typealias InboundIn = HTTPServerRequestPart
public typealias OutboundOut = HTTPServerResponsePart
let dateFormatter = RFC1123DateFormatter()
let jsonEncoder = JSONEncoder()
var plaintextBuffer: ByteBuffer!
var jsonBuffer: ByteBuffer!
init() {
let allocator = ByteBufferAllocator()
plaintextBuffer = allocator.buffer(capacity: Constants.plainTextResponseLength)
plaintextBuffer.write(staticString: Constants.plainTextResponse)
jsonBuffer = allocator.buffer(capacity: Constants.jsonResponseLength)
}
func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
let reqPart = self.unwrapInboundIn(data)
switch reqPart {
case .head(let request):
switch request.uri {
case "/plaintext":
processPlaintext(ctx: ctx)
case "/json":
processJSON(ctx: ctx)
default:
_ = ctx.close()
}
case .body:
break
case .end:
_ = ctx.write(self.wrapOutboundOut(.end(nil)))
}
}
func channelReadComplete(ctx: ChannelHandlerContext) {
ctx.flush()
ctx.fireChannelReadComplete()
}
private func processPlaintext(ctx: ChannelHandlerContext) {
let responseHead = plainTextResponseHead(contentLength: Constants.plainTextResponseLengthString)
ctx.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
ctx.write(self.wrapOutboundOut(.body(.byteBuffer(plaintextBuffer))), promise: nil)
}
private func processJSON(ctx: ChannelHandlerContext) {
let responseHead = jsonResponseHead(contentLength: Constants.jsonResponseLengthString)
ctx.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
let responseData = try! jsonEncoder.encode(JSONTestResponse())
jsonBuffer.clear()
jsonBuffer.write(bytes: responseData)
ctx.write(self.wrapOutboundOut(.body(.byteBuffer(jsonBuffer))), promise: nil)
}
private func jsonResponseHead(contentLength: String) -> HTTPResponseHead {
return responseHead(contentType: "application/json", contentLength: contentLength)
}
private func plainTextResponseHead(contentLength: String) -> HTTPResponseHead {
return responseHead(contentType: "text/plain", contentLength: contentLength)
}
private func responseHead(contentType: String, contentLength: String) -> HTTPResponseHead {
var headers = HTTPHeaders()
headers.replaceOrAdd(name: "content-type", value: contentType)
headers.replaceOrAdd(name: "content-length", value: contentLength)
headers.replaceOrAdd(name: "server", value: Constants.serverName)
headers.replaceOrAdd(name: "date", value: dateFormatter.getDate())
return HTTPResponseHead(version: Constants.httpVersion,
status: .ok,
headers: headers)
}
}
let group = MultiThreadedEventLoopGroup(numThreads: System.coreCount)
let bootstrap = ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.backlog, value: 8192)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_TCP), TCP_NODELAY), value: 1)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).then {
channel.pipeline.add(handler: HTTPHandler())
}
}
.childChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.childChannelOption(ChannelOptions.maxMessagesPerRead, value: 16)
.childChannelOption(ChannelOptions.recvAllocator, value: AdaptiveRecvByteBufferAllocator())
defer {
try! group.syncShutdownGracefully()
}
let channel = try! bootstrap.bind(host: "0.0.0.0", port: 8080).wait()
try! channel.closeFuture.wait()
| bsd-3-clause |
nathawes/swift | test/Driver/SourceRanges/range-incremental-no-build-record.swift | 4 | 2704 | // Check behavior with no build record.
//
// =============================================================================
// First, build without range dependencies with no new options.
// =============================================================================
// REQUIRES: executable_test
// Copy in the inputs.
// The lack of a build record or swiftdeps files should disable incremental compilation
// Ensure that the extra outputs are not generated when they should not be:
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/range-incremental-no-build-record/* %t
// RUN: cd %t && %target-swiftc_driver -output-file-map %t/output.json -incremental -enable-batch-mode ./main.swift ./fileA.swift ./fileB.swift -module-name main -j2 -driver-show-job-lifecycle -driver-show-incremental >& %t/output0
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-NO-BUILD-REC %s < %t/output0
// CHECK-NO-BUILD-REC: Incremental compilation could not read build record.
// RUN: ls %t | %FileCheck -check-prefix=CHECK-NO-RANGE-OUTPUTS %s
// CHECK-NO-RANGE-OUTPUTS-NOT: .swiftranges
// CHECK-NO-RANGE-OUTPUTS-NOT: .compiledsource
// CHECK-NO-RANGE-OUTPUTS: .swiftdeps
// CHECK-NO-RANGE-OUTPUTS-NOT: .swiftranges
// CHECK-NO-RANGE-OUTPUTS-NOT: .compiledsource
// RUN: %FileCheck -check-prefix=CHECK-HAS-BATCHES %s < %t/output0
// CHECK-HAS-BATCHES: Batchable: {compile:
// RUN: %target-run %t/main | tee run0 | grep Any > /dev/null && rm %t/main
// =============================================================================
// Same, except force the driver to compute both strategies via -driver-compare-incremental-schemes
// =============================================================================
// Copy in the inputs.
// The lack of a build record or swiftdeps files should disable incremental compilation
// Ensure that the extra outputs are not generated when they should not be:
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/range-incremental-no-build-record/* %t
// RUN: cd %t && %target-swiftc_driver -driver-compare-incremental-schemes -output-file-map %t/output.json -incremental -enable-batch-mode ./main.swift ./fileA.swift ./fileB.swift -module-name main -j2 -driver-show-job-lifecycle -driver-show-incremental >& %t/output1
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-NO-BUILD-REC %s < %t/output1
// RUN: %FileCheck -match-full-lines -check-prefix=CHECK-COMPARE-DISABLED-NO-BUILD-RECORD %s < %t/output1
// CHECK-COMPARE-DISABLED-NO-BUILD-RECORD: *** Incremental build disabled because could not read build record, cannot compare ***
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | tee run1 | grep Any > /dev/null && rm %t/main
| apache-2.0 |
Legoless/iOS-Course | 2015-1/Lesson8/Gamebox/Gamebox/ViewController.swift | 2 | 2151 | //
// ViewController.swift
// Gamebox
//
// Created by Dal Rupnik on 21/10/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, ImageViewControllerDelegate {
let manager = GameManager.shared
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var priorityTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
resultLabel.text = "Click to add game!"
nameTextField.delegate = self
priorityTextField.delegate = self
if let gameName = NSUserDefaults.standardUserDefaults().objectForKey("GameName") as? String {
nameTextField.text = gameName
}
}
func textFieldDidEndEditing(textField: UITextField) {
print("ENDED EDITING")
if (textField == self.nameTextField)
{
print ("NAME ENDED")
}
}
@IBAction func addGameButtonTap(sender: UIButton) {
if let name = nameTextField.text, priority = UInt(priorityTextField.text!) where name.characters.count > 0 {
let game = Game(name: name, priority: priority)
manager.games.append(game)
resultLabel.text = "Added! There are \(manager.games.count) games in database!"
resultLabel.textColor = UIColor.blackColor()
GameManager.shared.save()
}
else {
resultLabel.text = "Verify your data!"
resultLabel.textColor = UIColor.redColor()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ImageSegue" {
let viewController = segue.destinationViewController as! ImageViewController
viewController.delegate = self
}
}
func imageViewControllerDidFinish(imageViewController: ImageViewController) {
imageViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit |
mitchellporter/ios-animations | Animation/TabBar/TabBarExampleAnimatedTransitioning.swift | 2 | 2475 | import UIKit
/*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
This licensed material is licensed under the Apache 2.0 license. http://www.apache.org/licenses/LICENSE-2.0.
*/
class TabBarExampleAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
var isPresenting = false
let fromIndex: Int
let toIndex: Int
let animMultiplier: Double = 1.0
init(fromIndex: Int, toIndex: Int) {
self.fromIndex = fromIndex
self.toIndex = toIndex
super.init()
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.4
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let to = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! as UIViewController
let from = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! as UIViewController
let container = transitionContext.containerView()
let duration = transitionDuration(transitionContext)
container.addSubview(to.view)
var direction = toIndex > fromIndex ? CGFloat(-1) : CGFloat(1)
if let toPeople = to as? TabBarPeopleViewController {
to.view.transform = CGAffineTransformMakeTranslation(0, to.view.bounds.height)
} else if let fromPeople = from as? TabBarPeopleViewController {
to.view.alpha = 1.0
container.addSubview(from.view)
} else {
from.view.alpha = 1.0
to.view.alpha = 0.0
}
UIView.animateWithDuration(animMultiplier * transitionDuration(transitionContext), delay: animMultiplier * 0.0, options: nil, animations: { () -> Void in
to.view.alpha = 1.0
to.view.transform = CGAffineTransformIdentity
if let fromPeople = from as? TabBarPeopleViewController {
fromPeople.view.transform = CGAffineTransformMakeTranslation(0, from.view.bounds.height)
}
}) { finished in
to.view.transform = CGAffineTransformIdentity
from.view.transform = CGAffineTransformIdentity
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
}
| apache-2.0 |
szk-atmosphere/SAParallaxViewControllerSwift | SAParallaxViewControllerSwiftExample/SAParallaxViewControllerSwiftExample/AppDelegate.swift | 1 | 2207 | //
// AppDelegate.swift
// SAParallaxViewControllerSwiftExample
//
// Created by 鈴木大貴 on 2015/01/30.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
sschiau/swift | test/Driver/loaded_module_trace_header.swift | 15 | 1382 | // RUN: rm -f %t
// RUN: env SWIFT_LOADED_MODULE_TRACE_FILE=%t %target-build-swift -module-name loaded_module_trace_header -c %s -o- -import-objc-header %S/Inputs/loaded_module_trace_header.h > /dev/null
// RUN: %FileCheck %s < %t
// REQUIRES: objc_interop
// CHECK: {
// CHECK: "name":"loaded_module_trace_header"
// CHECK: "arch":"{{[^"]*}}"
// CHECK: "swiftmodules":[
// CHECK-DAG: "{{[^"]*}}/ObjectiveC.swiftmodule{{(\\/[^"]+[.]swiftmodule)?}}"
// CHECK-DAG: "{{[^"]*}}/Dispatch.swiftmodule{{(\\/[^"]+[.]swiftmodule)?}}"
// CHECK-DAG: "{{[^"]*}}/Darwin.swiftmodule{{(\\/[^"]+[.]swiftmodule)?}}"
// CHECK-DAG: "{{[^"]*}}/Foundation.swiftmodule{{(\\/[^"]+[.]swiftmodule)?}}"
// CHECK-DAG: "{{[^"]*}}/Swift.swiftmodule{{(\\/[^"]+[.]swiftmodule)?}}"
// CHECK-DAG: "{{[^"]*}}/SwiftOnoneSupport.swiftmodule{{(\\/[^"]+[.]swiftmodule)?}}"
// CHECK: ]
// CHECK: "swiftmodulesDetailedInfo":[
// CHECK: {
// CHECK-DAG: "name":"Swift"
// CHECK-DAG: "path":"{{[^"]*\\[/\\]}}Swift.swiftmodule{{(\\[/\\][^"]+[.]swiftmodule)?}}"
// CHECK-DAG: "isImportedDirectly":true
// CHECK-DAG: "supportsLibraryEvolution":true
// CHECK: }
// CHECK: {
// CHECK-DAG: "name":"SwiftOnoneSupport"
// CHECK-DAG: "path":"{{[^"]*\\[/\\]}}SwiftOnoneSupport.swiftmodule{{(\\[/\\][^"]+[.]swiftmodule)?}}"
// CHECK-DAG: "isImportedDirectly":true
// CHECK-DAG: "supportsLibraryEvolution":true
// CHECK: }
// CHECK: ]
| apache-2.0 |
zapdroid/RXWeather | Pods/Nimble/Sources/Nimble/Adapters/NMBObjCMatcher.swift | 1 | 3358 | import Foundation
#if _runtime(_ObjC)
public typealias MatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage) -> Bool
public typealias FullMatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage, _ shouldNotMatch: Bool) -> Bool
public class NMBObjCMatcher: NSObject, NMBMatcher {
let _match: MatcherBlock
let _doesNotMatch: MatcherBlock
let canMatchNil: Bool
public init(canMatchNil: Bool, matcher: @escaping MatcherBlock, notMatcher: @escaping MatcherBlock) {
self.canMatchNil = canMatchNil
self._match = matcher
self._doesNotMatch = notMatcher
}
public convenience init(matcher: @escaping MatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping MatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: matcher, notMatcher: ({ actualExpression, failureMessage in
!matcher(actualExpression, failureMessage)
}))
}
public convenience init(matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: ({ actualExpression, failureMessage in
matcher(actualExpression, failureMessage, false)
}), notMatcher: ({ actualExpression, failureMessage in
matcher(actualExpression, failureMessage, true)
}))
}
private func canMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
do {
if !canMatchNil {
if try actualExpression.evaluate() == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
return false
}
}
} catch let error {
failureMessage.actualValue = "an unexpected error thrown: \(error)"
return false
}
return true
}
public func matches(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result = _match(
expr,
failureMessage)
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
public func doesNotMatch(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result = _doesNotMatch(
expr,
failureMessage)
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
}
#endif
| mit |
practicalswift/swift | stdlib/public/core/StringUTF8View.swift | 1 | 16574 | //===--- StringUTF8.swift - A UTF8 view of String -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to
// allow performance optimizations of linear traversals.
extension String {
/// A view of a string's contents as a collection of UTF-8 code units.
///
/// You can access a string's view of UTF-8 code units by using its `utf8`
/// property. A string's UTF-8 view encodes the string's Unicode scalar
/// values as 8-bit integers.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.utf8 {
/// print(v)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 240
/// // 159
/// // 146
/// // 144
///
/// A string's Unicode scalar values can be up to 21 bits in length. To
/// represent those scalar values using 8-bit integers, more than one UTF-8
/// code unit is often required.
///
/// let flowermoji = "💐"
/// for v in flowermoji.unicodeScalars {
/// print(v, v.value)
/// }
/// // 💐 128144
///
/// for v in flowermoji.utf8 {
/// print(v)
/// }
/// // 240
/// // 159
/// // 146
/// // 144
///
/// In the encoded representation of a Unicode scalar value, each UTF-8 code
/// unit after the first is called a *continuation byte*.
///
/// UTF8View Elements Match Encoded C Strings
/// =========================================
///
/// Swift streamlines interoperation with C string APIs by letting you pass a
/// `String` instance to a function as an `Int8` or `UInt8` pointer. When you
/// call a C function using a `String`, Swift automatically creates a buffer
/// of UTF-8 code units and passes a pointer to that buffer. The code units
/// of that buffer match the code units in the string's `utf8` view.
///
/// The following example uses the C `strncmp` function to compare the
/// beginning of two Swift strings. The `strncmp` function takes two
/// `const char*` pointers and an integer specifying the number of characters
/// to compare. Because the strings are identical up to the 14th character,
/// comparing only those characters results in a return value of `0`.
///
/// let s1 = "They call me 'Bell'"
/// let s2 = "They call me 'Stacey'"
///
/// print(strncmp(s1, s2, 14))
/// // Prints "0"
/// print(String(s1.utf8.prefix(14)))
/// // Prints "They call me '"
///
/// Extending the compared character count to 15 includes the differing
/// characters, so a nonzero result is returned.
///
/// print(strncmp(s1, s2, 15))
/// // Prints "-17"
/// print(String(s1.utf8.prefix(15)))
/// // Prints "They call me 'B"
@_fixed_layout
public struct UTF8View {
@usableFromInline
internal var _guts: _StringGuts
@inlinable @inline(__always)
internal init(_ guts: _StringGuts) {
self._guts = guts
_invariantCheck()
}
}
}
extension String.UTF8View {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
// TODO: Ensure index alignment
}
#endif // INTERNAL_CHECKS_ENABLED
}
extension String.UTF8View: BidirectionalCollection {
public typealias Index = String.Index
public typealias Element = UTF8.CodeUnit
/// The position of the first code unit if the UTF-8 view is
/// nonempty.
///
/// If the UTF-8 view is empty, `startIndex` is equal to `endIndex`.
@inlinable
public var startIndex: Index {
@inline(__always) get { return _guts.startIndex }
}
/// The "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// In an empty UTF-8 view, `endIndex` is equal to `startIndex`.
@inlinable
public var endIndex: Index {
@inline(__always) get { return _guts.endIndex }
}
/// Returns the next consecutive position after `i`.
///
/// - Precondition: The next position is representable.
@inlinable @inline(__always)
public func index(after i: Index) -> Index {
if _fastPath(_guts.isFastUTF8) {
return i.nextEncoded
}
return _foreignIndex(after: i)
}
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
precondition(!i.isZeroPosition)
if _fastPath(_guts.isFastUTF8) {
return i.priorEncoded
}
return _foreignIndex(before: i)
}
@inlinable @inline(__always)
public func index(_ i: Index, offsetBy n: Int) -> Index {
if _fastPath(_guts.isFastUTF8) {
_precondition(n + i._encodedOffset <= _guts.count)
return i.encoded(offsetBy: n)
}
return _foreignIndex(i, offsetBy: n)
}
@inlinable @inline(__always)
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
if _fastPath(_guts.isFastUTF8) {
// Check the limit: ignore limit if it precedes `i` (in the correct
// direction), otherwise must not be beyond limit (in the correct
// direction).
let iOffset = i._encodedOffset
let result = iOffset + n
let limitOffset = limit._encodedOffset
if n >= 0 {
guard limitOffset < iOffset || result <= limitOffset else { return nil }
} else {
guard limitOffset > iOffset || result >= limitOffset else { return nil }
}
return Index(_encodedOffset: result)
}
return _foreignIndex(i, offsetBy: n, limitedBy: limit)
}
@inlinable @inline(__always)
public func distance(from i: Index, to j: Index) -> Int {
if _fastPath(_guts.isFastUTF8) {
return j._encodedOffset &- i._encodedOffset
}
return _foreignDistance(from: i, to: j)
}
/// Accesses the code unit at the given position.
///
/// The following example uses the subscript to print the value of a
/// string's first UTF-8 code unit.
///
/// let greeting = "Hello, friend!"
/// let i = greeting.utf8.startIndex
/// print("First character's UTF-8 code unit: \(greeting.utf8[i])")
/// // Prints "First character's UTF-8 code unit: 72"
///
/// - Parameter position: A valid index of the view. `position`
/// must be less than the view's end index.
@inlinable
public subscript(i: Index) -> UTF8.CodeUnit {
@inline(__always) get {
String(_guts)._boundsCheck(i)
if _fastPath(_guts.isFastUTF8) {
return _guts.withFastUTF8 { utf8 in utf8[_unchecked: i._encodedOffset] }
}
return _foreignSubscript(position: i)
}
}
}
extension String.UTF8View: CustomStringConvertible {
@inlinable
public var description: String {
@inline(__always) get { return String(String(_guts)) }
}
}
extension String.UTF8View: CustomDebugStringConvertible {
public var debugDescription: String {
return "UTF8View(\(self.description.debugDescription))"
}
}
extension String {
/// A UTF-8 encoding of `self`.
@inlinable
public var utf8: UTF8View {
@inline(__always) get { return UTF8View(self._guts) }
set { self = String(newValue._guts) }
}
/// A contiguously stored null-terminated UTF-8 representation of the string.
///
/// To access the underlying memory, invoke `withUnsafeBufferPointer` on the
/// array.
///
/// let s = "Hello!"
/// let bytes = s.utf8CString
/// print(bytes)
/// // Prints "[72, 101, 108, 108, 111, 33, 0]"
///
/// bytes.withUnsafeBufferPointer { ptr in
/// print(strlen(ptr.baseAddress!))
/// }
/// // Prints "6"
public var utf8CString: ContiguousArray<CChar> {
if _fastPath(_guts.isFastUTF8) {
var result = _guts.withFastCChar { ContiguousArray($0) }
result.append(0)
return result
}
return _slowUTF8CString()
}
@usableFromInline @inline(never) // slow-path
internal func _slowUTF8CString() -> ContiguousArray<CChar> {
var result = ContiguousArray<CChar>()
result.reserveCapacity(self._guts.count + 1)
for c in self.utf8 {
result.append(CChar(bitPattern: c))
}
result.append(0)
return result
}
/// Creates a string corresponding to the given sequence of UTF-8 code units.
@available(swift, introduced: 4.0, message:
"Please use failable String.init?(_:UTF8View) when in Swift 3.2 mode")
@inlinable @inline(__always)
public init(_ utf8: UTF8View) {
self = String(utf8._guts)
}
}
extension String.UTF8View {
@inlinable
public var count: Int {
@inline(__always) get {
if _fastPath(_guts.isFastUTF8) {
return _guts.count
}
return _foreignCount()
}
}
}
// Index conversions
extension String.UTF8View.Index {
/// Creates an index in the given UTF-8 view that corresponds exactly to the
/// specified `UTF16View` position.
///
/// The following example finds the position of a space in a string's `utf16`
/// view and then converts that position to an index in the string's
/// `utf8` view.
///
/// let cafe = "Café 🍵"
///
/// let utf16Index = cafe.utf16.firstIndex(of: 32)!
/// let utf8Index = String.UTF8View.Index(utf16Index, within: cafe.utf8)!
///
/// print(Array(cafe.utf8[..<utf8Index]))
/// // Prints "[67, 97, 102, 195, 169]"
///
/// If the position passed in `utf16Index` doesn't have an exact
/// corresponding position in `utf8`, the result of the initializer is
/// `nil`. For example, because UTF-8 and UTF-16 represent high Unicode code
/// points differently, an attempt to convert the position of the trailing
/// surrogate of a UTF-16 surrogate pair fails.
///
/// The next example attempts to convert the indices of the two UTF-16 code
/// points that represent the teacup emoji (`"🍵"`). The index of the lead
/// surrogate is successfully converted to a position in `utf8`, but the
/// index of the trailing surrogate is not.
///
/// let emojiHigh = cafe.utf16.index(after: utf16Index)
/// print(String.UTF8View.Index(emojiHigh, within: cafe.utf8))
/// // Prints "Optional(String.Index(...))"
///
/// let emojiLow = cafe.utf16.index(after: emojiHigh)
/// print(String.UTF8View.Index(emojiLow, within: cafe.utf8))
/// // Prints "nil"
///
/// - Parameters:
/// - sourcePosition: A position in a `String` or one of its views.
/// - target: The `UTF8View` in which to find the new position.
@inlinable
public init?(_ idx: String.Index, within target: String.UTF8View) {
if _slowPath(target._guts.isForeign) {
guard idx._foreignIsWithin(target) else { return nil }
} else {
// All indices, except sub-scalar UTF-16 indices pointing at trailing
// surrogates, are valid.
guard idx.transcodedOffset == 0 else { return nil }
}
self = idx
}
}
// Reflection
extension String.UTF8View : CustomReflectable {
/// Returns a mirror that reflects the UTF-8 view of a string.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
//===--- Slicing Support --------------------------------------------------===//
/// In Swift 3.2, in the absence of type context,
///
/// someString.utf8[someString.utf8.startIndex..<someString.utf8.endIndex]
///
/// was deduced to be of type `String.UTF8View`. Provide a more-specific
/// Swift-3-only `subscript` overload that continues to produce
/// `String.UTF8View`.
extension String.UTF8View {
public typealias SubSequence = Substring.UTF8View
@inlinable
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> String.UTF8View.SubSequence {
return Substring.UTF8View(self, _bounds: r)
}
}
extension String.UTF8View {
/// Copies `self` into the supplied buffer.
///
/// - Precondition: The memory in `self` is uninitialized. The buffer must
/// contain sufficient uninitialized memory to accommodate
/// `source.underestimatedCount`.
///
/// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]`
/// are initialized.
@inlinable @inline(__always)
public func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Iterator.Element>
) -> (Iterator, UnsafeMutableBufferPointer<Iterator.Element>.Index) {
guard buffer.baseAddress != nil else {
_preconditionFailure(
"Attempt to copy string contents into nil buffer pointer")
}
guard let written = _guts.copyUTF8(into: buffer) else {
_preconditionFailure(
"Insufficient space allocated to copy string contents")
}
let it = String().utf8.makeIterator()
return (it, buffer.index(buffer.startIndex, offsetBy: written))
}
}
// Foreign string support
extension String.UTF8View {
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(after i: Index) -> Index {
_internalInvariant(_guts.isForeign)
let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar(
startingAt: i.strippingTranscoding)
let utf8Len = _numUTF8CodeUnits(scalar)
if utf8Len == 1 {
_internalInvariant(i.transcodedOffset == 0)
return i.nextEncoded
}
// Check if we're still transcoding sub-scalar
if i.transcodedOffset < utf8Len - 1 {
return i.nextTranscoded
}
// Skip to the next scalar
return i.encoded(offsetBy: scalarLen)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(before i: Index) -> Index {
_internalInvariant(_guts.isForeign)
if i.transcodedOffset != 0 {
_internalInvariant((1...3) ~= i.transcodedOffset)
return i.priorTranscoded
}
let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar(
endingAt: i)
let utf8Len = _numUTF8CodeUnits(scalar)
return i.encoded(offsetBy: -scalarLen).transcoded(withOffset: utf8Len &- 1)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignSubscript(position i: Index) -> UTF8.CodeUnit {
_internalInvariant(_guts.isForeign)
let scalar = _guts.foreignErrorCorrectedScalar(
startingAt: _guts.scalarAlign(i)).0
let encoded = Unicode.UTF8.encode(scalar)._unsafelyUnwrappedUnchecked
_internalInvariant(i.transcodedOffset < 1+encoded.count)
return encoded[
encoded.index(encoded.startIndex, offsetBy: i.transcodedOffset)]
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(_ i: Index, offsetBy n: Int) -> Index {
_internalInvariant(_guts.isForeign)
return _index(i, offsetBy: n)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
_internalInvariant(_guts.isForeign)
return _index(i, offsetBy: n, limitedBy: limit)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignDistance(from i: Index, to j: Index) -> Int {
_internalInvariant(_guts.isForeign)
return _distance(from: i, to: j)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignCount() -> Int {
_internalInvariant(_guts.isForeign)
return _distance(from: startIndex, to: endIndex)
}
}
extension String.Index {
@usableFromInline @inline(never) // opaque slow-path
@_effects(releasenone)
internal func _foreignIsWithin(_ target: String.UTF8View) -> Bool {
_internalInvariant(target._guts.isForeign)
// Currently, foreign means UTF-16.
// If we're transcoding, we're already a UTF8 view index.
if self.transcodedOffset != 0 { return true }
// Otherwise, we must be scalar-aligned, i.e. not pointing at a trailing
// surrogate.
return target._guts.isOnUnicodeScalarBoundary(self)
}
}
extension String.UTF8View {
@inlinable
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
guard _guts.isFastUTF8 else { return nil }
return try _guts.withFastUTF8(body)
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.